自己的线程中的Android服务与应用程序进程一起被杀死



我在清单中声明了一个服务,例如

        <service android:name=".services.ScreenOnService" android:process="@string/screenProcess"/>

该服务所做的只是注册Screen_on广播(因为我总是需要屏幕已打开的信息,而不仅仅是我的应用程序正在运行时)

@Nullable
@Override
public IBinder onBind(Intent intent)
{
    return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    //All this service has to do is register for the screen on broadcast
    //as this one can't be registere in manifest and the ACTION_USER_PRESENT is
    //not guaranteed to be fired. (E.g. if no lock screen is used)
    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    registerReceiver(screenEventReceiver,filter);
    return START_STICKY;
}
@Override
public void onDestroy()
{
    unregisterReceiver(screenEventReceiver);
    super.onDestroy();
}

我从我的应用程序创建启动服务

@Override
public void onCreate() {
    super.onCreate();
    if(!isScreenOnServiceAlreadyRunning())
    {
        //Start the screen on service
        Intent screenOnService = new Intent(this, ScreenOnService.class);
        startService(screenOnService);
    }
}

只要应用程序正在运行,一切都很好。如果我杀死应用程序,它自己的进程中的服务也会被杀死,我不明白为什么。

我 http://fabcirablog.weebly.com/blog/creating-a-never-ending-background-service-in-android 在这里找到了一篇有前途的文章,并希望最好,但即使我这样做并发送广播,它也行不通。

如果应用程序被终止,为什么服务会停止工作?我以为它会继续运行,因为它在自己的过程中。如果我想要的东西无法通过我的方法实现,那么最好的方法是什么?

已经谢谢了。

@Hardcore_Graverobber 我认为您应该将服务作为一个单独的进程启动,

请参考本教程 http://www.vogella.com/tutorials/AndroidServices/article.html

最新更新