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