在Android应用开发中,偶尔会因为某些异常导致正在使用的应用出现异常并强制关闭,这样导致不友好的用户体验。为了解决这个问题,我们需要捕获出现的异常并做处理。
下文介绍程序崩溃后,一秒钟重启。
package com.lza.library.activity;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
public class HKApplication extends Application {//implements Thread.UncaughtExceptionHandler {
PendingIntent restartIntent;
@Override
public void onCreate() {
super.onCreate();
// 以下用来捕获程序崩溃异常
Intent intent = new Intent();
// 参数1:包名,参数2:程序入口的activity
intent.setClassName("com.lza.library", "com.lza.library.activity.MainActivity");
restartIntent = PendingIntent.getActivity(getApplicationContext(), 0,
intent, Intent.FLAG_ACTIVITY_NEW_TASK);
Thread.setDefaultUncaughtExceptionHandler(restartHandler); // 程序崩溃时触发线程
}
public UncaughtExceptionHandler restartHandler = new UncaughtExceptionHandler() {
public void uncaughtException(Thread thread, Throwable ex) {
AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
restartIntent); // 1秒钟后重启应用
new ActivityContrl().finishProgram(); // 自定义方法,关闭当前打开的所有avtivity
}
};
public class ActivityContrl {
private List<Activity> activityList = new ArrayList<Activity>();
public void remove(Activity activity) {
activityList.remove(activity);
}
public void add(Activity activity) {
activityList.add(activity);
}
public void finishProgram() {
for (Activity activity : activityList) {
if (null != activity) {
activity.finish();
}
}
android.os.Process.killProcess(android.os.Process.myPid());
}
}
//
// @Override
// public void onCreate() {
// super.onCreate();
// //设置Thread Exception Handler
// Thread.setDefaultUncaughtExceptionHandler(this);
// }
//
// public void uncaughtException(Thread thread, Throwable ex) {
// System.out.println("uncaughtException");
// System.exit(0);
// Intent intent = new Intent(this, MainActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
// Intent.FLAG_ACTIVITY_NEW_TASK);
// startActivity(intent);
// }
}
将manifest中的app的name改为自定义的:
<application
android:allowBackup="true"
android:label="@string/AppName"
android:theme="@style/AppTheme"
android:name=".activity.HKApplication"> 后面的代码省略--------------------------