Skip to content Skip to sidebar Skip to footer

Battery Changed Broadcast Receiver Crashing App On Some Phones

I activate my application whenever the phone get plugged in a power source. This is my manifest

Solution 1:

You are getting a ReceiverCallNotAllowedException.

This exception is thrown from registerReceiver(BroadcastReceiver, IntentFilter) and bindService(Intent, ServiceConnection, int) when these methods are being used from an BroadcastReceiver component. In this case, the component will no longer be active upon returning from receiving the Intent, so it is not valid to use asynchronous APIs.

This means, that you can't register a BroadcastReceiverinside a BroadcastReceiver.

Edit: Working example for a BroadcastReceiver, which listens to the ACTION_BATTERY_CHANGED Intent:

privateint mBatteryLevel;
    private IntentFilter mBatteryLevelFilter;

    BroadcastReceivermBatteryReceiver=newBroadcastReceiver() {
        @OverridepublicvoidonReceive(Context context, Intent intent) {
            mBatteryLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            Toast.makeText(context, "Current Battery Level: " + mBatteryLevel, Toast.LENGTH_LONG).show();
        }
    };

    privatevoidregisterMyReceiver() {
        mBatteryLevelFilter = newIntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(mBatteryReceiver, mBatteryLevelFilter);
    }

Now you just have to call registerMyReceiver().

Post a Comment for "Battery Changed Broadcast Receiver Crashing App On Some Phones"