2015-04-24 111 views
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; 
    } 
} 

回答

0

當按下後退按鈕,你基本上是摧毀這意味着onDestroy()叫,你stop()STICKY_SERVICE活動。因此,STICKY_SERVICE立即再次啓動。

當您按主頁按鈕時,您正在暫停活動(onPause()),基本上將其置於後臺。只有當操作系統決定GC時纔會銷燬活動。只有在該時間點,onDestroy()纔會被調用,您在此stop()服務和STICKY_SERVICE再次啓動。

希望這會有所幫助。

+0

但是,當我滑過應用程序,調用onDestroy()。無論在哪種情況下。在場景1中,服務被破壞並在幾秒鐘後重新啓動。在場景2中,服務被破壞並在數分鐘後重新啓動。這對我來說是個問題,我需要服務在bot場景中幾秒鐘內重新啓動,因爲代碼在場景2中不運行5分鐘。 – MeesterPatat