Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what happens if I call startService after calling bindService on a service class?

I am calling bindService on a Service MessengerService. It works fine. After that, I call startService.

The code is exactly same as this link Remote messenger service example section http://developer.android.com/reference/android/app/Service.html except I add a startService in activity

This is client code: Intent intnt = new Intent(context, MessengerService.class); intnt.putExtra("msg", "String from activity to service to handler 11");

    bindService(intnt, mConnection, Context.BIND_AUTO_CREATE);

    intnt.putExtra("msg", "String from activity to service to handler 22");     

    startService(intnt);

In Service code: In onStartCommand, whatever message i receive in intent which is passed in startService, I send it back to client handler.

I am getting index out of bound exception in line mClients.get(0).send(msg1). mClients is the array of clients attached to this service and stored during binding process.

The code is exactly same as this link Remote messenger service example section http://developer.android.com/reference/android/app/Service.html except I am adding a onStartCommand in Service

@Override
public int onStartCommand(Intent intent, int flags, int startId){

    String str = intent.getStringExtra("msg");
    Message msg1 = Message.obtain(null, MSG_STR_VALUE);
    Bundle data = new Bundle();
    data.putString("message", str);
    msg1.setData(data);

    System.out.println(str);
    try {
        s1.acquire();
    } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        mClients.get(0).send(msg1);
    } catch (RemoteException e) {
        e.printStackTrace();
    }

    return START_STICKY;
}
like image 437
IP Archer Avatar asked Oct 04 '22 19:10

IP Archer


1 Answers

You can find the answer to the question here.

Service lifecycle flow chart

In no particular order, onStartCommand() and onBind() are called

I was looking for the answer myself which was surprisingly difficult to find when I ran in to your question post so I am posting it since others may find it useful.

like image 86
octado Avatar answered Oct 12 '22 08:10

octado