即使在用戶關閉應用程序(來自任務管理器或相關任務)後,我也希望確保我的服務在後臺運行。我試圖執行START_STICKY
,但不知道如何正確覆蓋startService
方法以允許此工作。如何在服務中設置START_STICKY
目前我只是用startService
方法來啓動並綁定LoggingIn.class
到MessagingService.class
爲:
startService(new Intent(LoggingIn.this, MessagingService.class));
我已經研究了該方法onStartCommand
是實施START_STICKY
常見的位置,但我在我的應用程序中沒有找到它的需要,因爲一旦服務已經開始,我將所有其他類綁定到它:
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((MessagingService.IMBinder) service).getService();
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(GroupMessaging.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
和
bindService(new Intent(GroupMessaging.this, MessagingService.class),
mConnection, Context.BIND_AUTO_CREATE);
我怎樣才能正確地實現START_STICKY
,並確保我的服務保持活動狀態或應用程序關閉後,即使重新啓動?
如果您使用startService()並且不重寫onStartCommand(),則默認實現已經返回START_STICKY,這使我相信您對START_STICKY的真實含義有着不切實際的期望。 – 2015-04-03 21:05:13
@Sauron:你在哪裏見過? – 2015-04-04 13:49:09
仍在研究,但不知道這是否正確。該服務用於發短信的應用程序,並且需要始終處於 – Sauron 2015-04-04 14:44:31