我遇到了一个我无法理解的问题。我试图解决它 8 天,但仍然卡住。我询问了那些更有经验的开发人员,他们无法回答。所以拜托,我拼命寻求帮助
该服务很简单 - 它有一种方法 - 它应该给我 Log - 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(); 它不会崩溃 但这就是我不想要的——我需要设置一个服务来播放音频,这样我就可以从一个活动启动 mp3 并从另一个活动停止它。这是 MainActivity :
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;
}
}
如果我在 Manifest 中弄乱了一些东西,我将在此处包含服务部分:
</activity>
<service android:enabled="true" android:name="AudioService"></service>
</application>
</manifest>
我不明白这里出了什么问题,所以请给我建议我做错了什么