您的位置:首页 > 其它

如何设置当程序出现异常后进行重启

2017-05-10 18:19 288 查看

主要有三步

一、AndroidManifest.xml配置Application

二、在Application初始化CrashHandler(异常统一捕获)

三、CrashHandler

要测试可以增加一个按钮,响应“ int i = 0/0 ; ”就可以测试

一、AndroidManifest.xml

这个主要是“  android:name=".BaseApplication"  ”其它代码可以忽略

<?xml version="1.0" encoding="utf-8"?>


二、Application

import android.app.Application;
import android.content.Context;

/**
* 项目名称:sanhemu
* 类名称:BaseApplication
* 类描述:Application基础类
* 创建人: wjl
* 创建时间: 2017-05-10 18:00:17
*/
public class BaseApplication extends Application {

private Context sContext;

@Override
public void onCreate() {
super.onCreate();

sContext = getApplicationContext();

initErrorHandler();//当程序出现异常后,进行重启(需要有启动页才能用)
}
private void initErrorHandler(){
CrashHandler crashHandler = CrashHandler.getInstance();
crashHandler.init();
crashHandler.switchCrashActivity(getContext());
}
public Context getContext() {
return sContext;
}
}


三、CrashHandler

import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import java.lang.Thread.UncaughtExceptionHandler;

/**
* 项目名称:sanhemu
* 类名称:CrashHandler
* 类描述:异常统一捕获
* UncaughtException处理类,当程序发生Uncaught异常的时候,
* 由该类来接管程序,并记录发送错误报告.
* 需要在Application中注册,为了要在程序启动器就监控整个程序。
* 创建人:wjl
* 创建时间:2017-05-10 18:05:01
*/
public class CrashHandler implements UncaughtExceptionHandler {
private static final String TAG = "CrashHandler";
// CrashHandler实例
private static CrashHandler instance;
// 程序的Context对象
private Context context;

/** 保证只有一个CrashHandler实例 */
private CrashHandler() {
}

/** 获取CrashHandler实例 ,单例模式 */
public static CrashHandler getInstance() {
if (instance == null)
instance = new CrashHandler();
return instance;
}

/**
* 初始化
*/
public void init() {
// 设置该CrashHandler为程序的默认处理器
Thread.setDefaultUncaughtExceptionHandler(this);
}

/*
* 切换发生Crash所在的Activity
*/
public void switchCrashActivity(Context context) {
this.context = context;
}

/**
* 当UncaughtException发生时会转入该函数来处理(当应用出现异常后进行重启应用)
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
// 使用Toast来显示异常信息
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(context, "很抱歉,程序出现异常,3秒后将重启.",
Toast.LENGTH_LONG).show();
Looper.loop();
}
}.start();

try {
Thread.sleep(3000);
restartApp();
} catch (InterruptedException e) {
Log.e(TAG, "error : ", e);
}
}

private void restartApp(){
//有“_”是因为项目有备置androidannotations,如果“MainActivity_.class”不正确,程序会一直卡住
Intent intent = new Intent(context,MainActivity_.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid());  //结束进程之前可以把你程序的注销或者退出代码放在这段代码之前
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐