My application needs restart itself after catching some bad exception. question is how to restart my application it self ?
Context::finish() can just remove activity in stack top, NOT able to bring new created main activity to top
My application needs restart itself after catching some bad exception. question is how to restart my application it self ?
Context::finish() can just remove activity in stack top, NOT able to bring new created main activity to top
If restarting your application basically means start your LAUNCHER activity then you can simply start a new intent for your first activity with following flags :
homeActivity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
Killing an app due to a raised exception is easy: just fo not catch() it away.
Android will respond to an uncaught exception by killing your app.
if you do catch these bad exception, simply make sure you re-through them after processing:
class doSomething() {
try {
do something risky
} catch (AdError e)
record error to log , or notify server
throw e; // <------- and rethrow the exception
}
}
But you wanted app restart, which also involves starting your app back again.
This is, frankly, a tricky thing, and most apps do not do it!
But if I had to figure out an app restart scheme it would probably work like this:
Finally - A simple crash detector:
class MyFirstActivity {
void onCreate() {
other staff....
SharedPreferences preferences = getSharedPreferences("CRASH_INDICATOR", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("HAD_CRASHED", true); // <------------ mark as crashed
editor.commit();
}
}
class MyLastActivity {
void onStop() { // <----------------- app is now gracefully closing
other staff....
SharedPreferences preferences = getSharedPreferences("CRASH_INDICATOR",MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("HAD_CRASHED", false); // <------------ mark as NOT crashed
editor.commit();
}
}
class Alarmreceiver { // <----- check whether app had crashed in prior run and, if so, react
onReceive() {
SharedPreferences preferences = getSharedPreferences("CRASH_INDICATOR", MODE_PRIVATE);
boolean hadCrashed = preferences.getBoolean("HAD_CRASHED", false);
if (hadCrashed ) {
handle....
}
}
}