3
我的应用程序使用服务进行后台任务。我希望服务在用户杀死应用程序时继续运行(将其刷掉)。有两种情况,用户可以杀死该应用:Android:粘滞服务不重新启动
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;
}
}
但是,当我滑过应用程序,调用onDestroy()。无论在哪种情况下。在场景1中,服务被破坏并在几秒钟后重新启动。在场景2中,服务被破坏并在数分钟后重新启动。这对我来说是个问题,我需要服务在bot场景中几秒钟内重新启动,因为代码在场景2中不运行5分钟。 – MeesterPatat