广播接收器不检测键事件

时间:2013-08-21 16:34:06

标签: java android broadcastreceiver keyevent

我正在尝试在我的应用中接收电源按钮事件。我在我的清单文件中添加了以下代码,然后在广播接收器类的接收方法中显示吐司,但代码仍无法正常工作。我错过了什么吗?

 <receiver android:name="com.xxxxx">
    <intent-filter>
        <action android:name="android.intent.action.SCREEN_OFF"></action>
        <action android:name="android.intent.action.SCREEN_ON"></action>
        <action android:name="android.intent.action.ACTION_POWER_CONNECTED"></action>
        <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"></action>
         <action android:name="android.intent.action.ACTION_SHUTDOWN"></action>
    </intent-filter>
</receiver>

此致

1 个答案:

答案 0 :(得分:0)

是的,你想要做的只是我想要清除的几件事,在屏幕关闭时显示吐司是没有用的还检测电源按钮和屏幕状态是一样的我会告诉你如何检测屏幕状态并且仅显示吐司,但电源按钮我仍然不知道检测它的方式,因为电源按钮仅由系统管理,我认为你需要root来调整或添加功能按钮。这里的任何方式都是您需要的代码:

1 - 您需要一个可以开始/停止检测屏幕状态的活动,一个让您的应用程序在后台运行的服务,最后是Broadcastreceiver。所以从活动中你应该开始服务:

startService(new Intent(MainActivity.this, yourservice.class));

确保在完成后停止

stopService(new Intent(MainActivity.this, yourservice.class));

2-这里你的服务应该是这样的:

public class yourservice extends Service{
private BroadcastReceiver mReceiver;

public void onCreate() {
    super.onCreate();
    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    this.mReceiver = new your receiver();
    this.registerReceiver(this.mReceiver, filter);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (yourbroasdcast.screenOff) {
            //here screen is off do your stuff
    } else {
            //here screen is on do your stuff example your toast
Toast.makeText(getApplicationContext(), "write your toast here", Toast.LENGTH_LONG).show();
    }

    return START_STICKY;
}

3 - 你的广播接收者:

public class yourbroadcast extends BroadcastReceiver{

public static boolean screenOff;
@Override
public void onReceive(Context context, Intent intent) {

    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        screenOff = true;
    }else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
        screenOff = false;
    }
    Intent i = new Intent(context, yourservice.class);
    i.putExtra("screen state", screenOff);
    context.startService(i);
}

}

4 - 清单应该如下所示

<service
        android:enabled="true"
        android:name=".yourservice"/>
    <receiver android:name=".yourbroadcast" android:enabled="true">  
    <intent-filter>
        <action android:name="android.intent.action.SCREEN_OFF" />
        <action android:name="android.intent.action.SCREEN_ON" />
    </intent-filter>
    </receiver>

希望我帮助......如果你需要什么,只要问我:)