【问题标题】:what happens if I call startService after calling bindService on a service class?如果在服务类上调用 bindService 后调用 startService 会发生什么?
【发布时间】:2013-06-14 15:32:42
【问题描述】:

我在 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);

在服务代码中: 在 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;
}

【问题讨论】:

  • 您是否检查过是否有任何对象被添加到移动客户端?

标签: android android-service android-handler


【解决方案1】:

你可以找到问题here的答案。

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

我自己正在寻找答案,当我遇到您的问题帖子时,这出奇地难以找到,所以我发布它,因为其他人可能会觉得它有用。

【讨论】:

    【解决方案2】:

    不管你跑 startService() -> bindService()bindService() -> startService(),一旦调用startService(),需要使用stopSelf()stopService()来停止。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-10
      • 2011-04-02
      • 1970-01-01
      相关资源
      最近更新 更多