Android 如何捕获崩溃异常并重启应用

2018-01-16  本文已影响0人  侯蛋蛋_

第一种方法:通过AppUncaughtExceptionHandler来捕获异常

Android全局捕获崩溃异常记录日志保存至本地并定时删除

异常重启操作
因为捕获异常后我要马上关闭掉app即上面的byebye方法,是将app整个进程杀死,如果接着要显示提示对话框,则需要在新的任务栈中打开activity:

public static Intent newIntent(Context context, String title, String ultimateMessage) {

    Intent intent = new Intent();
    intent.setClass(context, PatchDialogActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    intent.putExtra(EXTRA_TITLE, title);
    intent.putExtra(EXTRA_ULTIMATE_MESSAGE, ultimateMessage);
    return intent;
}

对话框中给出了重启操作的选项,重启过程的实现:

private void restart() {
    Intent intent = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    super.onDestroy();
}

第二种方法:通过第三方捕获(腾讯bugly)

集成SDK

继承SDK需要下载官方的so文件

同时集成SDK和NDK

在Module的build.gradle文件中添加依赖和属性配置:

android {
    defaultConfig {
        ndk {
            // 设置支持的SO库架构
            abiFilters 'armeabi' //, 'x86', 'armeabi-v7a', 'x86_64', 'arm64-v8a'
        }
    }
}

dependencies {
    compile 'com.tencent.bugly:crashreport:latest.release' //其中latest.release指代最新Bugly SDK版本号,也可以指定明确的版本号,例如2.1.9
    compile 'com.tencent.bugly:nativecrashreport:latest.release' //其中latest.release指代最新Bugly NDK版本号,也可以指定明确的版本号,例如3.0
}

同时集成Bugly SDK和NDK的配置如下图所示,后续更新Bugly SDK和NDK时,只需变更配置脚本中的版本号即可。

Alt text

注意:自动集成时会自动包含Bugly SO库,建议在Module的build.gradle文件中使用NDK的“abiFilter”配置,设置支持的SO库架构。

如果在添加“abiFilter”之后Android Studio出现以下提示:

NDK integration is deprecated in the current plugin. Consider trying the new experimental plugin.

则在项目根目录的gradle.properties文件中添加:

android.useDeprecatedNdk=true

参数配置

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_LOGS" />
-dontwarn com.tencent.bugly.**
-keep public class com.tencent.bugly.**{*;}

初始化

CrashReport.initCrashReport(getApplicationContext(), "注册时申请的APPID", false); 

在“AndroidManifest.xml”的“Application”中增加“meta-data”配置项:

<application
    <!-- 配置APP ID -->
    <meta-data
            android:name="BUGLY_APPID"
            android:value="<APP_ID>" />
    <!-- 配置APP版本号 -->
    <meta-data
            android:name="BUGLY_APP_VERSION"
            android:value="<APP_Version>" />
    <!-- 配置APP渠道号 -->
    <meta-data
            android:name="BUGLY_APP_CHANNEL"
            android:value="<APP_Channel>" />
    <!-- 配置Bugly调试模式(true或者false)-->
    <meta-data
            android:name="BUGLY_ENABLE_DEBUG"
            android:value="<isDebug>" />
</application>

不同于“android:versionName”,“BUGLY_APP_VERSION”配置的是Bugly平台的APP版本号。

通过“AndroidManifest.xml”配置后的初始化方法如下:

CrashReport.initCrashReport(getApplicationContext());
上一篇下一篇

猜你喜欢

热点阅读