7


由于某种原因我没有应用任何过滤器或任何东西,没有调用 onReceive 方法,

这是课程:

import java.util.ArrayList;
import java.util.Calendar;

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

public class RegisterListener extends BroadcastReceiver {
private final int DELAY_TIME = 5;
private int m_seconds = 0;
private int m_minutes = 0;
private int m_hours   = 0;
static ArrayList<BroadcastReceiverListener> listeners = new ArrayList<BroadcastReceiverListener>();

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

    Log.d("ScreenReceiver Action:",intent.getAction());

    Calendar c = Calendar.getInstance(); 
    m_seconds = c.get(Calendar.SECOND);
    m_minutes = c.get(Calendar.MINUTE);
    m_hours = c.get(Calendar.HOUR);

    for (BroadcastReceiverListener listener:listeners){
           listener.onReceive(m_hours, m_minutes, m_seconds);
        }
}


public static void addBroadcastReceiveListener (BroadcastReceiverListener listener){
    if(!listeners.contains(listener)){
        listeners.add(listener);
    }
}

public void removeBroadcastReceiveListener (BroadcastReceiverListener listener){
    if(listeners.contains(listener)){
        listeners.remove(listener);
    }
}

这是清单中的声明(应用程序的子项)

<receiver android:name=".RegisterListener"></receiver>

编辑: 这是我尝试添加的过滤器(在 onReceive() 内)

    IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
    BroadcastReceiver mReceiver = new RegisterListener();
    registerReceiver(mReceiver, filter);

我收到一个错误:

The method registerReceiver(BroadcastReceiver, IntentFilter) is undefined for the type RegisterListener
4

2 回答 2

12

如果您总是想听ACTION_USER_PRESENT,请尝试:

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

解释

The method registerReceiver(BroadcastReceiver, IntentFilter) is undefined for the type RegisterListener

您必须registerReceiver()与上下文一起使用,例如context.registerReceiver(...). 但:

这是我尝试添加的过滤器(在 onReceive() 内)

在里面 注册一个接收器是没有意义的,onReceive()因为onReceive()在你注册一个接收器之前不会运行......所以它永远不会发生。您可以将此代码放入onCreate()您的活动中,如下所示:

IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
BroadcastReceiver mReceiver = new RegisterListener();
registerReceiver(mReceiver, filter);

这只会ACTION_USER_PRESENT 您的应用程序已经运行时侦听。

于 2013-03-29T16:05:57.967 回答
0
IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BROADCAST_STARTED_ACTION);
        intentFilter.addAction(BROADCAST_SUCCESS_ACTION);
        intentFilter.addAction(BROADCAST_FAILURE_ACTION);
        LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(broadCastReceiver, intentFilter);
于 2018-01-17T12:09:52.163 回答