我在“绑定服务”中放置了用于停止,播放和暂停的按钮。当我点击MainActivity中的播放btn时,应用程序崩溃,ServiceToo.startPlay()'在null对象引用上。
如何在没有崩溃的情况下控制我的播放器。
**This is the media player in the onCreate.in the Bound Service**
public void onCreate() {
mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
buildNote();
Toast.makeText(this, "Service Created", Toast.LENGTH_SHORT).show();
songlist = new String[]
{"android.resource://" + getPackageName() + "/" + R.raw.blipotron,
"android.resource://" + getPackageName() + "/" +
R.raw.funk_game,
"android.resource://" + getPackageName() + "/" +
R.raw.poofy_reel};
tracks[0] = "android.resource://" + getPackageName() + "/" +
R.raw.blipotron;
tracks[1] = "android.resource://" + getPackageName() + "/" +
R.raw.funk_game;
tracks[2] = "android.resource://" + getPackageName() + "/" +
R.raw.poofy_reel;
mediaPlayer = MediaPlayer.create(getApplicationContext(),
Uri.parse(tracks[currentTrack]));
mediaPlayer.setOnCompletionListener(this);
//container = STARTED;
//mediaPlayer.start();
Toast.makeText(this, "Service Created", Toast.LENGTH_SHORT).show();
}
这是在“绑定服务”
中创建的按钮方法 public void onCompletion(MediaPlayer mp) {
//mp.release();
if (currentTrack < tracks.length -currentTrack) {
currentTrack++;
mp = MediaPlayer.create(this, Uri.parse(tracks[currentTrack]));
mp.setOnCompletionListener(this);
mp.start();
}
}
public void play() {
if (container == STOPPED) {
mediaPlayer.start();
}
}
public void stop() {
if (container == STARTED){
mediaPlayer.stop();
}
}
public void pause() {
if (container == STARTED){
mediaPlayer.pause();
}
findViewById(R.id.play_btn).setOnClickListener(this);
findViewById(R.id.stop_btn).setOnClickListener(this);
findViewById(R.id.pause_btn).setOnClickListener(this);
这是MainActivity中的实际onClick按钮
private AudioService serviceRef;
// On Click button instances
@Override
public void onClick(View v) {
if (v.getId() == R.id.play_btn) {
startService(new Intent(this, AudioService.class));
serviceRef.play();
} else if (v.getId() == R.id.stop_btn) {
stopService(new Intent(this, AudioService.class));
serviceRef.stop();
} else if (v.getId() == R.id.pause_btn) {
stopService(new Intent(this, AudioService.class));
serviceRef.pause();
}