1

i have created one service by extending Service in android and i am sending Message to service using Messenger and Handler.

But the issue (which is a common behavior though) is whenever i have to send message to Service i have to bind it and when i go out of activity i have to unbind it which eventually destroys the service itself.

i can keep running service in background by fringing startService method but is there any way to send Messages to service without using bind as i don't want to destroy the service when i go out of activity.

Hunt
  • 8,215
  • 28
  • 116
  • 256

2 Answers2

6

LocalBroadcastManager is a great way to send messages/data,

In your service class create a private broadcastreciever and string for the intent action name:

public static String MSERVICEBROADCASTRECEIVERACTION ="whatevs";
private BroadcastReceiver mServiceBroadcastReceiver= new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("foo","onReceive called");
        Log.d("foo","extra = " + intent.getStringExtra("foo")); // should print out " extra = bar"

    }
};

And register it in your onCreate

@Override
public void onCreate() {
        // your other code...
         LocalBroadcastManager.getInstance(this).registerReceiver(mServiceBroadcastReceiver, new IntentFilter(ServiceClassName.MSERVICEBROADCASTRECEIVERACTION));
    }

And De-register it in onDestroy()

@Override
public void onDestroy() {
        // your other code...
         LocalBroadcastManager.getInstance(this).unregisterReceiver(mServiceBroadcastReceiver);
    }

As for sending messages to it, from an activity or fragment:

    LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(context);
    Intent intent = new Intent(ServiceClassName.MSERVICEBROADCASTRECEIVERACTION);
    // add some data 
    intent.putExtra("foo","bar");
    lbm.sendBroadcast(intent);

HTHs you send data without needing to bind!

petey
  • 16,914
  • 6
  • 65
  • 97
0

Unbind Service will not destroy the service. it will disconnect the service connection between the activity and service

Make sure you return START_STICKY to keep your service running

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

Also make sure your running the service as foreground using notification to keep running the service after the application is removed from stack.

startForeground(1000,mBuilder.build());  // mBuilder - notification builder 
Libin
  • 16,967
  • 7
  • 61
  • 83
  • if its just disconnecting then why my service's `onDestroy` is getting called at the time of unbinding service ? – Hunt Mar 28 '14 at 13:09
  • make sure you are not stopping the service. use only unbindService(mConnection); – Libin Mar 28 '14 at 13:13
  • ok, i think your application(all activity) is removed from stack. see my updated answer – Libin Mar 28 '14 at 13:17