篇中归纳皆来自多篇网络Blog,只是在其基础上进行效果实验,整合之后写出自己的想法 ,方便予己 ~
经检测针对 Android 9.0 系统,代码有效,可实现我们的需求效果 ~
MyApplication
package nk.com.restartapp;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
/**
* @author MrLiu
* @date 2020/5/13
* desc
*/
public class MyApplication extends Application {
private static Context context;
List<Activity> activityList = new ArrayList<>();
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
/**
* context
*/
public static Context getContext() {
return context;
}
public void init() {
// 设置该CrashHandler为程序的默认处理器
CrashHandler unCeHandler = new CrashHandler(this);
Thread.setDefaultUncaughtExceptionHandler(unCeHandler);
}
/**
* @param activity activity关闭时,删除Activity列表中的Activity对象
*/
public void removeActivity(Activity activity) {
activityList.remove(activity);
}
/**
* @param activity 向列表中添加Activity对象
*/
public void addActivity(Activity activity) {
activityList.add(activity);
}
/**
* 关闭Activity列表中的 所有Activity
*/
public void finishAllActivity() {
for (Activity activity : activityList) {
if (null != activity) {
activity.finish();
}
}
// 杀死应用进程
android.os.Process.killProcess(android.os.Process.myPid());
}
}
application内注册我们自己的application
android:name=".MyApplication"
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nk.com.restartapp">
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
intent-filter>
activity>
application>
manifest>
CrashHandler
package nk.com.restartapp;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
/**
* @author MrLiu
* @date 2020/5/13
* desc 捕获异常
*/
public class CrashHandler implements Thread.UncaughtExceptionHandler {
private Thread.UncaughtExceptionHandler mDefaultHandler;
MyApplication application;
public CrashHandler(MyApplication myApplication) {
// // 获取系统默认的UncaughtException处理器
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
this.application = myApplication;
}
/**
* 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
*
* @param ex
* @return true:如果处理了该异常信息;否则返回false.
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handlerException(ex) && mDefaultHandler != null) {
// 若果用户没有处理则让系统默认的异常处理器来处理
mDefaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Log.e("CatchExcep", "error ;", e);
}
// 重启app
Intent intent = new Intent(application.getApplicationContext(), MainActivity.class);
// PendingIntent restartIntent = PendingIntent.getActivity(application.getApplicationContext(), 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent restartIntent = PendingIntent.getActivity(MyApplication.getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 退出程序
AlarmManager mgr = (AlarmManager) application.getSystemService(Context.ALARM_SERVICE);
// 3秒后重启
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 3000, restartIntent);
application.finishAllActivity();
}
}
/**
* 获取具体异常,此处可做崩溃前的处理
*
* @param ex
* @return true:如果处理了该异常信息;否则返回false.
*/
private boolean handlerException(Throwable ex) {
if (ex == null) {
return false;
}
// 发个友好的提示,弹个土司 - 此处只是为了效果,可进行注释或替换为自己的逻辑代码
new Thread() {
public void run() {
Looper.prepare();
Toast.makeText(application.getApplicationContext(), "检测到程序异常,即将退出", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
return true;
}
}
MainActivity
package nk.com.restartapp;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 检测程序异常
CatchExcApplication();
}
/**
* 检测程序异常,重启
*/
public void CatchExcApplication() {
// 添加程序异常检测
MyApplication application = (MyApplication) getApplication();
application.init();
application.addActivity(this);
}
}
百分之90的代码相同,唯一不同的是CrashHandler(异常)的一个处理方式,在这个版本中可以在APP崩溃之前将错误上传到后台,主要用于及时定位问题 ; 不过题外话一下,其实现在有很多方式可以三方平台的SDK可以进行错误收集 ~
MyApplication
package nk.com.startappdemo;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
/**
* @author MrLiu
* @date 2020/5/13
* desc
*/
public class MyApplication extends Application {
private static Context context;
List<Activity> activityList = new ArrayList<>();
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
/**
* context
*/
public static Context getContext() {
return context;
}
public void init() {
// 设置该CrashHandler为程序的默认处理器
CrashHandler unCeHandler = new CrashHandler(this);
Thread.setDefaultUncaughtExceptionHandler(unCeHandler);
}
/**
* @param activity activity关闭时,删除Activity列表中的Activity对象
*/
public void removeActivity(Activity activity) {
activityList.remove(activity);
}
/**
* @param activity 向列表中添加Activity对象
*/
public void addActivity(Activity activity) {
activityList.add(activity);
}
/**
* 关闭Activity列表中的 所有Activity
*/
public void finishAllActivity() {
for (Activity activity : activityList) {
if (null != activity) {
activity.finish();
}
}
// 杀死应用进程
android.os.Process.killProcess(android.os.Process.myPid());
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nk.com.startappdemo">
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
intent-filter>
activity>
application>
manifest>
CrashHandler
package nk.com.startappdemo;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author MrLiu
* @date 2020/5/12
* desc 异常捕获处理 ~
*/
public class CrashHandler implements Thread.UncaughtExceptionHandler {
public static final String TAG = "CrashHandler";
private static CrashHandler INSTANCE = new CrashHandler();
/**
* 系统默认的UncaughtException处理类
**/
private Thread.UncaughtExceptionHandler mDefaultHandler;
/**
* 用来存储设备信息和异常信息
**/
private Map<String, String> mInfos = new HashMap<String, String>();
private DateFormat mFormatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
public CrashHandler() {
}
public static CrashHandler getInstance() {
return INSTANCE;
}
public void init() {
// 获取系统默认的UncaughtException处理器
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
// 设置该CrashHandler为程序的默认处理器
Thread.setDefaultUncaughtExceptionHandler(this);
}
/**
* @描述: 当UncaughtException发生时会转入该函数来处理
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
// 如果用户没有处理则让系统默认的异常处理器来处理
mDefaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Log.e(this.getClass().toString(), e == null ? "" : e.toString());
}
// 重新启动应用
Intent intent = new Intent(MyApplication.getContext(), MainActivity.class);
PendingIntent restartIntent = PendingIntent.getActivity(MyApplication.getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager mgr = (AlarmManager) MyApplication.getContext().getSystemService(Context.ALARM_SERVICE);
// 1秒钟后重启应用
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent);
// todo:退出程序
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
}
/**
* @return true:如果处理了该异常信息;否则返回false.
* @throws
* @描述:自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
*/
private boolean handleException(Throwable ex) {
if (null == ex) {
return false;
}
// 使用Toast来显示异信息
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(MyApplication.getContext(), "程序开了个小差,即将退出.", Toast.LENGTH_LONG).show();
Looper.loop();
}
}.start();
// 收集设备参数信息
collectDeviceInfo(MyApplication.getContext());
// 保存日志文件
saveCrashInfo2File(ex);
return true;
}
/**
* @描述:收集设备参数信息
*/
private void collectDeviceInfo(Context context) {
try {
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
if (pi != null) {
String versionName = pi.versionName == null ? "null" : pi.versionName;
String versionCode = pi.versionCode + "";
mInfos.put("versionName", versionName);
mInfos.put("versionCode", versionCode);
}
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "an error occured when collect package info", e);
}
Field[] fields = Build.class.getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
mInfos.put(field.getName(), field.get(null).toString());
Log.d(TAG, field.getName() + " : " + field.get(null));
} catch (Exception e) {
Log.e(TAG, "an error occured when collect crash info", e);
}
}
}
/**
* @throws
* @描述:保存错误信息到文件中 目录/sdcard/qfangadtv/crash/
* @返回类型 void 返回文件名称,便于将文件传送到服务器
*/
private String saveCrashInfo2File(Throwable ex) {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : mInfos.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key + "=" + value + "\n");
}
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();
String result = writer.toString();
sb.append(result);
try {
long timestamp = System.currentTimeMillis();
String time = mFormatter.format(new Date());
String fileName = "crash-" + time + "-" + timestamp + ".log";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String path = "/sdcard/×××/crash/";
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
FileOutputStream fos = new FileOutputStream(path + fileName);
fos.write(sb.toString().getBytes());
fos.close();
}
return fileName;
} catch (Exception e) {
Log.e(TAG, "an error occured while writing file...", e);
}
return null;
}
}
MainActivity
package nk.com.restartapp;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 检测程序异常
CatchExcApplication();
}
/**
* 检测程序异常,重启
*/
public void CatchExcApplication() {
// 添加程序异常检测
MyApplication application = (MyApplication) getApplication();
application.init();
application.addActivity(this);
}
}
基于项目开发原则进行二次简单封装,方便管理 ( Demo地址在此 ) ~
MyApplication
package nk.com.restartapp;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
/**
* @author MrLiu
* @date 2020/5/13
* desc
*/
public class MyApplication extends Application {
private static Context context;
List<Activity> activityList = new ArrayList<>();
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
init();
}
/**
* context
*/
public static Context getContext() {
return context;
}
public void init() {
// 设置该CrashHandler为程序的默认处理器
CrashHandler unCeHandler = new CrashHandler(this);
Thread.setDefaultUncaughtExceptionHandler(unCeHandler);
}
/**
* @param activity activity关闭时,删除Activity列表中的Activity对象
*/
public void removeActivity(Activity activity) {
activityList.remove(activity);
}
/**
* @param activity 向列表中添加Activity对象
*/
public void addActivity(Activity activity) {
activityList.add(activity);
}
/**
* 关闭Activity列表中的 所有Activity
*/
public void finishAllActivity() {
for (Activity activity : activityList) {
if (null != activity) {
activity.finish();
}
}
// 杀死应用进程
android.os.Process.killProcess(android.os.Process.myPid());
}
}
application内注册我们自己的application
android:name=".MyApplication"
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nk.com.restartapp">
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
intent-filter>
activity>
application>
manifest>
CrashHandler
package nk.com.restartapp;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
/**
* @author MrLiu
* @date 2020/5/13
* desc 捕获异常
*/
public class CrashHandler implements Thread.UncaughtExceptionHandler {
private Thread.UncaughtExceptionHandler mDefaultHandler;
MyApplication application;
public CrashHandler(MyApplication myApplication) {
// // 获取系统默认的UncaughtException处理器
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
this.application = myApplication;
}
/**
* 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
*
* @param ex
* @return true:如果处理了该异常信息;否则返回false.
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handlerException(ex) && mDefaultHandler != null) {
// 若果用户没有处理则让系统默认的异常处理器来处理
mDefaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Log.e("CatchExcep", "error ;", e);
}
// 重启app
Intent intent = new Intent(application.getApplicationContext(), MainActivity.class);
// PendingIntent restartIntent = PendingIntent.getActivity(application.getApplicationContext(), 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent restartIntent = PendingIntent.getActivity(MyApplication.getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 退出程序
AlarmManager mgr = (AlarmManager) application.getSystemService(Context.ALARM_SERVICE);
// 3秒后重启
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 3000, restartIntent);
application.finishAllActivity();
}
}
/**
* 获取具体异常,此处可做崩溃前的处理
*
* @param ex
* @return true:如果处理了该异常信息;否则返回false.
*/
private boolean handlerException(Throwable ex) {
if (ex == null) {
return false;
}
// 发个友好的提示,弹个土司 - 此处只是为了效果,可进行注释或替换为自己的逻辑代码
new Thread() {
public void run() {
Looper.prepare();
Toast.makeText(application.getApplicationContext(), "检测到程序异常,即将退出", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
return true;
}
}
BaseActivity
package nk.com.restartapp;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
/**
* @author MrLiu
* @date 2020/5/13
* desc
*/
public class BaseActivity extends AppCompatActivity {
private MyApplication application;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
application = (MyApplication) getApplication();
// 添加 - 检测程序异常
CatchExcApplication();
}
public void CatchExcApplication() {
application.init();
application.addActivity(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
application.removeActivity(this);
}
}
MainActivity
package nk.com.restartapp;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(this, "启动完成", Toast.LENGTH_SHORT).show();
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<Object> list = new ArrayList<>();
}
});
}
}
activity_main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:background="#ff7"
android:gravity="center"
android:textColor="#f42"
android:text="自创崩溃 - 数据越界" />
LinearLayout>