2016-09-06 52 views
1

我有一個具有綁定服務的Singleton對象。我希望它重新啓動,當我從啓動程序啓動我的應用程序時,單身對象將初始化並綁定到此現有的服務實例。在自定義對象中創建時粘滯服務未重新啓動

下面是用於創建和單身綁定服務的代碼:

public class MyState { 

    private static MyState sState; 

    private MyService mService; 
    private Context mContext; 
    private boolean mBound = false; 


    private ServiceConnection mConnection = new ServiceConnection() { 
     @Override 
     public void onServiceConnected(ComponentName name, IBinder service) { 
      MyService.MyBinder binder = (MyService.MyBinder) service; 
      mService = binder.getService(); 
      mBound = true; 
     } 

     @Override 
     public void onServiceDisconnected(ComponentName name) { 
      mBound = false; 
     } 
    }; 

    public static MyState get(Context context) { 
     if (sState == null) { 
      sState = new MyState(context); 
     } 
     return sState; 
    } 

    public MyState(Context context) { 
     mContext = context.getApplicationContext(); 
     startService(); 
    } 

    private void startService() { 
     Intent intent = new Intent(mContext, MyService.class); 
     mContext.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); 
     // this won't create another instance of service, but will call onStartCommand 
     mContext.startService(intent); 
    } 
} 

這裏是代碼insice服務

public class MyService extends Service { 

    private final IBinder mBinder = new MyBinder(); 

    public class MyBinder extends Binder { 
     MyService getService() { 
      return MyService.this; 
     } 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     return START_STICKY; 
    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     return mBinder; 
    } 

    // this method is called by singleton object to stop service manually by user                            
    public void stop() { 
     stopSelf(); 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     // some cleanup code here                                        
    } 
} 

不幸的是,當我刷了我的應用程序在任務列表中該服務從不重新啓動。在這種情況下,服務的onDestroy方法永遠不會被調用。

我將綁定移動到用戶可以與服務交互的活動,並且令人驚訝的是它開始按我的預期工作。 我試圖在我的活動中使用應用程序上下文來調用服務創建,它仍然有效。

從不同於從普通Java對象啓動它的活動啓動服務?

回答

1

當您返回START_STICKY這項服務將停止,只要你關閉/終止該應用後因應用程序關閉了所有的參考/值將成爲null所有意圖和變量等STICKY服務將無法得到意向值。如果你想重新啓動該服務的應用程序殺死使用return START_REDELIVER_INTENT

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    return START_REDELIVER_INTENT; 
} 

後應用殺死後,這將在5-10秒後重新啓動該服務。

+0

我會試試看。但是,當我在Activity中啓動服務時,服務爲什麼會正常啓動? – nevermourn

+0

每當應用程序運行時,所有的引用和值都在那裏,但在應用程序終止後,所有的值都變爲null,這就是爲什麼服務重新啓動正確 –

+0

嗯,實際上它有點愚蠢,它重新啓動但具有null Intent值,這正是javadoc說關於START_STICKY。 儘管如此,我還是不明白爲什麼它在Activity和Activity之外的行爲有所不同。 當它處於活動狀態時,將調用onDestroy,但不在它之外。 – nevermourn

相關問題