Is there a way for my to program my app to automatically restart itself whenever it crashes? My app is just a simple media rendering App, however it occasionally crashes ( it's supposed to ). Is this at all possible? Thanks. My code looks like this
public void Play(){ if(mp != null) {
mp.reset();
mp.release();
mp = null;
}
AudioRenderer mr = new AudioRenderer();
mp = mr.AudioRenderer(filePath);
}
private class AudioRenderer extends Activity {
private MediaPlayer AudioRenderer(String filePath) {
File location = new File(filePath);
Uri path = Uri.fromFile(location);
mp= MediaPlayer.create(this, path);
}
return mp
}
This example demonstrates how do I programmatically “restart” an Android app. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
this will do the job for you.
How to start the automatically stopped android service?
still i don't understand why it is supposed to crash.
UPDATE
you create an handler for uncaught exception
private Thread.UncaughtExceptionHandler onRuntimeError= new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread thread, Throwable ex) {
//Try starting the Activity again
};
in your on create, you register an handler for uncaught exception
@Override
protected void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(onRuntimeError);
}
I might be late a lot, but I found 2 in 1 solution for your problem.
public void doRestart() {
Intent mStartActivity = new Intent(context, LoginActivity.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
}
private void appInitialization() {
defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
}
//make crash report on ex.stackreport
private Thread.UncaughtExceptionHandler defaultUEH;
// handler listener
private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
ex.printStackTrace();
doRestart();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_index);
appInitialization();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With