Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android實現捕獲未知異常並提交給服務器的方法

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

編輯:關於Android編程

本文實例講述了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程序設計有所幫助。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved