簡體   English   中英

Android:Sticky Service無法重啟

[英]Android: Sticky Service not restarting

我的應用程序使用服務進行后台任務。 我希望服務在用戶殺死應用程序時繼續運行(輕掃它)。 有兩種情況,用戶可以殺死應用程序:

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;
    }
}

當你按下后退按鈕時,你實際上是在破壞活動,這意味着在你stop() STICKY_SERVICE地方調用onDestroy() 因此,STICKY_SERVICE立即再次啟動。

當您按下主頁按鈕時,您將暫停活動( onPause() ),基本上將其置於后台。 僅當操作系統決定對其進行GC時,才會銷毀該活動。 只有在那個時間點,調用onDestroy() STICKY_SERVICE stop()服務,並且STICKY_SERVICE再次啟動。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM