在安卓开发过程中经常会出现一些未能及时捕抓到的异常,导致系统弹出
这样这么不友好的界面,弹出来,让用户怎么看你。
这样的异常是可以被catch到,然后处理,不要让系统自己这样瞎处理,暴露作为一个程序员的无能
可以使用UncaughtExceptionHandler对这样不能及时捕抓的异常统一catch到。
实现UncaughtExceptionHandler接口
public class CrashHandler implements UncaughtExceptionHandler {
private Thread.UncaughtExceptionHandler mDefaultHandler;
private static CrashHandler instance = new CrashHandler();
private Context mContext;
private String tag = CrashHandler.this.getClass().getSimpleName();
public static CrashHandler getInstance() {
return instance;
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (ex==null && mDefaultHandler != null) {
// 系统默认的异常处理器来处理
mDefaultHandler.uncaughtException(thread, ex);
} else {
//开发者自定义处理异常
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
}
public void init(Context context) {
mContext = context;
// 获取系统默认的UncaughtException处理器
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
// 设置该CrashHandler为程序的默认处理器
Thread.setDefaultUncaughtExceptionHandler(this);
}
}
在启动的时候把这个句柄改为程序的默认异常处理器
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
Intent intent = new Intent();
intent.setClass(getApplicationContext(), DemoService.class);
startService(intent);
CrashHandler crashHandler = CrashHandler.getInstance();
crashHandler.init(getApplicationContext());
}
}
这里实现了Application就要在配置文件中进行记录
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:name="com.example.uncaughtexphandler.App" >
现在运行你的程序,屏蔽了系统的不友好的提示框。
即使程序死掉也是默默无闻。
一般情况下,除了默默死去之外,还有一种情况就是需要它重启,那么问题来了,怎么重启呢,重启部分如下:
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (ex == null && mDefaultHandler != null) {
mDefaultHandler.uncaughtException(thread, ex);
} else {
Intent intent = new Intent(context, ExceptionActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);//ZhengZhiying add
}
}
就是在uncaughtException方法中加入跳转到另外的Activity,这里是ExceptionActivity.java,然后从ExceptionActivity.java再跳回到应用程序的主页。那么为什么不是直接跳入主界面呢,比如直接跳入MainActivity.java,因为在所有的启动的界面是在同一个进程中,这样的话就跳转不能成功,这是我的个人理解。
比如这里的ExceptionActivity.java可以这样写:
public class ExceptionActivity extends Activity {
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView text = new TextView(this);
context = this;
text.setText("异常");
setContentView(text);
startNewActicity();
finish();
}
protected void startNewActicity() {
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
就是这样,实现了异常后不弹窗自动重启。非常实用,安卓开发者必备技能点。