6

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 find the problem. thnx! This is the receiver in Main activity:

public class PowerConnectionReceiver extends BroadcastReceiver {

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

        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);

        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                status == BatteryManager.BATTERY_STATUS_FULL;
        if (isCharging){
            Toast.makeText(context, "The device is charging", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(context, "The device is not charging", Toast.LENGTH_SHORT).show();

        }

    }
}

This is the manifest:

<receiver android:name=".view.MainActivity$PowerConnectionReceiver">
        <intent-filter>
            <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
            <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
        </intent-filter>
    </receiver>
Gidi Sprintzin
  • 365
  • 1
  • 2
  • 15
  • Please Share the Log cat traces so that we can identify exact problem that why android app is crashing – Ashish Agrawal Sep 16 '15 at 12:31
  • Unable to instantiate receiver com.gidi.places.easymap.view.MainActivity$PowerConnectionReceiver: java.lang.InstantiationException: class com.gidi.places.easymap.view.MainActivity$PowerConnectionReceiver has no zero argument constructor – Gidi Sprintzin Sep 16 '15 at 12:36
  • register receiver in onResume and unRegisterReceiver in OnPause – Ashish Agrawal Sep 16 '15 at 12:42

6 Answers6

16

I found a great way to check if the device is charging, or not. Here is the code of the receiver class:

public class PowerConnectionReceiver extends BroadcastReceiver {

    public PowerConnectionReceiver() {
    }

    @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();
        }
    }


}

Registering it on onResume:

receiver = new PowerConnectionReceiver();

    IntentFilter ifilter = new IntentFilter();
    ifilter.addAction(Intent.ACTION_POWER_CONNECTED);
    ifilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
    registerReceiver(receiver, ifilter);

Unregistered on onPause:

        unregisterReceiver(receiver);

Works fine!

Gidi Sprintzin
  • 365
  • 1
  • 2
  • 15
1

you can use this code

  IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = this.registerReceiver(null, ifilter);

//charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;

if(isCharging == true){
    tvCharged.setText("CHARGING");
}else{
    tvCharged.setText("NOT CHARGING");
}

//how are we charging
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

if(usbCharge == true){
    tvHowCharging.setText("USB");
}else{
    tvHowCharging.setText("ELECTRICAL OUTLET");
}

//get battery level and print it out
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
tvLevelOutput.setText(level + " / 100");
pbLevel.setProgress(level);
pbLevel.invalidate();

//get battery temperatur
int temp = batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
tvTempOutput.setText(temp + "Grad");
pbTemp.incrementProgressBy(temp);
pbTemp.invalidate();

//get battery voltage
int voltage = batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
tvVoltageOutput.setText(voltage + " V");
pbVoltage.incrementProgressBy(voltage);
pbVoltage.invalidate();
Ashish Agrawal
  • 1,977
  • 2
  • 18
  • 32
0

register Receiver in Activity OnResume in place of Manifiest take global variable

boolean isToastShown = false;

and code of receiver is

 if (isCharging){
    if(!isToastShown){
        Toast.makeText(context, "The device is charging", Toast.LENGTH_SHORT).show();
        }
    }else{
        isToastShown = false;
        Toast.makeText(context, "The device is not charging", Toast.LENGTH_SHORT).show();

    }
Ashish Agrawal
  • 1,977
  • 2
  • 18
  • 32
  • Thnx! I registered it like you said, it`s not crashing anymore, but i still get a number of toasts (three of four) instead of just one.... – Gidi Sprintzin Sep 16 '15 at 13:03
  • Thanx again, but it didn`t work, the problem is in the receiver itself, i think, because it `s receiving a number of intents, while it should not... – Gidi Sprintzin Sep 16 '15 at 13:19
0

BroadcastReceiver receives charging state. That's why continuously triggering toast message.

 boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                status == BatteryManager.BATTERY_STATUS_FULL

instead of

  boolean isCharging =status= BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;

please refer this link: Check if device is plugged in

Community
  • 1
  • 1
  • tried it too. The "not charging" toast appears once, but the other one with "charging" appears three or four times in a row... weird.... – Gidi Sprintzin Sep 16 '15 at 13:25
0

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!

Rodrigo Gontijo
  • 587
  • 1
  • 9
  • 21
0

The same thing happened to me once and I received the broadcast several times.
This sometimes happens if we register the same broadcast several times and we do not free it by re-registering it.
Make sure you don't call twice to register the broadcast.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
EJV
  • 1