[Android]将应用崩溃信息汇报给开发者
经实践,发现Android,在代码中未捕获的异常如果是UI线程抛出的,则异常发生后无法再唤醒新的界面。所以对于所抛异常的处理Sodino的做法是:
1.对于UI线程(即Android中的主线程)抛出的未捕获异常,将这些异常信息存储起来然后关闭到整个应用程序。当用户下一次开启程序时,则进入崩溃信息反馈界面让用户将出错信息以Email的形式发送给开发者。
2.对于非UI线程抛出的异常,则立即唤醒崩溃信息反馈界面提示用户将出错信息发送Email。
效果图如下[CSDN]:
过程了解了,则需要了解的几个知识点如下:
1.拦截UncaughtException
Application.onCreate()是整个Android应用的入口方法。在该方法中执行如下代码即可拦截UncaughtException:
- ueHandler=newUEHandler(this);
- //设置异常处理实例
- Thread.setDefaultUncaughtExceptionHandler(ueHandler);
2.抓取导致程序崩溃的异常信息
UEHandler是Thread.UncaughtExceptionHandler的实现类,在其public void uncaughtException(Thread thread, Throwable ex)的实现中可以获取崩溃信息,代码如下:
- //fetchExcpetionInfo
- Stringinfo=null;
- ByteArrayOutputStreambaos=null;
- PrintStreamprintStream=null;
- try{
- baos=newByteArrayOutputStream();
- printStream=newPrintStream(baos);
- ex.printStackTrace(printStream);
- byte[]data=baos.toByteArray();
- info=newString(data);
- data=null;
- }catch(Exceptione){
- e.printStackTrace();
- }finally{
- try{
- if(printStream!=null){
- printStream.close();
- }
- if(baos!=null){
- baos.close();
- }
- }catch(Exceptione){
- e.printStackTrace();
- }
- }
3.程序抛异常后,要关闭整个应用
悲催的程序员,唉,以下三种方式都无效了,咋办啊!!!
3.1android.os.Process.killProcess(android.os.Process.myPid());
3.2ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
am.restartPackage("lab.sodino.errorreport");
3.3System.exit(0)
好吧,毛主席告诉我们:自己动手丰衣足食。
SoftApplication中声明一个变量need2Exit,其值为true标识当前的程序需要完整退出;为false时该干嘛干嘛去。该变量在应用的启动Activity.onCreate()处赋值为false。
在捕获了崩溃信息后,调用SoftApplication.setNeed2Exit(true)标识程序需要退出,并finish()掉ActErrorReport,这时ActErrorReport退栈,抛错的ActOccurError占据手机屏幕,根据Activity的生命周期其要调用onStart(),则我们在onStart()处读取need2Exit的状态,若为true,则也关闭到当前的Activity,则退出了整个应用了。此方法可以解决一次性退出已开启了多个Activity的Application。详细代码请阅读下面的示例源码。
好了,代码如下:
lab.sodino.errorreport.SoftApplication.java
view plain- packagelab.sodino.errorreport;
- importjava.io.File;
- importandroid.app.Application;
- /**
- *@authorSodinoE-mail:sodinoopen@hotmail.com
- *@versionTime:2011-6-9下午11:49:56
- */
- publicclassSoftApplicationextendsApplication{
- /**"/data/data/<app_package>/files/error.log"*/
- publicstaticfinalStringPATH_ERROR_LOG=File.separator+"data"+File.separator+"data"
- +File.separator+"lab.sodino.errorreport"+File.separator+"files"+File.separator
- +"error.log";
- /**标识是否需要退出。为true时表示当前的Activity要执行finish()。*/
- privatebooleanneed2Exit;
- /**异常处理类。*/
- privateUEHandlerueHandler;
- publicvoidonCreate(){
- need2Exit=false;
- ueHandler=newUEHandler(this);
- //设置异常处理实例
- Thread.setDefaultUncaughtExceptionHandler(ueHandler);
- }
- publicvoidsetNeed2Exit(booleanbool){
- need2Exit=bool;
- }
- publicbooleanneed2Exit(){
- returnneed2Exit;
- }
- }
lab.sodino.errorreport.ActOccurError.java
view plain
- packagelab.sodino.errorreport;
- importjava.io.File;
- importjava.io.FileInputStream;
- importandroid.app.Activity;
- importandroid.content.Intent;
- importandroid.os.Bundle;
- importandroid.util.Log;
- importandroid.view.View;
- importandroid.widget.Button;
- publicclassActOccurErrorextendsActivity{
- privateSoftApplicationsoftApplication;
- /**Calledwhentheactivityisfirstcreated.*/
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- softApplication=(SoftApplication)getApplication();
- //一开始进入程序恢复为"need2Exit=false"。
- softApplication.setNeed2Exit(false);
- Log.d("ANDROID_LAB","ActOccurError.onCreate()");
- ButtonbtnMain=(Button)findViewById(R.id.btnThrowMain);
- btnMain.setOnClickListener(newButton.OnClickListener(){
- publicvoidonClick(Viewv){
- Log.d("ANDROID_LAB","Thread.main.run()");
- inti=0;
- i=100/i;
- }
- });
- ButtonbtnChild=(Button)findViewById(R.id.btnThrowChild);
- btnChild.setOnClickListener(newButton.OnClickListener(){
- publicvoidonClick(Viewv){
- newThread(){
- publicvoidrun(){
- Log.d("ANDROID_LAB","Thread.child.run()");
- inti=0;
- i=100/i;
- }
- }.start();
- }
- });
- //处理记录于error.log中的异常
- StringerrorContent=getErrorLog();
- if(errorContent!=null){
- Intentintent=newIntent(this,ActErrorReport.class);
- intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- intent.putExtra("error",errorContent);
- intent.putExtra("by","error.log");
- startActivity(intent);
- }
- }
- publicvoidonStart(){
- super.onStart();
- if(softApplication.need2Exit()){
- Log.d("ANDROID_LAB","ActOccurError.finish()");
- ActOccurError.this.finish();
- }else{
- //donormalthings
- }
- }
- /**
- *读取是否有未处理的报错信息。<br/>
- *每次读取后都会将error.log清空。<br/>
- *
- *@return返回未处理的报错信息或null。
- */
- privateStringgetErrorLog(){
- FilefileErrorLog=newFile(SoftApplication.PATH_ERROR_LOG);
- Stringcontent=null;
- FileInputStreamfis=null;
- try{
- if(fileErrorLog.exists()){
- byte[]data=newbyte[(int)fileErrorLog.length()];
- fis=newFileInputStream(fileErrorLog);
- fis.read(data);
- content=newString(data);
- data=null;
- }
- }catch(Exceptione){
- e.printStackTrace();
- }finally{
- try{
- if(fis!=null){
- fis.close();
- }
- if(fileErrorLog.exists()){
- fileErrorLog.delete();
- }
- }catch(Exceptione){
- e.printStackTrace();
- }
- }
- returncontent;
- }
- }
lab.sodino.errorreport.ActErrorReport.java
view plain
- packagelab.sodino.errorreport;
- importandroid.app.Activity;
- importandroid.content.Intent;
- importandroid.os.Bundle;
- importandroid.util.Log;
- importandroid.view.View;
- importandroid.widget.Button;
- importandroid.widget.EditText;
- importandroid.widget.TextView;
- /**
- *@authorSodinoE-mail:sodinoopen@hotmail.com
- *@versionTime:2011-6-12下午01:34:17
- */
- publicclassActErrorReportextendsActivity{
- privateSoftApplicationsoftApplication;
- privateStringinfo;
- /**标识来处。*/
- privateStringby;
- privateButtonbtnReport;
- privateButtonbtnCancel;
- privateBtnListenerbtnListener;
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.report);
- softApplication=(SoftApplication)getApplication();
- by=getIntent().getStringExtra("by");
- info=getIntent().getStringExtra("error");
- TextViewtxtHint=(TextView)findViewById(R.id.txtErrorHint);
- txtHint.setText(getErrorHint(by));
- EditTexteditError=(EditText)findViewById(R.id.editErrorContent);
- editError.setText(info);
- btnListener=newBtnListener();
- btnReport=(Button)findViewById(R.id.btnREPORT);
- btnCancel=(Button)findViewById(R.id.btnCANCEL);
- btnReport.setOnClickListener(btnListener);
- btnCancel.setOnClickListener(btnListener);
- }
- privateStringgetErrorHint(Stringby){
- Stringhint="";
- Stringappend="";
- if("uehandler".equals(by)){
- append="whentheapprunning";
- }elseif("error.log".equals(by)){
- append="whenlasttimetheapprunning";
- }
- hint=String.format(getResources().getString(R.string.errorHint),append,1);
- returnhint;
- }
- publicvoidonStart(){
- super.onStart();
- if(softApplication.need2Exit()){
- //上一个退栈的Activity有执行“退出”的操作。
- Log.d("ANDROID_LAB","ActErrorReport.finish()");
- ActErrorReport.this.finish();
- }else{
- //goaheadnormally
- }
- }
- classBtnListenerimplementsButton.OnClickListener{
- @Override
- publicvoidonClick(Viewv){
- if(v==btnReport){
- //需要android.permission.SEND权限
- IntentmailIntent=newIntent(Intent.ACTION_SEND);
- mailIntent.setType("plain/text");
- String[]arrReceiver={"sodinoopen@hotmail.com"};
- StringmailSubject="AppErrorInfo["+getPackageName()+"]";
- StringmailBody=info;
- mailIntent.putExtra(Intent.EXTRA_EMAIL,arrReceiver);
- mailIntent.putExtra(Intent.EXTRA_SUBJECT,mailSubject);
- mailIntent.putExtra(Intent.EXTRA_TEXT,mailBody);
- startActivity(Intent.createChooser(mailIntent,"MailSending..."));
- ActErrorReport.this.finish();
- }elseif(v==btnCancel){
- ActErrorReport.this.finish();
- }
- }
- }
- publicvoidfinish(){
- super.finish();
- if("error.log".equals(by)){
- //donothing
- }elseif("uehandler".equals(by)){
- //1.
- //android.os.Process.killProcess(android.os.Process.myPid());
- //2.
- //ActivityManageram=(ActivityManager)
- //getSystemService(ACTIVITY_SERVICE);
- //am.restartPackage("lab.sodino.errorreport");
- //3.
- //System.exit(0);
- //1.2.3.都失效了,Google你让悲催的程序员情何以堪啊。
- softApplication.setNeed2Exit(true);
- //////////////////////////////////////////////////////
- ////另一个替换方案是直接返回“HOME”
- //Intenti=newIntent(Intent.ACTION_MAIN);
- ////如果是服务里调用,必须加入newtask标识
- //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- //i.addCategory(Intent.CATEGORY_HOME);
- //startActivity(i);
- //////////////////////////////////////////////////////
- }
- }
- }
lab.sodino.errorreport.UEHandler.java
view plain
- packagelab.sodino.errorreport;
- importjava.io.ByteArrayOutputStream;
- importjava.io.File;
- importjava.io.FileOutputStream;
- importjava.io.PrintStream;
- importandroid.content.Intent;
- importandroid.util.Log;
- /**
- *@authorSodinoE-mail:sodinoopen@hotmail.com
- *@versionTime:2011-6-9下午11:50:43
- */
- publicclassUEHandlerimplementsThread.UncaughtExceptionHandler{
- privateSoftApplicationsoftApp;
- privateFilefileErrorLog;
- publicUEHandler(SoftApplicationapp){
- softApp=app;
- fileErrorLog=newFile(SoftApplication.PATH_ERROR_LOG);
- }
- @Override
- publicvoiduncaughtException(Threadthread,Throwableex){
- //fetchExcpetionInfo
- Stringinfo=null;
- ByteArrayOutputStreambaos=null;
- PrintStreamprintStream=null;
- try{
- baos=newByteArrayOutputStream();
- printStream=newPrintStream(baos);
- ex.printStackTrace(printStream);
- byte[]data=baos.toByteArray();
- info=newString(data);
- data=null;
- }catch(Exceptione){
- e.printStackTrace();
- }finally{
- try{
- if(printStream!=null){
- printStream.close();
- }
- if(baos!=null){
- baos.close();
- }
- }catch(Exceptione){
- e.printStackTrace();
- }
- }
- longthreadId=thread.getId();
- Log.d("ANDROID_LAB","Thread.getName()="+thread.getName()+"id="+threadId+"state="
- +thread.getState());
- Log.d("ANDROID_LAB","Error["+info+"]");
- if(threadId!=1){
- //对于非UI线程可显示出提示界面,如果是UI线程抛的异常则界面卡死直到ANR。
- Intentintent=newIntent(softApp,ActErrorReport.class);
- intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- intent.putExtra("error",info);
- intent.putExtra("by","uehandler");
- softApp.startActivity(intent);
- }else{
- //write2/data/data/<app_package>/files/error.log
- write2ErrorLog(fileErrorLog,info);
- //killAppProgress
- android.os.Process.killProcess(android.os.Process.myPid());
- }
- }
- privatevoidwrite2ErrorLog(Filefile,Stringcontent){
- FileOutputStreamfos=null;
- try{
- if(file.exists()){
- //清空之前的记录
- file.delete();
- }else{
- file.getParentFile().mkdirs();
- }
- file.createNewFile();
- fos=newFileOutputStream(file);
- fos.write(content.getBytes());
- }catch(Exceptione){
- e.printStackTrace();
- }finally{
- try{
- if(fos!=null){
- fos.close();
- }
- }catch(Exceptione){
- e.printStackTrace();
- }
- }
- }
- }
/res/layout/main.xml
view plain
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello"
- />
- <Buttonandroid:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="ThrowsExceptionByMainThread"
- android:id="@+id/btnThrowMain"
- ></Button>
- <Buttonandroid:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="ThrowsExceptionByChildThread"
- android:id="@+id/btnThrowChild"
- ></Button>
- </LinearLayout>
/res/layout/report.xml
view plain
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <TextViewandroid:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/errorHint"
- android:id="@+id/txtErrorHint"/>
- <EditTextandroid:layout_width="fill_parent"
- android:layout_height="wrap_content"android:id="@+id/editErrorContent"
- android:editable="false"android:layout_weight="1"></EditText>
- <LinearLayoutandroid:layout_width="fill_parent"
- android:layout_height="wrap_content"android:background="#96cdcd"
- android:gravity="center"android:orientation="horizontal">
- <Buttonandroid:layout_width="fill_parent"
- android:layout_height="wrap_content"android:text="Report"
- android:id="@+id/btnREPORT"android:layout_weight="1"></Button>
- <Buttonandroid:layout_width="fill_parent"
- android:layout_height="wrap_content"android:text="Cancel"
- android:id="@+id/btnCANCEL"android:layout_weight="1"></Button>
- </LinearLayout>
- </LinearLayout>
用到的string.xml资源为:
view plain
- <stringname="errorHint">Aerrorhashappened%1$s.Pleaseclick<i><b>"REPORT"</b></i>tosendtheerrorinformationtousbyemail,Thanks!!!</string>
重要的一点是要在AndroidManifest.xml中对<application>节点设置android:name=".SoftApplication"
本文内容归CSDN博客博主Sodino 所有
转载请注明出处:http://blog.csdn.net/sodino/archive/2011/06/13/6540329.aspx
更多相关文章
- SpringBoot 2.0 中 HikariCP 数据库连接池原理解析
- android中常见的内存泄漏和解决办法
- Android(安卓)利用SurfaceView实现一个简单的计时器
- 随笔之如何判断Android应用进程是否为单线程及闲扯多核并行编程
- android 上企业信息云端查看及实现
- Android(安卓)玩家看过来:来自 Seagate 的 GoFlex Satellite 你也
- 浅谈android的线程安全和handler处理
- 在电脑端加密的文件,放在android上进行解密,但是出现pad block cor
- Android最佳性能实践(1):合理管理内存