Android实现将应用崩溃信息发送给开发者并重启应用的方法
作者:Sodino 发布时间:2021-07-25 02:42:14
本文实例讲述了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/<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";
/** 标识是否需要退出。为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
}
}
/**
* 读取是否有未处理的报错信息。<br/>
* 每次读取后都会将error.log清空。<br/>
*
* @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();
}
}
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);
// 如果<span style="background-color: rgb(255, 255, 255); ">没有NEW_TASK标识且</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资源为:
<string name="errorHint">A error has happened %1$s.Please click <i><b>"REPORT"</b></i> to send the error information to us by email, Thanks!!!</string>
重要的一点是要在AndroidManifest.xml中对<application>节点设置android:name=".SoftApplication"
希望本文所述对大家Android程序设计有所帮助。
猜你喜欢
- 壹、入围方案Sentinelgithub地址:https://sentinelguard.io/zh-cn/docs/introductio
- 今天我们来讨论如何在项目开发中优雅地使用RocketMQ。本文分为三部分,第一部分实现SpringBoot与RocketMQ的整合,第二部分
- 1.切所有controller下的请求项目结构任意公共方法的执行:execution(public * (…))##public可以省略,
- 一、文件上传的必要前提A form 表单的 enctype 取值必须是:multipart/form-data(默认值是:applicati
- 摘要本文主要讲解mall通过整合SpringSecurity和JWT实现后台用户的登录和授权功能,同时改造Swagger-UI的配置使其可以
- 前言本文主要给大家介绍了关于JDK8新增的原子性操作类LongAdder的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的
- 我们很容易能想到,可以用递归来实现汉诺塔游戏。因为要将n(n>1)个盘子从“源”柱子移到“目标”柱子,我们要先把n-1个盘子从“源”柱
- 项目需要去调用.NET的WebSrevice,本身是Java,研究了半天,终于有些头绪,记下来。1,新建.NET WebService。只在
- 人们常说堆栈堆栈,堆和栈是内存中两处不一样的地方,什么样的数据存在栈,又是什么样的数据存在堆中?这里浅谈Java中的栈和堆首先,将结论写在前
- 压缩包制作也是很多项目中需要用到的功能。比如有大量的文件(假设有10000个)需要上传,1个1个的上传似乎不太靠谱(靠,那得传到什么时候啊?
- Java中的final关键字非常重要,它可以应用于类、方法以及变量。这篇文章中我将带你看看什么是final关键字?将变量,方法和类声明为fi
- Kryo框架的source已移至https://github.com/EsotericSoftware/kryo ,进入此页面,然后点击右边
- 前言:学习了SpringBoot分页查询的两种写法,一种是手动实现,另一种是使用框架实现。现在我将具体的实现流程分享一下。首先是手动实现分页
- 一、查看线程的运行状态题目线程有以下6种状态:新建、运行、阻塞、等待、计时等待和终止。new新线程时,线程处于新建 状态。调用start()
- 引言 批量下载思路,首先前端发送下载请求,携带必要参数,
- 现在面试,基本上都是面试造火箭🚀,工作拧螺丝🔩。而且是喜欢问一些 Spring 相关的知识点,比如 @Autowired 和 @Resour
- clone() 方法麻烦一些,需要将所有涉及到的类实现声明式接口 Cloneable,并覆盖Object类中的clone()方法,并设置作用
- 前言最近在给熔断器组件增加一个降级策略(Hystrix好像没有这个配置),我们提供了如下几种策略:1、默认策略2、返回常量值3、抛出指定异常
- 在java里, 我们可以使用Executors.newFixedThreadPool 来创建线程池, 然后就可以不停的创建新任务,并用线程池
- 本文实例为大家分享了用JavaMail发送HTML模板邮件的具体代码,供大家参考,具体内容如下依赖<dependency>&nb