问题描述
我想在接通电源时播放一首歌,而在断开电源时停止播放,但是在断开电源时仍会播放这首歌。 请分享与此有关的工作代码。
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();
}
}
}
1楼
该链接将为您提供帮助。 您必须为android.intent.action.ACTION_POWER_DISCONNECTED注册广播。 并且接收到断电广播后停止媒体播放器。
并且您上面的代码为Mediaplayer的每条广播消息创建了一个新对象,使我感到麻烦,在接收方方法之外的用户。