如何在Android程序Force Closed后自动重启

在开发Android程序中,都会或多或少的遇到程序被Force Closed,那么如何让程序在Force Closed后自动重启呢?可以通过以下两部来简单实现:
1、在Activity的onCreate方法里初始化一个PendingIntent,你可以在intent中put一个针对crash的code,这样下次Activity启动后,就可以通过get code来判断是否是restart,以此来做一些事情。

Intent intent = getIntent();
int code = intent.getIntExtra(RESTART_INTENT_KEY, 0);

if (CRASHED_CODE == code)
{
    /** You can do something here. */   
    Log.d(TAG, "So sorry that the application crashed.");
}

intent.putExtra(RESTART_INTENT_KEY, CRASHED_CODE);
m_restartIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);

2、为当前Activity的Thread设置一个UncaughtExceptionHandler,当某个Thread因为未捕获的异常而终止的时候会回调到它,这样只需要在uncaughtException(Thread thread, Throwable ex)方法的实现中,设置一个alarm来启动程序,如下边代码,程序将会在Crash 3秒后自动重启。

private UncaughtExceptionHandler m_handler = new UncaughtExceptionHandler()
{
    @Override
    public void uncaughtException(Thread thread, Throwable ex)
    {
        Log.d(TAG, "uncaught exception is catched!");
        AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 3000, m_restartIntent);
        System.exit(2);
    }
};
Thread.setDefaultUncaughtExceptionHandler(m_handler);

当然如果你觉得你的application在Force Closed后,自动重启并不是一个最佳的选择,也可以利用上述代码在程序Force Closed后保存一些程序Crash的Log,以便在以后的版本中修复Bug。