热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Android实现将应用崩溃信息发送给开发者并重启应用的方法

这篇文章主要介绍了Android实现将应用崩溃信息发送给开发者并重启应用的方法,涉及Android错误处理与应用操作的相关技巧,需要的朋友可以参考下

本文实例讲述了Android实现将应用崩溃信息发送给开发者并重启应用的方法。分享给大家供大家参考,具体如下:

在开发过程中,虽然经过测试,但在发布后,在广大用户各种各样的运行环境和操作下,可能会发生一些异想不到的错误导致程序崩溃。将这些错误信息收集起来并反馈给开发者,对于开发者改进优化程序是相当重要的。好了,下面就来实现这种功能吧。

(更正时间:2012年2月9日18时42分07秒)

由于为历史帖原因,以下做法比较浪费,但抓取异常的效果是一样的。

1.对于UI线程(即Android中的主线程)抛出的未捕获异常,将这些异常信息存储起来然后关闭到整个应用程序。并再次启动程序,则进入崩溃信息反馈界面让用户将出错信息以Email的形式发送给开发者。

2.对于非UI线程抛出的异常,则立即唤醒崩溃信息反馈界面提示用户将出错信息发送Email。

效果图如下:

过程了解了,则需要了解的几个知识点如下:

1.拦截UncaughtException

Application.onCreate()是整个Android应用的入口方法。在该方法中执行如下代码即可拦截UncaughtException:

ueHandler = new UEHandler(this);
// 设置异常处理实例
Thread.setDefaultUncaughtExceptionHandler(ueHandler);

2.抓取导致程序崩溃的异常信息

UEHandler是Thread.UncaughtExceptionHandler的实现类,在其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();
  }
}

3.程序抛异常后,要关闭整个应用

悲催的程序员,唉,以下三种方式都无效了,咋办啊!!!

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中声明一个变量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

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//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";
  /** 标识是否需要退出。为true时表示当前的Activity要执行finish()。 */
  private boolean need2Exit;
  /** 异常处理类。 */
  private UEHandler ueHandler;
  public void onCreate() {
    need2Exit = false;
    ueHandler = new UEHandler(this);
    // 设置异常处理实例
    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();
    // 一开始进入程序恢复为"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
    }
  }
  /**
   * 读取是否有未处理的报错信息。
* 每次读取后都会将error.log清空。
* * @return 返回未处理的报错信息或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;
  /** 标识来处。 */
  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()) {
      // 上一个退栈的Activity有执行“退出”的操作。
      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权限
        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);
      // ////////////////////////////////////////////////////
      // // 另一个替换方案是直接返回“HOME”
      // Intent i = new Intent(Intent.ACTION_MAIN);
      // // 如果是服务里调用,必须加入newtask标识
      // 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) {
      // 此处示例跳转到汇报异常界面。
      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 {
      // 此处示例发生异常后,重新启动应用
      Intent intent = new Intent(softApp, ActOccurError.class);
      // 如果没有NEW_TASK标识且是UI线程抛的异常则界面卡死直到ANR
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      softApp.startActivity(intent);
      // write 2 /data/data//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

<&#63;xml version="1.0" encoding="utf-8"&#63;>

  
  
  


/res/layout/report.xml

<&#63;xml version="1.0" encoding="utf-8"&#63;>

  
  
  
    
    
  


用到的string.xml资源为:

代码如下:
A error has happened %1$s.Please click "REPORT" to send the error information to us by email, Thanks!!!

重要的一点是要在AndroidManifest.xml中对节点设置android:name=".SoftApplication"

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android调试技巧与常见问题解决方法汇总》、《Android开发入门与进阶教程》、《Android多媒体操作技巧汇总(音频,视频,录音等)》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结》

希望本文所述对大家Android程序设计有所帮助。


推荐阅读
  • 拥抱Android Design Support Library新变化(导航视图、悬浮ActionBar)
    转载请注明明桑AndroidAndroid5.0Loollipop作为Android最重要的版本之一,为我们带来了全新的界面风格和设计语言。看起来很受欢迎࿰ ... [详细]
  • Python字典推导式及循环列表生成字典方法
    本文介绍了Python中使用字典推导式和循环列表生成字典的方法,包括通过循环列表生成相应的字典,并给出了执行结果。详细讲解了代码实现过程。 ... [详细]
  • 本文讲述了如何通过代码在Android中更改Recycler视图项的背景颜色。通过在onBindViewHolder方法中设置条件判断,可以实现根据条件改变背景颜色的效果。同时,还介绍了如何修改底部边框颜色以及提供了RecyclerView Fragment layout.xml和项目布局文件的示例代码。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • Android Studio Bumblebee | 2021.1.1(大黄蜂版本使用介绍)
    本文介绍了Android Studio Bumblebee | 2021.1.1(大黄蜂版本)的使用方法和相关知识,包括Gradle的介绍、设备管理器的配置、无线调试、新版本问题等内容。同时还提供了更新版本的下载地址和启动页面截图。 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • 本文介绍了Python版Protobuf的安装和使用方法,包括版本选择、编译配置、示例代码等内容。通过学习本教程,您将了解如何在Python中使用Protobuf进行数据序列化和反序列化操作,以及相关的注意事项和技巧。 ... [详细]
  • ZSI.generate.Wsdl2PythonError: unsupported local simpleType restriction ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • Google Play推出全新的应用内评价API,帮助开发者获取更多优质用户反馈。用户每天在Google Play上发表数百万条评论,这有助于开发者了解用户喜好和改进需求。开发者可以选择在适当的时间请求用户撰写评论,以获得全面而有用的反馈。全新应用内评价功能让用户无需返回应用详情页面即可发表评论,提升用户体验。 ... [详细]
  • Java验证码——kaptcha的使用配置及样式
    本文介绍了如何使用kaptcha库来实现Java验证码的配置和样式设置,包括pom.xml的依赖配置和web.xml中servlet的配置。 ... [详细]
  • Android系统移植与调试之如何修改Android设备状态条上音量加减键在横竖屏切换的时候的显示于隐藏
    本文介绍了如何修改Android设备状态条上音量加减键在横竖屏切换时的显示与隐藏。通过修改系统文件system_bar.xml实现了该功能,并分享了解决思路和经验。 ... [详细]
  • 本文介绍了Android 7的学习笔记总结,包括最新的移动架构视频、大厂安卓面试真题和项目实战源码讲义。同时还分享了开源的完整内容,并提醒读者在使用FileProvider适配时要注意不同模块的AndroidManfiest.xml中配置的xml文件名必须不同,否则会出现问题。 ... [详细]
author-avatar
没有结果的爱请你收好
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有