ProcessPhoenix使用方法 Android应用报错自动重启的方法

阎鹏
2023-12-01

1、在 Application 里面注册一个 CrashHandler ,监听应用 crash

public class MyApplication extends Application {

    private static MyApplication mInstance = null;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        Thread.setDefaultUncaughtExceptionHandler(new CrashHandler());
    }

    public static MyApplication getInstance() {
        return mInstance;
    }
}

2、使用 ProcessPhoenix 库

 implementation 'com.jakewharton:process-phoenix:2.0.0'

3、新建 CrashHandler

public class CrashHandler implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        ProcessPhoenix.triggerRebirth(MyApplication.getInstance());
    }
}

4、在 AndroidManifest.xml 中添加 android.intent.category.DEFAULT,否则不起作用

    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

 类似资料: