Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start a service from Thread.UncaughtExceptionHandler?

I'm trying to setup a global exception handling service as mentioned in this answer. This approach sounds logical because after a crash, the code in my custom Thread.UncaughtExceptionHandler may not execute successfully, either because the application may not be in a stable state or because there may not be enough time before the process is killed by the OS.

Unfortunately, this approach doesn't seem to work because the service launches in the same process so it, too, is killed. How can I start a service from the handler's uncaughtException()? Can I force the service to launch in a completely seperate process?


I'm setting my custom default (VM-level) exception handler in Application like this:

public class MyApp extends Application {    
    @Override
    public void onCreate() {
        Thread.setDefaultUncaughtExceptionHandler(
            MyExceptionReporter.getInstance(this));
        ...

In my custom handler, I'm launching the service like this:

final Intent i = new Intent(MyExceptionService.INTENT);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra(MyExceptionService.EXTRA_STACK_TRACE,
    Log.getStackTraceString(ex));
mContext.startService(i);

The service is declated in the AndroidMaifest.xml file and launches fine from elsewhere in the application.

like image 731
quietmint Avatar asked Feb 19 '23 07:02

quietmint


1 Answers

Ah, I figured this out. The key was to add android:process to the manifest, which forces the service to launch in a seperate process. This prevents the service from being killed when the application is killed.

<service
    android:name="your.package.blah.blah.MyExceptionService"
    android:process=":exception" >
    <intent-filter>
        <action android:name="your.package.blah.blah.REPORT" />
    </intent-filter>
    </service>
like image 60
quietmint Avatar answered Mar 04 '23 05:03

quietmint