我正在尝试绑定到服务,但绑定服务方法总是返回false。我相信问题在于我的联系。当我导入LocalBinder类的位置(在服务中)时,我没有得到任何编译错误,但bindService调用仍然是false。
服务信息:
//binder for client
private final IBinder mBinder = new LocalBinder();
//client class binder
public class LocalBinder extends Binder {
ServiceA getService() {
// Return this instance of LocalService so clients can call public methods
return ServiceA.this;
}
}
@Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
//called when service is created
public void onCreate(){
super.onCreate();
Toast.makeText(this,"ServiceA is started",Toast.LENGTH_SHORT).show();
}
连接:
private ServiceConnection connect2A = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalBinder newBinder = (LocalBinder) service;
mainService = newBinder.getService();
bound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
bound = false;
}
};
初次通话:
@Override
protected void onStart(){
super.onStart();
Intent intent = new Intent(this, ServiceA.class);
startService(intent);
boolean check = bindService(intent,connect2A,0);
Toast.makeText(this, "Return from check is: " + check, Toast.LENGTH_LONG).show();
//program does get to this point, but binding fails
}
AndroidManifest.XML文件:
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".ServiceTest2Activity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:enabled="true" android:name=".serviceA" />
</application>
答案 0 :(得分:0)
一些想法:
- onStart()方法是什么类的?我在onCreate()中绑定了我的服务。
- 您是否需要将Context.BIND_AUTO_CREATE
传递给bindService调用? e.g。
boolean check = bindService(intent, connect2A, Context.BIND_AUTO_CREATE);
- 正如其他评论者建议的那样,您应该从AndroidManifest.xml发布相关的片段。
- 你应该在onServiceConnected
方法中添加一些跟踪/吐司,以便你知道它是否被调用。