SagiLow SagiLow - 8 days ago 7
Android Question

Why onReceive is not called extending BroadcastReceiver in Android

the onReceive method isn't called for some reason

I've not applied any filters or anything,

Here is the class :

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


Here is the declaration in the manifest (child of Application)

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


Edit :
This is the filter i tried to add (inside the onReceive() )

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


I get an error :

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

Sam Sam
Answer

If you always want to listen for ACTION_USER_PRESENT, try:

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

Explanations

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

You must use registerReceiver() with a Context, for example context.registerReceiver(...). But:

This is the filter i tried to add (inside the onReceive() )

It doesn't make sense to register a receiver inside onReceive() because onReceive() will not run until you have registered a receiver... So it will never happen. You can put this code in onCreate() in your Activity, like this:

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

This will only listen for ACTION_USER_PRESENT while your app is already running.

Comments