我试图让android应用程序在崩溃时重启,但我无法让它正常工作。你能帮帮我吗?
这是应用程序代码。希望你能帮助我:
主要活动:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this));
if (getIntent().getBooleanExtra("crash", false)) {
Log.d("Test","Restart after crash");
}
}
}
myapplication.java
public class MyApplication extends Application {
public static MyApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
@Override
public Context getApplicationContext() {
return super.getApplicationContext();
}
public static MyApplication getInstance() {
return instance;
}
}
myexceptionhandler:
public class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
private Activity activity;
public MyExceptionHandler(Activity a) {
activity = a;
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
Intent intent = new Intent(activity, MainActivity.class);
intent.putExtra("crash", true);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(MyApplication.getInstance().getBaseContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager mgr = (AlarmManager) MyApplication.getInstance().getBaseContext().getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000, pendingIntent);
Log.d("Test","exit my way");
activity.finish();
System.exit(2);
}
}
这是我从adb外壳得到的警报
RTC_WAKEUP #0: Alarm{c22bdfd type 0 when 1627381079029 ro.xxxx.appwithrestart}
tag=*walarm*:ro.xxxx.appwithrestart/.MainActivity
operation=PendingIntent{56be29a: PendingIntentRecord{9be2a45 ro.xxxx.appwithrestart startActivity (whitelist: e045cfd:+30s0ms)}}
(appsync)ro.x.appwithrestart/0
报警触发后:
ro.xxxx.appwithrestart, u0: -3s669ms,
u0a298:ro.xxxx.appwithrestart +35ms running, 1 wakeups:
*walarm*:ro.xxxx.appwithrestart/.MainActivity
(AppSync) ro.xxxx.appwithrestart/0
但是应用程序没有启动。
暂无答案!
目前还没有任何答案,快来回答吧!