Java 我在接通电源时播放过一首歌,但它';当电源断开时,它不会停止
我想在电源接通时播放一首歌,并在电源断开时停止播放,但这首歌在电源断开时仍然播放。请分享与此相关的工作代码Java 我在接通电源时播放过一首歌,但它';当电源断开时,它不会停止,java,android,Java,Android,我想在电源接通时播放一首歌,并在电源断开时停止播放,但这首歌在电源断开时仍然播放。请分享与此相关的工作代码 public class MyReceiver extends BroadcastReceiver { public MyReceiver() { } @Override public void onReceive(Context context, Intent intent) { // TODO: This method is called when the
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
MediaPlayer mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(context, R.raw.mysong);
if (intent.getAction() == Intent.ACTION_POWER_CONNECTED) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(true);
mMediaPlayer.start();
}
else if (intent.getAction() == Intent.ACTION_POWER_DISCONNECTED) {
Toast.makeText(context, "POWER DISCONNECTED !!!!!", Toast.LENGTH_SHORT).show();
mMediaPlayer.stop();
}
}
}
此链接将帮助您。
您必须注册android.intent.action.action\u电源的广播。
然后,在电源断开的情况下接收广播,停止您的媒体播放器
您上面的代码为每个广播消息Mediaplayer创建了一个新对象,这样我就有问题了,用户就在接收方方法之外。您试过调试它吗?行
mmediplayer.stop()代码>断开电源时调用?mMediaPlayer.stop();Toast.makeText(上下文,“电源断开!!!”,Toast.LENGTH\u SHORT.show();我收到了这个祝酒词..我在我的设备上运行