Why is my BroadcastReceiver receiving ACTION_USER_

2019-06-26 01:06发布

问题:

My application needs to make a toast when the user unlocks the screen, so I registered a BroadcastReceiver to pick up the intent ACTION_USER_PRESENT in the manifest, like so:

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

And then I defined a class like this:

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;
        }
    }
}

But for some reason, the Log statement is printed twice, and my service makes two toasts instead of one. Does anyone know why this might be happening, and what I can do to stop it? Am I overlooking something silly?

EDIT: I'm terribly sorry everyone, but I found the problem myself... the bug was that in the service class that was supposed to receive the broadcast, I had instantiated a new ScreenReceiver and it too was picking up the intent. I misunderstood the class and thought that to receive the intent I had to have one there, but after removing that block, I only receive the intent once. Android wasn't sending the intent twice, it was just getting picked up twice... Thank you for your help everyone!

回答1:

Try This:

1. Simply create your broadcast reciever.

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. Register your receiver before sending broadcast with above broadcast object. you can also add multiple actions.

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

3. Send broadcast

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

now you can remove all your stuff which you have declared in your xml-manifest file I dont know exactly but i think it should work.