0

I wrote an application that shows a toast whenever the device dis/connects to the power. I wrote it step by step with this tutorial (section 1).

The app does nothing. I put a breakpoint in the begining of onReceive to see if the app go to there and found out that the app doesn't get to onReceive when I dis/connected the device.

What is the problem in the app?

I didn't change MainActivity at all.

Here's the class I wrote:

public class CustomReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String intentAction = intent.getAction();
        String toastMessege = null;
        switch (intentAction) {
            case Intent.ACTION_POWER_CONNECTED:
                toastMessege = "Power connected!";
                break;
            case Intent.ACTION_POWER_DISCONNECTED:
                toastMessege = "Power disconnected!";
                break;
        }
        Toast.makeText(context,toastMessege,Toast.LENGTH_SHORT).show();
    }
}

And here's the AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="android.example.powerreceiver">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <receiver
            android:name=".CustomReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
            </intent-filter>
        </receiver>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
Santanu Sur
  • 10,997
  • 7
  • 33
  • 52
J. Doe
  • 299
  • 3
  • 12
  • 1
    That course you linked is deprecated. Implicit broadcast receivers declared in manifest will no longer work since android Oreo unless they're in the [exceptions](https://developer.android.com/guide/components/broadcast-exceptions) list. – Pawel Oct 23 '19 at 13:26
  • also related: https://stackoverflow.com/questions/47618775/intent-action-power-connected-not-working-when-added-inside-androidmanifest-xm – Richard Le Mesurier Oct 23 '19 at 13:34
  • Is there a replacement for these intent in the newer versions? – J. Doe Oct 23 '19 at 13:43

1 Answers1

0

You need to register these at runtime for them to work

Lena Bru
  • 13,521
  • 11
  • 61
  • 126