有许多相同标题的问题,但它们没有帮助。所以我在问。
我有一项服务在第一次活动中成功启动。当切换到第二个活动时,我需要bind
使用该服务。但是永远不会调用onServiceConnected
。
(注意:我使用emulator
,并使用this example来实现绑定)
活动:
public class GameActivity extends NativeActivity implements GroupInfoListener
{
public SimmobBroker broker;// <- this is my service
ServiceConnection cnn= new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name,
IBinder service) {
Log.i(TAG,"onServiceConnected");
SimmobBrokerBinder binder = (SimmobBrokerBinder) service;
broker = binder.getService();
Log.i(TAG,"onServiceConnected...now initializing the activity");
InitializeActivity();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, SimmobBroker.class);
getApplicationContext().bindService(intent, cnn, getApplicationContext().BIND_AUTO_CREATE);
// InitializeActivity();
}
};
服务
public class SimmobBroker extends Service {
@Override
public void onCreate() {
Log.i(TAG, "SimmobBroker Created");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "SimmobBroker onStartCommand");
myHandler.post(simmobConnect);
return START_STICKY;
}
@SuppressLint("HandlerLeak")
public final Handler myHandler = new Handler() {/*...*/}
private final IBinder myBinder = new SimmobBrokerBinder();
public class SimmobBrokerBinder extends Binder {
public SimmobBroker getService() {
return SimmobBroker.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return myBinder;
}
};
感谢您的帮助。
答案 0 :(得分:0)
尝试直接调用bindService,而不是从应用程序上下文调用。
bindService(intent, cnn, Context.BIND_AUTO_CREATE)