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

android使用UncaughtExceptionHandler捕获全局异常(闪退)

2017-07-28 00:20 453 查看
CrashHandler:

package itant.com.cashtest;

import android.util.Log;

/**
* Created by zhanzc on 2017/7/27.
*/

public class CrashHandler implements Thread.UncaughtExceptionHandler {

@Override
public void uncaughtException(Thread thread, Throwable throwable) {
Log.e("bug", "crash");
//退出程序
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
}


CrashApplication:(记得要在AndroidManifest.xml文件里注册)

package itant.com.cashtest;

import android.app.Application;
import android.util.Log;

/**
* Created by zhanzc on 2017/7/27.
*/

public class CrashApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Log.e("bug", "application oncreate");

Thread.setDefaultUncaughtExceptionHandler(new CrashHandler());
}
}


然后故意制造一个崩溃,比如:

Method method = null;
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
try {
method = Class.forName("android.app.ActivityManager").getMethod("forceStopPackage", String.class);
if (method != null) {
method.invoke(manager, getPackageName());
}
} catch (Exception e) {
Log.e("bug", e.getMessage());
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  异常 android