I am trying to make two toasts: one when the device is charging, and one when it`s not. But the receiver acting crazy, sending many toasts, and crashing the app. I can not f
If you dont want to use the broadcast on your activity, you can use in a service!!
Example:
public class batteryChangeService extends Service {
private BroadcastReceiver mBatteryStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
Toast.makeText(context, "The device is charging", Toast.LENGTH_SHORT).show();
} else {
intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED);
Toast.makeText(context, "The device is not charging", Toast.LENGTH_SHORT).show();
}
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
IntentFilter ifilter = new IntentFilter();
ifilter.addAction(Intent.ACTION_POWER_CONNECTED);
ifilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
registerReceiver(mBatteryStateReceiver, ifilter);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
unregisterReceiver(mBatteryStateReceiver);
}
}
Register the service in your manifest:
<service
android:enabled="true"
android:name="NAME.COMPANY.APPLICATION.batteryChangeService"
android:exported="true"/>
In fact, you can use any BroadcastReceiver inside a service!