I want all my activities to have knowledge about the power state: is there a charger connected? When the registered receiver receives an ACTION_POWER_CONNECTED
or an ACTION_POWER_DISCONNECTED
a callback to the activity is made to inform the registered activity. Since I want all activities that are part of the application, and I work with this callback method I created an interface which forces the activity to implement powerDisconnected()
and powerConnected();
public interface BrightnessActivityInterface {
void powerDisconnected();
void powerConnected();
}
Because my activities all use the same type of code (eg. screen on and bright lock when connected, and screen dim when power is disconnected) I extended the class Activity
and implemented the BrightnessActivityInterface
:
public class BrightnessActivity extends Activity implements BrightnessActivityInterface {
private ChargingOffReceiver chargingOff;
private ChargingOnReceiver chargingOn;
public BrightnessActivity(){
chargingOn = new ChargingOnReceiver(this);
registerReceiver(chargingOn, new IntentFilter(Intent.ACTION_POWER_CONNECTED));
chargingOff = new ChargingOffReceiver(this);
registerReceiver(chargingOff, new IntentFilter(Intent.ACTION_POWER_DISCONNECTED));
}
@Override
public void onResume() {
super.onResume();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON + WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
@Override
public void onPause() {
super.onPause();
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
public void powerDisconnected() {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
public void powerConnected() {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON + WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
All my activities extend now this BrightnessActivity instead of Activity. Sounds all good so far?
The problem is the first activity I start I get a nullpointer just after the line
registerReceiver(chargingOn, new IntentFilter(Intent.ACTION_POWER_CONNECTED));
'this' has a value (it is my launch activity), and chargingOn is a ChargingOnReceiver. I installed the source but I have no idea what I am looking at.
My class has the rights to register to the ACTION_POWER_CONNECTED
and it worked fine until I derived all my classes from BrightnessActivity
instead of Activity. Please advice.