当前位置: 代码迷 >> Android >> 接通电源后我已经播放了歌曲,但是断开电源后并没有停止播放
  详细解决方案

接通电源后我已经播放了歌曲,但是断开电源后并没有停止播放

热度:80   发布时间:2023-08-04 10:31:24.0

我想在接通电源时播放一首歌,而在断开电源时停止播放,但是在断开电源时仍会播放这首歌。 请分享与此有关的工作代码。

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_POWER_DISCONNECTED注册广播。 并且接收到断电广播后停止媒体播放器。

并且您上面的代码为Mediaplayer的每条广播消息创建了一个新对象,使我感到麻烦,在接收方方法之外的用户。

  相关解决方案