有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java广播接收器未检测到按键事件

我正在尝试在我的应用程序中接收电源按钮事件。我在清单文件中添加了以下代码,然后在broadcast receiver类的receive方法中显示了toast,但代码仍然不起作用。我错过什么了吗

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

问候


共 (1) 个答案

  1. # 1 楼答案

    是的,你想做的可能只是我想澄清的几件事,在屏幕关闭时显示toast是没有用的,而且检测电源按钮和屏幕状态是一样的,我将向你展示如何检测屏幕状态和仅显示toast,但电源按钮我仍然不知道如何检测它,因为电源按钮只由系统管理,我认为您需要root来调整或添加电源按钮的功能。以下是您需要的代码:

    1-你需要一个可以启动/停止检测屏幕状态的活动,一个让你的应用程序在后台工作的服务,最后是广播接收器。因此,从活动开始,你应该开始服务:

    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-你的broadcasrtreceiver:

    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>
    

    希望我能帮忙。。。如果你需要什么,就问我:)