为什么我的 BroadcastReceiver 会收到 ACTION_USER_PRESENT 两次?

Pat*_*ney 5 android broadcastreceiver android-intent

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

<receiver 
            android:name=".ScreenReceiver" >
            <intent-filter>
                <action 
                    android:name="android.intent.action.USER_PRESENT"/>
            </intent-filter>
        </receiver>
Run Code Online (Sandbox Code Playgroud)

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

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Bha*_*rma 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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

IntentFilter actions = new IntentFilter(Intent.ACTION_USER_PRESENT);
registerReciever(reciever_ob, actions);
Run Code Online (Sandbox Code Playgroud)

3.发送广播

Intent intent = new Intent(Intent.ACTION_USER_PRESENT);
SendBroadcast(intent);
Run Code Online (Sandbox Code Playgroud)

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

  • Intent.ACTION_USER_PRESENT 只能由系统“发送”。 (10认同)