欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android实现捕获未知异常并提交给服务器的方法

程序员文章站 2024-03-07 16:50:57
本文实例讲述了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程序设计有所帮助。