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

Android崩溃后重启App心得

2016-01-27 09:57 417 查看
昨天接到需求要求,App崩溃后要进行统计重启,搜索了下,  主要就是application 继承Thread.UncaughtExceptionHandler 

实现  uncaughtException(final Thread thread, final Throwable ex) 方法  在里面对ex进行判断,不为空的情况就可以处理了.

按照百度里面一些例子尝试,发现单纯的Intent是没有在崩溃后唤起App的,后来尝试了PendingIntent 是可行的.

Intent intent = new Intent(application.getApplicationContext(), MainActivity.class);
PendingIntent restartIntent = PendingIntent.getActivity(
application.getApplicationContext(), 0, intent,
Intent.FLAG_ACTIVITY_NEW_TASK);
//退出程序
AlarmManager mgr = (AlarmManager)application.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
restartIntent); // 1秒钟后重启应用


  但是执行了这个代码后,会发现崩溃的app处于黑屏,卡死状态,知道ANR,后来查阅了一下,我们如果想重启我们的自己的app 需要杀掉原进程,不然android不允许同名称的两个进程存在.

所以在上面代码之后必须加载一句话..

// 杀死该应用进程
android.os.Process.killProcess(android.os.Process.myPid());


这样就ok了 .

为什么Intent不ok, 我们来一起看看PendingIntent 的解释
http://my.oschina.net/u/242041/blog/206710
附加一个开源中国的详细链接,这里就不多做解释了

Demo 下载地址:

http://download.csdn.net/detail/doudou_1117/9419261
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android