Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/silverlight/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 后台服务会在应用程序关闭后立即停止_Android_Service_Background Service - Fatal编程技术网

Android 后台服务会在应用程序关闭后立即停止

Android 后台服务会在应用程序关闭后立即停止,android,service,background-service,Android,Service,Background Service,我正在创建一个消息传递应用程序,我需要一个服务来接收消息,即使在应用程序关闭或打开时,我也有一个广播接收器来接收短信,我创建了一个服务类,并作为 Intent mIntent=new Intent(this,BackgroundService.class); startService(mIntent); 在清单中,我将服务添加为 <service android:name=".BackgroundService" android:enabled="true"/&

我正在创建一个消息传递应用程序,我需要一个服务来接收消息,即使在应用程序关闭或打开时,我也有一个广播接收器来接收短信,我创建了一个服务类,并作为

Intent mIntent=new Intent(this,BackgroundService.class);
startService(mIntent);
在清单中,我将服务添加为

 <service android:name=".BackgroundService"
            android:enabled="true"/>
我也尝试过前台服务

 Notification notification = new NotificationCompat.Builder(this)
            .setContentTitle("TutorialsFace Music Player")
            .setTicker("TutorialsFace Music Player")
            .setContentText("My song")
            .setSmallIcon(R.mipmap.ic_launcher)
            .build();
        startForeground(NOTIFICATION_ID,
            notification);
但一旦我从最近的应用程序中关闭我的应用程序,服务也会停止 当我重新启动应用程序时,服务就会启动

即使应用程序关闭,我如何使我的服务长寿。因为我的应用程序是基于短信的,所以如果没有服务,我无法在我的应用程序关闭时接收消息, 任何帮助都将不胜感激,
提前谢谢

是的,服务与应用程序在同一线程中工作。您可以覆盖onDestroy方法,以使用自己的线程再次启动服务

@Override
public void onDestroy() {
    super.onDestroy();
    getApplicationContext().startService(new Intent(getApplicationContext(), BackgroundService.class));
}

谢谢你的回答,但它不起作用。一旦应用程序关闭,服务就会关闭。你不能让这项服务继续运行。你需要重新启动服务,要做到这一点,你需要在你的服务类上添加Override onDestroy,希望这对你有所帮助!是的,我使用了相同的ondestroy方法重新启动了我的服务,但仍然使用app Close关闭了服务。哦,我知道你需要有关清单的更多信息,如果你愿意,你可以检查我正在处理的这个项目,并使用一个简单的示例
 Notification notification = new NotificationCompat.Builder(this)
            .setContentTitle("TutorialsFace Music Player")
            .setTicker("TutorialsFace Music Player")
            .setContentText("My song")
            .setSmallIcon(R.mipmap.ic_launcher)
            .build();
        startForeground(NOTIFICATION_ID,
            notification);
@Override
public void onDestroy() {
    super.onDestroy();
    getApplicationContext().startService(new Intent(getApplicationContext(), BackgroundService.class));
}