Android實現捕獲未知異常並提交給伺服器的方法_Android

來源:互聯網
上載者:User

本文執行個體講述了Android實現捕獲未知異常並提交給伺服器的方法。分享給大家供大家參考,具體如下:

在Android應用中,即便應用已經投放市場,但有時也會遇到一些未知的異常,此時如果能夠獲得使用者的反饋資訊,那麼對於我們應用的開發是一個很好的協助

為了實現這樣的效果,我們需要做如下工作

寫一個類實現UncaughtExceptionHandler介面,重寫uncaughtException方法

功能描述:當應用出現了未知異常,應用強制退出,應用再次啟動時,提示使用者是否將錯誤資訊反饋給開發人員

public class MyUncaughtExceptionHandler implements UncaughtExceptionHandler {  private static final String TAG = "MyUncaughtExceptionHandler";  // 將錯誤資訊儲存到sharepreference中  private static SharedPreferences bugPreferences;  private static SharedPreferences.Editor bugEditor;  private static Context mContext;  private static PackageInfo packageInfo;  private UncaughtExceptionHandler defaultUncaughtExceptionHandler;  private static HandleProgressDialog progressDialog;  // 儲存錯誤原因的欄位  private static String bugExistStr = "";  private static Handler handler = new Handler() {    @Override    public void handleMessage(Message msg) {      progressDialog.dismiss();    }  };  public MyUncaughtExceptionHandler(Context context) {    try {      mContext = context;      packageInfo = context.getPackageManager().getPackageInfo(          context.getPackageName(), 0);      bugPreferences = context.getSharedPreferences("bug", 0);      bugEditor = bugPreferences.edit();      defaultUncaughtExceptionHandler = Thread          .getDefaultUncaughtExceptionHandler();    } catch (NameNotFoundException e) {      e.printStackTrace();    } catch (Exception e) {      e.printStackTrace();    }  }  // 當異常發生時,會調用這個方法  public void uncaughtException(Thread th, Throwable t) {    try {      // 儲存bug      saveBugText(t);      defaultUncaughtExceptionHandler.uncaughtException(th, t);    } catch (FileNotFoundException e) {      e.printStackTrace();    } catch (Exception e) {      e.printStackTrace();    }  }  private void saveBugText(Throwable ex) throws FileNotFoundException {    Writer writer = new StringWriter();    PrintWriter printWriter = new PrintWriter(writer);    ex.printStackTrace(printWriter);    Throwable cause = ex.getCause();    while (cause != null) {      cause.printStackTrace(printWriter);      cause = cause.getCause();    }    printWriter.close();    bugEditor.putString("bugText", writer.toString());    bugEditor.commit();  }  // 下次開啟應用的時候,如果上次產生了未知異常則顯示對話方塊應用與使用者反饋  public static void showBugReportDialog(final Context context) {    bugExistStr = context.getSharedPreferences("bug", 0).getString(        "bugText", "");    if (bugExistStr != null && !bugExistStr.equals("")) {      AlertDialog.Builder builder = new AlertDialog.Builder(context);      builder.setTitle(R.string.bug_report);      builder.setMessage(R.string.whether_report_to_developer);      builder.setNegativeButton(R.string.cancel, new OnClickListener() {        public void onClick(DialogInterface dialog, int which) {          finish(dialog);        }      });      builder.setPositiveButton(R.string.send, new OnClickListener() {        public void onClick(DialogInterface dialog, int which) {          // 提交bug到伺服器          postBugReportInBackground(context);          dialog.dismiss();        }      });      AlertDialog dialog = builder.create();      dialog.show();    }  }  private static void postBugReportInBackground(final Context context) {    progressDialog = new HandleProgressDialog(context);    progressDialog.show();    new Thread(new Runnable() {      public void run() {        postBugReport();        // 將之前的bug資訊清除掉        if (bugExistStr != null) {          bugEditor.putString("bugText", "");          bugEditor.commit();        }        handler.sendEmptyMessage(0);      }    }).start();  }  /**   * Send Bug Report.   */  private static void postBugReport() {    List<NameValuePair> nvps = new ArrayList<NameValuePair>();    nvps.add(new BasicNameValuePair("device", Build.DEVICE));    nvps.add(new BasicNameValuePair("model", Build.MODEL));    nvps.add(new BasicNameValuePair("sdk-version", Build.VERSION.SDK));    nvps.add(new BasicNameValuePair("apk-version", packageInfo.versionName));    nvps.add(new BasicNameValuePair("bug", bugExistStr));    try {      HttpPost httpPost = new HttpPost(Constants.BaseUrl          + "c=main&a=androidCrash");      httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));      DefaultHttpClient httpClient = new DefaultHttpClient();      HttpParams params = httpClient.getParams();      HttpConnectionParams.setConnectionTimeout(params, 5000);      HttpConnectionParams.setSoTimeout(params, 5000);      httpClient.execute(httpPost);    } catch (IOException e) {      e.printStackTrace();    } catch (Exception e) {      e.printStackTrace();    }  }  private static void finish(DialogInterface dialog) {    if (bugExistStr != null) {      bugEditor.putString("bugText", "");      bugEditor.commit();    }    dialog.dismiss();  }}

在需要捕捉異常的地方調用

@Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    appApplication = (APPApplication) getApplication();    appApplication.activites.add(this);    initViews();    Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler(        MainActivity.this));    MyUncaughtExceptionHandler.showBugReportDialog(this);  }

更多關於Android相關內容感興趣的讀者可查看本站專題:《Android開發入門與進階教程》、《Android視圖View技巧總結》、《Android編程之activity操作技巧總結》、《Android操作SQLite資料庫技巧總結》、《Android操作json格式資料技巧總結》、《Android資料庫操作技巧總結》、《Android檔案操作技巧匯總》、《Android編程開發之SD卡操作方法匯總》、《Android資源操作技巧匯總》及《Android控制項用法總結》

希望本文所述對大家Android程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.