【问题标题】:Why is my BroadcastReceiver receiving ACTION_USER_PRESENT twice?为什么我的 BroadcastReceiver 收到 ACTION_USER_PRESENT 两次?
【发布时间】:2020-09-25 08:00:55
【问题描述】:

我的应用程序需要在用户解锁屏幕时祝酒,所以我注册了一个BroadcastReceiver 以在清单中获取意图ACTION_USER_PRESENT,如下所示:

<receiver 
            android:name=".ScreenReceiver" >
            <intent-filter>
                <action 
                    android:name="android.intent.action.USER_PRESENT"/>
            </intent-filter>
        </receiver>

然后我定义了一个这样的类:

package com.patmahoneyjr.toastr;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class ScreenReceiver extends BroadcastReceiver {

    private boolean screenOn;
    private static final String TAG = "Screen Receiver";

    @Override
public void onReceive(Context context, Intent intent) {

    if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
        screenOn = true;
        Intent i = new Intent(context, toastrService.class);
        i.putExtra("screen_state", screenOn);
        context.startService(i);
        Log.d(TAG, " The screen turned on!");
    } else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        screenOn = false;
        }
    }
}

但是由于某种原因,Log 语句被打印了两次,我的服务做了两次 toast 而不是一次。有谁知道为什么会发生这种情况,以及我能做些什么来阻止它?我忽略了一些愚蠢的事情吗?

编辑:非常抱歉大家,但我自己发现了问题......错误是在应该接收广播的服务类中,我已经实例化了一个新的 ScreenReceiver,它也正在接收意图。我误解了课程,并认为要接收意图,我必须在那里有一个,但是在删除该块之后,我只收到一次意图。 Android 没有发送两次意图,只是被接收了两次...谢谢大家的帮助!

【问题讨论】:

  • 粘贴有关如何发送广播的代码
  • 我做到了,那是在 onReceive 方法中。 context.startService(i)
  • 我的意思是关于发送广播的代码,而不是启动服务
  • 哦,我就是这么干的……有没有更好的办法?

标签: android android-intent broadcastreceiver


【解决方案1】:

试试这个:

1. 只需创建您的广播接收器。

BroadcastReceiver reciever_ob = new BroadcastReceiver( 

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(action.equals(Intent.ACTION_USER_PRESENT)){
             //DO YOUR WORK HERE
        }
    }
}

2. 在使用上述广播对象发送广播之前注册您的接收器。您还可以添加多个操作。

IntentFilter actions = new IntentFilter(Intent.ACTION_USER_PRESENT);
registerReciever(reciever_ob, actions);

3.发送广播

Intent intent = new Intent(Intent.ACTION_USER_PRESENT);
SendBroadcast(intent);

现在您可以删除您在 xml-manifest 文件中声明的所有内容,我不确切知道,但我认为它应该可以工作。

【讨论】:

  • Intent.ACTION_USER_PRESENT 只能由系统发送
猜你喜欢
  • 2011-12-12
  • 1970-01-01
  • 2017-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-22
  • 1970-01-01
相关资源
最近更新 更多