gpt4 book ai didi

Android:bindService() 有问题 -> 服务为空

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:36:26 25 4
gpt4 key购买 nike

我在将服务绑定(bind)到 Activity 时遇到问题。我得到 playing_service==null。我找不到我做错了什么。为什么 playing_service 为空??

MyActivity 类:

private playService playing_service=null;

private ServiceConnection service_conn=new ServiceConnection(){
public void onServiceConnected(ComponentName className, IBinder service) {
LocalBinder binder=(LocalBinder)service;
playing_service=binder.getService();
}
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub

}
};

public void playTrack(View view){
Intent i=new Intent(this,playService.class);
i.setAction("com.c0dehunter.soundrelaxer.PLAY");
bindService(i,service_conn,Context.BIND_AUTO_CREATE);

if(playing_service==null) //here I get true,
//if I try to access playing_service I get NullPointerException

}
}

playService类:

private final IBinder binder=new LocalBinder();

public int onStartCommand(Intent intent, int flags, int startId){
return 1; //dummy
}

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return binder;
}

public class LocalBinder extends Binder{
public playService getService(){
return playService.this;
}
}

最佳答案

您的服务可能不为空,因为绑定(bind)服务是一种异步方法,因此您应该在服务连接实现中执行此操作,而不是在调用绑定(bind)方法后检查服务的可用性,例如:

private ServiceConnection service_conn=new ServiceConnection(){
public void onServiceConnected(ComponentName className, IBinder service) {
LocalBinder binder=(LocalBinder)service;
playing_service=binder.getService();

if(playing_service != null){
Log.i("service-bind", "Service is bonded successfully!");

//do whatever you want to do after successful binding
}
}
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub

}
};

关于Android:bindService() 有问题 -> 服务为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9211994/

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