Debora Carnevali
Debora Carnevali

Reputation: 28

Android BroadcastReceiver start activity

With this BroadcastReceiver I can launch an activity every time the device screen turns off. The only problem is that the same activity is started 2 times. I do not understand the issue

public class ScreenReceiver extends BroadcastReceiver {

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

        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            intent = new Intent(context, Login2.class);
            context.startActivity(intent);               
        }
    }
}

start receiver into oncreate of activity

IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_ON);
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, intentFilter);

manifest

<receiver android:name="utils.ScreenReceiver"
          android:enabled="true">
    <intent-filter>
        <action android:name="android.intent.action.SCREEN_OFF" />
        <action android:name="android.intent.action.SCREEN_ON" />
    </intent-filter>
</receiver>

Upvotes: 1

Views: 482

Answers (1)

Bobbake4
Bobbake4

Reputation: 24847

You are effectively registering two instances of your ScreenReceiver and thus responding twice, and creating two versions of your Activity. You are first registering it system wide using the <intent-filter> applied in your manifest. Secondly, you are registering a different instance of ScreenReceiver with your call to registerReceiver(mReceiver, intentFilter);. You should only use one mechanism for registering your BroadcastReceiver.

Also, make sure you are making a call to unregister the receiver if you stick with the Activity registerReceiver(mReceiver, intentFilter); method.

Upvotes: 2

Related Questions