1、自定义UncaughtExceptionHandler
1 public class UnCeHandler implements UncaughtExceptionHandler { 2 3 private Thread.UncaughtExceptionHandler mDefaultHandler; 4 public final String TAG = "CatchExcep"; 5 CatchExcApplication application; 6 7 public UnCeHandler(CatchExcApplication application) { 8 // 获取系统默认的UncaughtException处理器 9 mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); 10 this.application = application; 11 } 12 13 @Override 14 public void uncaughtException(Thread thread, Throwable ex) { 15 if (!handleException(ex) && mDefaultHandler != null) { 16 // 如果用户没有处理则让系统默认的异常处理器来处理 17 mDefaultHandler.uncaughtException(thread, ex); 18 } else { 19 try { 20 Thread.sleep(2000); 21 } catch (InterruptedException e) { 22 Log.e(TAG, "error : ", e); 23 } 24 Intent intent = new Intent(application.getApplicationContext(),MainActivity.class); 25 PendingIntent restartIntent = PendingIntent.getActivity( 26 application.getApplicationContext(), 0, intent, 27 Intent.FLAG_ACTIVITY_NEW_TASK); 28 // 退出程序 29 AlarmManager mgr = (AlarmManager) application.getSystemService(Context.ALARM_SERVICE); 30 mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,restartIntent); // 1秒钟后重启应用 31 application.finishActivity(); 32 } 33 } 34 35 /** 36 * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. 37 * 38 * @param ex 39 * @return true:如果处理了该异常信息;否则返回false. 40 */ 41 private boolean handleException(Throwable ex) { 42 if (ex == null) { 43 return false; 44 } 45 // 使用Toast来显示异常信息 46 new Thread() { 47 @Override 48 public void run() { 49 Looper.prepare(); 50 Toast.makeText(application.getApplicationContext(),"很抱歉,程序出现异常,即将退出.", Toast.LENGTH_SHORT).show(); 51 Looper.loop(); 52 } 53 }.start(); 54 return true; 55 }
2、自定义Application
1 public class CatchExcApplication extends Application { 2 3 ArrayList<Activity> list = new ArrayList<Activity>(); 4 5 public CatchExcApplication() 6 { 7 //设置该CrashHandler为程序的默认处理器 8 Thread.setDefaultUncaughtExceptionHandler(new UnCeHandler(this)); 9 } 10 11 14 15 /** 16 * Activity关闭时,删除Activity列表中的Activity对象*/ 17 public void removeActivity(Activity a){ 18 list.remove(a); 19 } 20 21 /** 22 * 向Activity列表中添加Activity对象*/ 23 public void addActivity(Activity a){ 24 list.add(a); 25 } 26 27 /** 28 * 关闭Activity列表中的所有Activity*/ 29 public void finishActivity(){ 30 for (Activity activity : list) { 31 if (null != activity) { 32 activity.finish(); 33 } 34 } 35 //杀死该应用进程 36 android.os.Process.killProcess(android.os.Process.myPid()); 37 } 38 }
3、配置AndroidManifest.xml
1 <application 2 android:name="com.hht.restartdemo.CatchExcApplication" 3 android:allowBackup="true" 4 android:icon="@drawable/ic_launcher" 5 android:label="@string/app_name" 6 android:theme="@style/AppTheme" > 7 <activity 8 android:name="com.hht.restartdemo.MainActivity" 9 android:label="@string/app_name" > 10 <intent-filter> 11 <action android:name="android.intent.action.MAIN" /> 12 13 <category android:name="android.intent.category.LAUNCHER" /> 14 </intent-filter> 15 </activity> 16 </application>