我遇到了一个我无法理解的问题。我尝试解决这个问题8天了,但仍然卡住了。我询问了更有经验的开发人员,他们无法回答。所以请,我拼命寻求帮助
该服务很简单 - 它只有一种方法 - 它应该给我日志 - getLog()
public class AudioService extends Service{
MyBinder binder = new MyBinder();
public void getLog(){Log.d("MyLog","I reached getLog!");}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return binder;
}
class MyBinder extends Binder {
AudioService getService() {
return AudioService.this;
}
}
}
当我尝试访问 audioService.getLog() 时,MainAcivity 崩溃;但是,如果我插入行 AudioService audioService= new AudioService(); 它不会崩溃。但这就是我不想要的 - 我需要设置一个将播放音频的服务,以便我可以从一个 Activity 启动 mp3 并从另一个 Activity 停止它。这是主要 Activity :
public class MainActivity extends Activity {
ServiceConnection sConn;
Intent intservice;
AudioService audioService ;
boolean bound=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
intservice=new Intent(this,AudioService.class);
sConn=new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName arg0, IBinder binder) {
// TODO Auto-generated method stub
audioService = ((AudioService.MyBinder) binder).getService();
bound=true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
bound=false;
}
};
startService(intservice);
audioService.getLog();
}
@Override
protected void onStart() {
super.onStart();
bindService(intservice, sConn, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
if (!bound) return;
unbindService(sConn);
bound = false;
}
}
如果我在 list 中弄乱了某些内容,我将在此处包含服务部分:
</activity>
<service android:enabled="true" android:name="AudioService"></service>
</application>
</manifest>
我不明白这里出了什么问题,所以请给我建议,我哪里做错了
最佳答案
嗯,我已经找到原因了。绑定(bind)是一个需要时间的过程,现有的每个示例都等待 onClick,这意味着 Activity 在 onStart() 和 onCreate() 之间有足够的时间。就我而言,它会立即发生。所以最好的办法就是将所有Activity移到public void onServiceConnected(ComponentName arg0, IBinder binder)下。这应该意味着绑定(bind)发生后 - Activity 顺利进行。
希望对很多人有帮助
关于java android - 简单的绑定(bind)服务崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17770268/