Search code examples
androidbroadcastreceiver

BroadcastReceiver in activity


I want to change the KeepScreenOn value of my activity, therefore I want to use an BroadcastReceiver inside the activity. I register the receiver in onCreate with:

registerReceiver(receiver, new IntentFilter("ACTION_POWER_CONNECTED"));
            registerReceiver(receiver, new IntentFilter("ACTION_POWER_DISCONNECTED"));

and unregister it in onPause:

unregisterReceiver(receiver);

The receiver looks like this:

    private BroadcastReceiver receiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(Intent.ACTION_POWER_CONNECTED)) {
            findViewById(R.id.fullscreen_content).setKeepScreenOn(true);
        } else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
            media=MediaPlayer.create(context,R.raw.battery);
            media.start();
            findViewById(R.id.fullscreen_content).setKeepScreenOn(false);
        }
    }
};

No errors, it simply does not change anything when disconnecting/connecting to power source. Any suggestions?


Solution

  • You should use the defined constants, not string values :

    IntentFilter(Intent.ACTION_POWER_CONNECTED)
    

    instead of :

    IntentFilter("ACTION_POWER_CONNECTED")