一般对于Java的错误,会有一个try...catch...程序块或者抛出来进行处理,但是一个应用程序代码这么多,往往不能将所有错误都处理掉,此时的错误就是未捕捉的错误,这些错误可能会导致程序的崩溃,对此,Java提供了一个接口UncaughtExceptionHandler来处理这个问题。
可以创建一个类HandlerException继承Application,并且实现UncaughtExceptionHandler,在这个类中必须重写uncaughtException(Thread thread, Throwable ex)。可以写一个辅助方法handlerException(Throwable ex)方法,进行错误的处理,代码如下:
private boolean handleException(Throwable ex){
if (ex == null){
return false;
}
new Thread(){
@Override
public void run(){
Looper.prepare();
.../*你的处理方法的实现*/
Looper.loop();
}
}.start();
return true;
}
此方法实现你所需要做的处理,如处理了异常,返回true;若是没有处理返回false。
HandlerException类如下:
public class HandlerException extends Application implements Thread.UncaughtExceptionHandler
{
@Override
public void onCreate()
{
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread t, Throwable e)
{
Thread.UncaughtExceptionHandler uncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
if (!handleException(e) && uncaughtExceptionHandler != null){
uncaughtExceptionHandler.uncaughtException(t, e);
}else
{
try
{
Thread.sleep(1000);
} catch (InterruptedException e1)
{
e1.printStackTrace();
}
Intent intent = new Intent(HandlerException.this, MainActivity.class);
PendingIntent pdIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, pdIntent);
android.os.Process.killProcess(android.os.Process.myPid());
}
}
private boolean handleException(Throwable ex){
if (ex == null){
return false;
}
new Thread(){
@Override
public void run(){
Looper.prepare();
Toast.makeText(HandlerException.this, "error now restart", Toast.LENGTH_SHORT).show();/*处理错误的实现代码*/
Looper.loop();
}
}.start();
return true;
}
}
此时,处理错误的Application类已经写好,只需要在AndroidManifest文件中的设置如下即可。
<application
android:name=".HandlerException"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
如此,在MainActivity中人工设置一个错误,测试发现app可以重启,完成!