为什么我的BroadcastReceiver接收ACTION_USER_PRESENT两次?

时间:2012-04-23 01:01:13

标签: android android-intent broadcastreceiver

我的应用程序需要在用户解锁屏幕时举杯,因此我注册了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没有两次发送意图,只是被捡了两次......感谢大家的帮助!

1 个答案:

答案 0 :(得分:0)

试试这个:

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文件中声明的所有东西,我不确切知道,但我认为它应该有效。