您的位置:首页 > 移动开发 > Android开发

android全局捕获异常,重启应用

2017-07-31 14:42 513 查看
1.捕获异常类
public class CrashHandler implements Thread.UncaughtExceptionHandler {

private Context context;
public CrashHandler(Context context){
this.context=context;
}

@Override
public void uncaughtException(Thread t, Throwable e) {
showToast(t);
}

/**
* 操作
* @param thread
*/
private void showToast(Thread thread) {
final Dialog dialog=new Dialog(context);
dialog.setContentView(R.layout.dialog_layout);

new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(context, "程序异常,重新启动", Toast.LENGTH_LONG).show();
Looper.loop();
}
}).start();

try {
thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
restartApp();
}

/**
* 重启应用
*/
private void restartApp(){
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());//再此之前可以做些退出等操作
}
}
2.自定义Application
public class MyApplication extends Application {
private static Context mContext;
@Override
public void onCreate() {
super.onCreate();
mContext=this;
Thread.setDefaultUncaughtExceptionHandler(new CrashHandler(mContext));
}
}

3.manifest里面内容
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.com.crashtest">
<!--name注意修改-->
<application
android:allowBackup="true"
android:name=".MyApplication"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
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>
<activity android:name=".ActivityTest"></activity>
</application>

</manifest>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: