gpt4 book ai didi

android - 在上一个 Activity 中调用 startService 时 bindService 失败

转载 作者:太空狗 更新时间:2023-10-29 12:53:43 52 4
gpt4 key购买 nike

我不确定如何解决这个问题,但在一个 Activity 中我调用了 startService,然后立即调用以启动下一个 Activity。

这有效,服务启动,并开始按预期处理数据。

我转到下一个 Activity,并在 onResume 中调用 AsyncTask 来绑定(bind)服务。

所以,基本流程是我调用 AsyncTask,bindService 返回 false,因此永远不会调用 mConnection。

那么,问题是为什么 bindService 返回 false?

我将绑定(bind)放在 AsyncTask 中的原因是我让线程在绑定(bind)前休眠 10 秒,以查看是否需要先启动服务。

我也在这个 Activity 中启动了服务,首先,在 onCreate 方法中,等了 10 秒,但是 bindService 仍然返回 false。

private class BindServiceTask extends AsyncTask<Void, Void, Boolean> {
protected Boolean doInBackground(Void... params) {
return bindService(
new Intent(IMyCallback.class.getName()),
mConnection, Context.BIND_AUTO_CREATE);
}
protected void onPostExecute(Boolean b) {
if (b) {
Log.i(TAG, "onResume - binding succeeded");
Toast.makeText(mContext, "Bound to service succeeded",
Toast.LENGTH_LONG).show();
} else {
Log.i(TAG, "onResume - binding failed");
Toast.makeText(mContext, "Bound to service failed",
Toast.LENGTH_LONG).show();
}
}
}
private IMyCallback mCallback = new IMyCallback.Stub() {
@Override
public void dataChanged(double[] info) throws RemoteException {
mHandler.sendMessage(mHandler.obtainMessage(LOCATION_MSG, info));
}
};
IMyService mIRemoteService;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
Log.i(TAG, "onServiceConnected");
mIRemoteService = IMyService.Stub.asInterface(service);
try {
Log.i(TAG, "registering callback");
mIRemoteService.registerCallback(mCallback);
} catch (RemoteException e) {
Log.e(TAG, e.toString());
}
}

public void onServiceDisconnected(ComponentName className) {
Log.e(TAG, "Service has unexpectedly disconnected");
mIRemoteService = null;
}
};

最佳答案

问题似乎是 list 的问题。

我缺少 intent-filter 来告诉系统可以绑定(bind)哪些服务:

    <service
android:name=".MyService"
android:process=":remote" >
<intent-filter>

<!--
These are the interfaces supported by the service, which
you can bind to.
-->
<action android:name="my.com.services.IMyCallback" />
<action android:name="my.com.services.IMySecondaryService" />
<!--
This is an action code you can use to select the service
without explicitly supplying the implementation class.
-->
<action android:name="my.com.activity.MY_SERVICE" />
</intent-filter>
</service>

关于android - 在上一个 Activity 中调用 startService 时 bindService 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9155484/

52 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com