Android實(shí)現(xiàn)將應(yīng)用崩潰信息發(fā)送給開發(fā)者并重啟應(yīng)用的方法
本文實(shí)例講述了Android實(shí)現(xiàn)將應(yīng)用崩潰信息發(fā)送給開發(fā)者并重啟應(yīng)用的方法。分享給大家供大家參考,具體如下:
在開發(fā)過程中,雖然經(jīng)過測(cè)試,但在發(fā)布后,在廣大用戶各種各樣的運(yùn)行環(huán)境和操作下,可能會(huì)發(fā)生一些異想不到的錯(cuò)誤導(dǎo)致程序崩潰。將這些錯(cuò)誤信息收集起來并反饋給開發(fā)者,對(duì)于開發(fā)者改進(jìn)優(yōu)化程序是相當(dāng)重要的。好了,下面就來實(shí)現(xiàn)這種功能吧。
(更正時(shí)間:2012年2月9日18時(shí)42分07秒)
由于為歷史帖原因,以下做法比較浪費(fèi),但抓取異常的效果是一樣的。
1.對(duì)于UI線程(即Android中的主線程)拋出的未捕獲異常,將這些異常信息存儲(chǔ)起來然后關(guān)閉到整個(gè)應(yīng)用程序。并再次啟動(dòng)程序,則進(jìn)入崩潰信息反饋界面讓用戶將出錯(cuò)信息以Email的形式發(fā)送給開發(fā)者。
2.對(duì)于非UI線程拋出的異常,則立即喚醒崩潰信息反饋界面提示用戶將出錯(cuò)信息發(fā)送Email。
效果圖如下:
過程了解了,則需要了解的幾個(gè)知識(shí)點(diǎn)如下:
1.攔截UncaughtException
Application.onCreate()是整個(gè)Android應(yīng)用的入口方法。在該方法中執(zhí)行如下代碼即可攔截UncaughtException:
ueHandler = new UEHandler(this); // 設(shè)置異常處理實(shí)例 Thread.setDefaultUncaughtExceptionHandler(ueHandler);
2.抓取導(dǎo)致程序崩潰的異常信息
UEHandler是Thread.UncaughtExceptionHandler的實(shí)現(xiàn)類,在其public void uncaughtException(Thread thread, Throwable ex)的實(shí)現(xiàn)中可以獲取崩潰信息,代碼如下:
// fetch Excpetion Info String info = null; ByteArrayOutputStream baos = null; PrintStream printStream = null; try { baos = new ByteArrayOutputStream(); printStream = new PrintStream(baos); ex.printStackTrace(printStream); byte[] data = baos.toByteArray(); info = new String(data); data = null; } catch (Exception e) { e.printStackTrace(); } finally { try { if (printStream != null) { printStream.close(); } if (baos != null) { baos.close(); } } catch (Exception e) { e.printStackTrace(); } }
3.程序拋異常后,要關(guān)閉整個(gè)應(yīng)用
悲催的程序員,唉,以下三種方式都無效了,咋辦?。。?!
3.1 android.os.Process.killProcess(android.os.Process.myPid());
3.2 ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
am.restartPackage("lab.sodino.errorreport");
3.3 System.exit(0)
SoftApplication中聲明一個(gè)變量need2Exit,其值為true標(biāo)識(shí)當(dāng)前的程序需要完整退出;為false時(shí)該干嘛干嘛去。該變量在應(yīng)用的啟動(dòng)Activity.onCreate()處賦值為false。
在捕獲了崩潰信息后,調(diào)用SoftApplication.setNeed2Exit(true)標(biāo)識(shí)程序需要退出,并finish()掉ActErrorReport,這時(shí)ActErrorReport退棧,拋錯(cuò)的ActOccurError占據(jù)手機(jī)屏幕,根據(jù)Activity的生命周期其要調(diào)用onStart(),則我們?cè)趏nStart()處讀取need2Exit的狀態(tài),若為true,則也關(guān)閉到當(dāng)前的Activity,則退出了整個(gè)應(yīng)用了。此方法可以解決一次性退出已開啟了多個(gè)Activity的Application。詳細(xì)代碼請(qǐng)閱讀下面的示例源碼。
好了,代碼如下:
lab.sodino.errorreport.SoftApplication.java
package lab.sodino.errorreport; import java.io.File; import android.app.Application; /** * @author Sodino E-mail:sodinoopen@hotmail.com * @version Time:2011-6-9 下午11:49:56 */ public class SoftApplication extends Application { /** "/data/data/<app_package>/files/error.log" */ public static final String PATH_ERROR_LOG = File.separator + "data" + File.separator + "data" + File.separator + "lab.sodino.errorreport" + File.separator + "files" + File.separator + "error.log"; /** 標(biāo)識(shí)是否需要退出。為true時(shí)表示當(dāng)前的Activity要執(zhí)行finish()。 */ private boolean need2Exit; /** 異常處理類。 */ private UEHandler ueHandler; public void onCreate() { need2Exit = false; ueHandler = new UEHandler(this); // 設(shè)置異常處理實(shí)例 Thread.setDefaultUncaughtExceptionHandler(ueHandler); } public void setNeed2Exit(boolean bool) { need2Exit = bool; } public boolean need2Exit() { return need2Exit; } }
lab.sodino.errorreport.ActOccurError.java
package lab.sodino.errorreport; import java.io.File; import java.io.FileInputStream; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; public class ActOccurError extends Activity { private SoftApplication softApplication; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); softApplication = (SoftApplication) getApplication(); // 一開始進(jìn)入程序恢復(fù)為"need2Exit=false"。 softApplication.setNeed2Exit(false); Log.d("ANDROID_LAB", "ActOccurError.onCreate()"); Button btnMain = (Button) findViewById(R.id.btnThrowMain); btnMain.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { Log.d("ANDROID_LAB", "Thread.main.run()"); int i = 0; i = 100 / i; } }); Button btnChild = (Button) findViewById(R.id.btnThrowChild); btnChild.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { new Thread() { public void run() { Log.d("ANDROID_LAB", "Thread.child.run()"); int i = 0; i = 100 / i; } }.start(); } }); // 處理記錄于error.log中的異常 String errorContent = getErrorLog(); if (errorContent != null) { Intent intent = new Intent(this, ActErrorReport.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("error", errorContent); intent.putExtra("by", "error.log"); startActivity(intent); } } public void onStart() { super.onStart(); if (softApplication.need2Exit()) { Log.d("ANDROID_LAB", "ActOccurError.finish()"); ActOccurError.this.finish(); } else { // do normal things } } /** * 讀取是否有未處理的報(bào)錯(cuò)信息。<br/> * 每次讀取后都會(huì)將error.log清空。<br/> * * @return 返回未處理的報(bào)錯(cuò)信息或null。 */ private String getErrorLog() { File fileErrorLog = new File(SoftApplication.PATH_ERROR_LOG); String content = null; FileInputStream fis = null; try { if (fileErrorLog.exists()) { byte[] data = new byte[(int) fileErrorLog.length()]; fis = new FileInputStream(fileErrorLog); fis.read(data); content = new String(data); data = null; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (fis != null) { fis.close(); } if (fileErrorLog.exists()) { fileErrorLog.delete(); } } catch (Exception e) { e.printStackTrace(); } } return content; } }
lab.sodino.errorreport.ActErrorReport.java
package lab.sodino.errorreport; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; /** * @author Sodino E-mail:sodinoopen@hotmail.com * @version Time:2011-6-12 下午01:34:17 */ public class ActErrorReport extends Activity { private SoftApplication softApplication; private String info; /** 標(biāo)識(shí)來處。 */ private String by; private Button btnReport; private Button btnCancel; private BtnListener btnListener; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.report); softApplication = (SoftApplication) getApplication(); by = getIntent().getStringExtra("by"); info = getIntent().getStringExtra("error"); TextView txtHint = (TextView) findViewById(R.id.txtErrorHint); txtHint.setText(getErrorHint(by)); EditText editError = (EditText) findViewById(R.id.editErrorContent); editError.setText(info); btnListener = new BtnListener(); btnReport = (Button) findViewById(R.id.btnREPORT); btnCancel = (Button) findViewById(R.id.btnCANCEL); btnReport.setOnClickListener(btnListener); btnCancel.setOnClickListener(btnListener); } private String getErrorHint(String by) { String hint = ""; String append = ""; if ("uehandler".equals(by)) { append = " when the app running"; } else if ("error.log".equals(by)) { append = " when last time the app running"; } hint = String.format(getResources().getString(R.string.errorHint), append, 1); return hint; } public void onStart() { super.onStart(); if (softApplication.need2Exit()) { // 上一個(gè)退棧的Activity有執(zhí)行“退出”的操作。 Log.d("ANDROID_LAB", "ActErrorReport.finish()"); ActErrorReport.this.finish(); } else { // go ahead normally } } class BtnListener implements Button.OnClickListener { @Override public void onClick(View v) { if (v == btnReport) { // 需要 android.permission.SEND權(quán)限 Intent mailIntent = new Intent(Intent.ACTION_SEND); mailIntent.setType("plain/text"); String[] arrReceiver = { "sodinoopen@hotmail.com" }; String mailSubject = "App Error Info[" + getPackageName() + "]"; String mailBody = info; mailIntent.putExtra(Intent.EXTRA_EMAIL, arrReceiver); mailIntent.putExtra(Intent.EXTRA_SUBJECT, mailSubject); mailIntent.putExtra(Intent.EXTRA_TEXT, mailBody); startActivity(Intent.createChooser(mailIntent, "Mail Sending...")); ActErrorReport.this.finish(); } else if (v == btnCancel) { ActErrorReport.this.finish(); } } } public void finish() { super.finish(); if ("error.log".equals(by)) { // do nothing } else if ("uehandler".equals(by)) { // 1. // android.os.Process.killProcess(android.os.Process.myPid()); // 2. // ActivityManager am = (ActivityManager) // getSystemService(ACTIVITY_SERVICE); // am.restartPackage("lab.sodino.errorreport"); // 3. // System.exit(0); // 1.2.3.都失效了,Google你讓悲催的程序員情何以堪啊。 softApplication.setNeed2Exit(true); // //////////////////////////////////////////////////// // // 另一個(gè)替換方案是直接返回“HOME” // Intent i = new Intent(Intent.ACTION_MAIN); // // 如果是服務(wù)里調(diào)用,必須加入newtask標(biāo)識(shí) // i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // i.addCategory(Intent.CATEGORY_HOME); // startActivity(i); // //////////////////////////////////////////////////// } } }
lab.sodino.errorreport.UEHandler.java
package lab.sodino.uncaughtexception; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import android.content.Intent; import android.util.Log; /** * @author Sodino E-mail:sodinoopen@hotmail.com * @version Time:2011-6-9 下午11:50:43 */ public class UEHandler implements Thread.UncaughtExceptionHandler { private SoftApplication softApp; private File fileErrorLog; public UEHandler(SoftApplication app) { softApp = app; fileErrorLog = new File(SoftApplication.PATH_ERROR_LOG); } @Override public void uncaughtException(Thread thread, Throwable ex) { // fetch Excpetion Info String info = null; ByteArrayOutputStream baos = null; PrintStream printStream = null; try { baos = new ByteArrayOutputStream(); printStream = new PrintStream(baos); ex.printStackTrace(printStream); byte[] data = baos.toByteArray(); info = new String(data); data = null; } catch (Exception e) { e.printStackTrace(); } finally { try { if (printStream != null) { printStream.close(); } if (baos != null) { baos.close(); } } catch (Exception e) { e.printStackTrace(); } } // print long threadId = thread.getId(); Log.d("ANDROID_LAB", "Thread.getName()=" + thread.getName() + " id=" + threadId + " state=" + thread.getState()); Log.d("ANDROID_LAB", "Error[" + info + "]"); if (threadId != 1) { // 此處示例跳轉(zhuǎn)到匯報(bào)異常界面。 Intent intent = new Intent(softApp, ActErrorReport.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("error", info); intent.putExtra("by", "uehandler"); softApp.startActivity(intent); } else { // 此處示例發(fā)生異常后,重新啟動(dòng)應(yīng)用 Intent intent = new Intent(softApp, ActOccurError.class); // 如果<span style="background-color: rgb(255, 255, 255); ">沒有NEW_TASK標(biāo)識(shí)且</span>是UI線程拋的異常則界面卡死直到ANR intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); softApp.startActivity(intent); // write 2 /data/data/<app_package>/files/error.log write2ErrorLog(fileErrorLog, info); // kill App Progress android.os.Process.killProcess(android.os.Process.myPid()); } } private void write2ErrorLog(File file, String content) { FileOutputStream fos = null; try { if (file.exists()) { // 清空之前的記錄 file.delete(); } else { file.getParentFile().mkdirs(); } file.createNewFile(); fos = new FileOutputStream(file); fos.write(content.getBytes()); } catch (Exception e) { e.printStackTrace(); } finally { try { if (fos != null) { fos.close(); } } catch (Exception e) { e.printStackTrace(); } } } }
/res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: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" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Throws Exception By Main Thread" android:id="@+id/btnThrowMain" ></Button> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Throws Exception By Child Thread" android:id="@+id/btnThrowChild" ></Button> </LinearLayout>
/res/layout/report.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns: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/errorHint" android:id="@+id/txtErrorHint" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/editErrorContent" android:editable="false" android:layout_weight="1"></EditText> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#96cdcd" android:gravity="center" android:orientation="horizontal"> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Report" android:id="@+id/btnREPORT" android:layout_weight="1"></Button> <Button android: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資源為:
重要的一點(diǎn)是要在AndroidManifest.xml中對(duì)<application>節(jié)點(diǎn)設(shè)置android:name=".SoftApplication"
更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android調(diào)試技巧與常見問題解決方法匯總》、《Android開發(fā)入門與進(jìn)階教程》、《Android多媒體操作技巧匯總(音頻,視頻,錄音等)》、《Android基本組件用法總結(jié)》、《Android視圖View技巧總結(jié)》、《Android布局layout技巧總結(jié)》及《Android控件用法總結(jié)》
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
相關(guān)文章
Android實(shí)現(xiàn)上拉加載更多ListView(PulmListView)
這篇文章主要介紹了Android實(shí)現(xiàn)上拉加載更多ListView:PulmListView,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-09-09android實(shí)現(xiàn)一鍵鎖屏和一鍵卸載的方法實(shí)例
這篇文章主要給大家介紹了關(guān)于android如何實(shí)現(xiàn)一鍵鎖屏和一鍵卸載的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-05-05Android實(shí)現(xiàn)瘋狂連連看游戲之開發(fā)游戲界面(二)
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)瘋狂連連看游戲之開發(fā)游戲界面,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-03-03Android帶清除功能的輸入框控件EditTextWithDel
這篇文章主要為大家詳細(xì)介紹了Android帶清除功能的輸入框控件EditTextWithDel,感興趣的小伙伴們可以參考一下2016-09-09Android開發(fā)使用UncaughtExceptionHandler捕獲全局異常
本文主要介紹在Android開發(fā)中使用UncaughtExceptionHandler捕獲全局異常,需要的朋友可以參考下。2016-06-06Android實(shí)現(xiàn)多級(jí)樹形選擇列表
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)多級(jí)樹形選擇列表,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-04-04詳解Android:向服務(wù)器提供數(shù)據(jù)之get、post方式
本篇文章主要介紹了詳解Android:向服務(wù)器提供數(shù)據(jù)之get、post方式,具有一定的參考價(jià)值,有興趣的可以了解一下。2017-03-03