2012-04-23 18 views
4

我的应用程序需要挣钱的时候,用户解锁屏幕举杯,所以我注册了一个BroadcastReceiver在清单回暖的意图ACTION_USER_PRESENT,就像这样:为什么我的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; 
     } 
    } 
} 

但由于某些原因,日志语句印刷两次,我的服务提出了两个烤面包,而不是一个。有谁知道为什么会发生这种情况,我能做些什么来阻止它?我能忽略一些愚蠢的东西吗?

编辑:我非常抱歉所有人,但我自己发现了这个问题......错误是在应该接收广播的服务类中,我实例化了一个新的ScreenReceiver,它也正在拾取意图。我误解了班级,并认为要获得我必须在那里的意图,但是在删除该块后,我只收到意图一次。 Android没有两次发送这个意图,它只是被拾起两次......感谢您为每个人提供的帮助!

+0

粘贴关于你如何发送广播的代码 – Longerian 2012-04-23 02:51:15

+0

我做了,这是'onReceive'方法。用'context.startService(i)' – 2012-04-23 10:53:14

+0

我的意思是关于发送广播的代码,而不是启动服务 – Longerian 2012-04-23 11:27:03

回答

0

试试这个:

只需创建您的广播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.以上广播对象发送广播之前注册您的接收器。你也可以添加多个动作。

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

发送广播

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

现在你可以删除你的东西,你在你的XML-清单文件已经宣布我不知道到底,但我认为它应该工作。

+5

Intent.ACTION_USER_PRESENT只能由系统*发送*。 – 2014-05-26 13:47:26

相关问题