如果我在服务类上调用bindService后调用startService会发生什么?

IP *_*her 5 android android-service android-handler

我在Service MessengerService上调用bindService.它工作正常.之后,我调用startService.

代码与此链接远程信使服务示例部分 http://developer.android.com/reference/android/app/Service.html 完全相同,只是我在活动中添加了一个startService

这是客户端代码:Intent intnt = new Intent(context,MessengerService.class); intnt.putExtra("msg","从服务到处理程序11的活动的字符串");

    bindService(intnt, mConnection, Context.BIND_AUTO_CREATE);

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

    startService(intnt);
Run Code Online (Sandbox Code Playgroud)

在服务代码中:在onStartCommand中,无论我在startService中传递的意图中收到什么消息,我都将其发送回客户端处理程序.

我在行mClients.get(0).send(msg1)中获取索引超出绑定异常.mClients是附加到此服务的客户端数组,在绑定过程中存储.

代码与此链接远程信使服务示例部分 http://developer.android.com/reference/android/app/Service.html 完全相同,只是我在服务中添加onStartCommand

@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;
}
Run Code Online (Sandbox Code Playgroud)

小智 3

您可以在这里找到问题的答案。

服务生命周期流程图

调用 onStartCommand() 和 onBind() 的顺序不分先后

我自己一直在寻找答案,当我遇到你的问题帖子时,发现很难找到答案,所以我将其发布,因为其他人可能会发现它有用。