我想在连接电源时播放歌曲,并在断电时停止播放歌曲,但断电后此歌仍然播放。请分享有关此的工作代码。
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();
}
}
}
答案 0 :(得分:0)
此链接将为您提供帮助。 您必须为android.intent.action.ACTION_POWER_DISCONNECTED注册Broadcast。 并且接收电源断开广播会停止媒体播放器。
https://spark.apache.org/docs/2.1.0/api/R/dapply.html
以上代码为每个广播消息Mediaplayer创建了新对象,这样我就成了问题,用户在接收方法之外。