Search code examples
javaandroidandroid-serviceintentserviceandroid-service-binding

Stop/Pause/Sleep Service if connection unavailable and resume if available


I have an application in which I have created a service MyService.class Now MyService.class is tied to my activity using bindService() but I want my service to run in the background even if activity destroys itself.

So I started the service and then bind it like below:

private void doBindService() {
  if (!isServiceBound){
    Log.d(LOG_TAG, "Binding Service...");
    if (mBtAdapter != null && mBtAdapter.isEnabled()){
      Intent intent = new Intent(MyActivity.this, MyService.class);
      startService(intent);
      bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }
  }
}

In MyActivity's onDestroy method I am unbinding the service

Now my service is running smoothly until the connection with the remote device breaks. I want to pause/sleep/stop this service if connection breaks, then after every 60 seconds it tries to start the service/connection.

I have tried this but doesn't work.

private void stopService() {
    doUnbindService();
    stopService(new Intent(MyActivity.this, MyService.class));
    startService(new Intent(MyActivity.this, MyService.class));
}

Please any help will be much appreciated. Thanks in advance!!!


Solution

  • Try this

    • create a method that perform the Operation you want
    • create a Thread or Runnable class
    • Call the Helper method you created in the run() of the Thread or Runnable
    • Inside the Service onStartCommand start the Thread if connection is available
    • thread.wait/sleep if no connection