Android:粘性服务无法重新启动

Android:粘性服务无法重新启动,android,service,restart,sticky,Android,Service,Restart,Sticky,我的应用程序使用一项服务来执行后台任务。我希望在用户关闭应用程序(将其刷走)时,该服务继续运行。有两种情况下,用户可以终止应用程序: Scenario 1: When in app: 1 User presses **backbutton**, apps goes to background and user is on the homescreen. 2 User presses the multitasking button and swips the app away.

我的应用程序使用一项服务来执行后台任务。我希望在用户关闭应用程序(将其刷走)时,该服务继续运行。有两种情况下,用户可以终止应用程序:

Scenario 1: When in app:
    1 User presses **backbutton**, apps goes to background and user is on the homescreen.
    2 User presses the multitasking button and swips the app away.
    3 The Service should restart because its sticky.

Scenario 2: When in app:
    1 User presses **homebutton**, apps goes to background and user is on the homescreen.
    2 User presses the multitasking button and swips the app away.
    3 The Service should restart because its sticky.
场景1完全按照预期工作。应用程序在几秒钟内被刷走后,服务将重新启动

场景2没有按预期工作。服务确实会重新启动,但会在超过5分钟后重新启动

我不明白为什么在场景2中需要这么长时间才能重新启动服务。有没有已知的解决方案

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent test = new Intent(this, TestService.class);
        startService(test);
    }
}

public class TestService extends Service {

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("Service", "Service is restarted!");//In Scenario 2, it takes more than 5 minutes to print this. 
        return Service.START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

当您按下后退按钮时,实际上是在破坏活动,这意味着
ondestory()
stop()
STICKY\u服务的
处被调用。因此,粘性_服务会立即重新启动

当您按下“主页”按钮时,您正在暂停活动(
onPause()
),实际上是将其置于后台。只有当操作系统决定对其进行GC时,活动才会被销毁。只有在调用
onDestroy()
的时间点,您才能
stop()
服务,然后
STICKY\u服务再次启动


希望这能有所帮助。

但当我刷走应用程序时,会调用onDestroy()。不管在哪种情况下。在场景1中,服务将被销毁,并在几秒钟后重新启动。在场景2中,服务将被销毁,并在几分钟后重新启动。这对我来说是个问题,我需要在bot场景中在几秒钟内重新启动服务,因为在场景2.100%工作解决方案中,代码在5分钟内没有运行->请尝试此答案