2016-09-06 53 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

相关问题