我试图编写一个代码,每次用户按下开机按钮并使手机从睡眠状态恢复时,如果应用程序正在运行,它应该播放声音,否则什么也不会发生。
我想我需要一个广播接收器来检查它是否按下了 power:ON 而不是 Power:OFF 并播放声音。稍后将替换为 async task 。
我如何达到上述要求。请给我一些方法。
我不想使用服务,因为即使应用程序没有运行它也会继续运行。
而且我希望它仅在应用程序在后台运行时才运行,因此是广播接收器。
我是安卓的菜鸟。
请帮忙。
提前致谢。
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MainActivity extends Activity {
MediaPlayer mp3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp3=MediaPlayer.create(this, R.raw.sound);
}
public class YourReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
// do what you want when the screen is turned back on
mp3.start();
}
}
}