Start a service from Thread.UncaughtExceptionHandler?

匆匆过客 提交于 2019-11-30 17:27:55

问题


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.


回答1:


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>


来源:https://stackoverflow.com/questions/13652153/start-a-service-from-thread-uncaughtexceptionhandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!