How to exit (only) current activity if an UncaughtExceptionHandler event occurs?

I encoded a bit to check Thread.UncaughtExceptionHandler for a specific use case (explained below).

Firstly, I have BaseActivityimplemented this way.

public class BaseActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
                Log.e("CRASH_REPORT", "Activity crashed!");
                System.exit(0);
            }
        });
    }
}


Expanding BaseActivity, any uncaught exception gets into the process by the handler. System.exit(0)shuts down the VM .

Now I have created 2 actions with this hierarchy (both extensions BaseActivity).

ParentActivity → SubActivity


In ParentActivityI have only one button that will start SubActivitywhen clicked (code omitted).

In, SubActivity.onCreate(...)I intentionally introduce an exception to run uncaughtException(...).

public class SubActivity extends BaseActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int crash = 1 / 0;
    }
}


SubActivity , uncaughtException(...) , (, ).

, (SubActivity ), () (ParentActivity)?

. .

+4
1

, , NO WAY Activity, uncaughtException(...) , .

, "" .


1. Activity ( )

android:process=dedicated_process_name Activity. , Activity , , 1- . .

<activity
    android:name=".ParentActivity"
    android:process="::parent_process" />


2. Force (System.exit(code)) , Activity .

BaseActivity onCrashed(...).

public class BaseActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
                Log.e("CRASH_REPORT", "Activity crashed!");
                onCrashed(thread, throwable);
                System.exit(0);
            }
        });
    }

    protected void onCrashed(Thread thread, Throwable throwable) {
        // space for rent
    }
}

Activity, BaseActivity, , . .

public class SubActivity extends BaseActivity
    @Override
    protected void onCrashed(Thread thread, Throwable throwable) {
        Intent i = new Intent(this, ParentActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        am.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pi);
    }

uncaughtException (...) Application, Application , . (, Activity)

0

Source: https://habr.com/ru/post/1608611/


All Articles