I have a small problem in Androidstudio with my battery status app. I have the following receiver:
<receiver android:name=".PowerConnectionReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.BATTERY_CHANGED"/>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>
But the PowerConnectionReceiver
only work with the ACTION_POWER_* event. The battery change event is not working
public class PowerConnectionReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED))
Toast.makeText(context, "Loading", Toast.LENGTH_SHORT).show();
else if (intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED))
Toast.makeText(context, "not loading", Toast.LENGTH_SHORT).show();
Toast.makeText(context, "test toast", Toast.LENGTH_SHORT).show();
}
}
Intent intent = getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
You forgot to instantiate your PowerConnectionReceiver
.
Intent intent = getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
should be
Intent intent = getApplicationContext().registerReceiver(PowerConnectionReceiver() , new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
Even better would be to keep a reference, so you can unregister again in onStop()
.