0

我试图编写一个代码,每次用户按下开机按钮并使手机从睡眠状态恢复时,如果应用程序正在运行,它应该播放声音,否则什么也不会发生。

我想我需要一个广播接收器来检查它是否按下了 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();
        }
    }

}
4

1 回答 1

1

您可以在清单文件中注册 aBroadcastReceiver以监听按下电源按钮的时间。这将告诉系统您有一个类your.package.YourReceiver,当按下电源按钮打开屏幕时,它想要做一些事情

<receiver android:name="your.package.YourReceiver">
    <intent-filter>
        <action android:name="android.intent.action.SCREEN_ON"></action>
    </intent-filter>
</receiver>

然后你必须创建一个类来处理事件。这是收到广播时将运行的代码。

public class YourReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        // do what you want when the screen is turned back on
    }
}

笔记...

如果您需要处理关闭屏幕的电源按钮按下,在清单中使用它。

<action android:name="android.intent.action.SCREEN_OFF"></action>

您可以使用其中一种或两种。

于 2013-02-20T15:06:28.733 回答