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!