1

I'm making a university project where I have to make a charger alarm. I select a ringtone, enter a pin, then plug in a charger. When I plug out, it moves to another activity where the phone starts ringing, the screen is locked and can only proceed if provided a correct pin code.

I'm stuck at the point where I have to move from one activity to another when the charger disconnects.

My code is not working. This is the receiver in the manifest file:

<receiver android:name=".MainActivity$PowerConnectionReceiver">
    <intent-filter>
            <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
    </intent-filter>
</receiver>

This is the broadcast receiver I made in the MainActivity:

public class PowerConnectionReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        // an Intent broadcast.
        Toast.makeText(context, "The device is not charging", Toast.LENGTH_SHORT).show();
        Intent myintent = new Intent(MainActivity.this,setter.class);
        startActivity(myintent);
    }
}
Alexandr Shurigin
  • 3,921
  • 1
  • 13
  • 25

2 Answers2

1

Please see:

You cannot receive this through components declared in manifests, only by explicitly registering for it with...

https://developer.android.com/reference/android/content/Intent.html#ACTION_BATTERY_CHANGED

And did you set the corresponding permission?

<uses-permission android:name="android.permission.BATTERY_STATS"/>
Martin Pfeffer
  • 12,471
  • 9
  • 59
  • 68
0

Your intent has not correct parameters.

Intent myintent = new Intent(MainActivity.this,setter.class);

Change should be:

Intent myintent = new Intent(context, MainActivity.class)

Make sure your <receiver></receiver> tags are out of the activity tag in Manifest. Place them in application level.

coroutineDispatcher
  • 7,718
  • 6
  • 30
  • 58
  • does `onReceived()` ever get called? – coroutineDispatcher Dec 10 '19 at 14:31
  • Probably not. I've tried setting text to a TextView inside onReceive(). The textView doesn't change. Maybe I'm doing something wrong. I'm new to android studio and java so I'm not sure what's the problem with it. It seems fine. – Haseeb Aslam Dec 10 '19 at 14:45
  • I got the weirdest project and my instructor made it up on the spot while assigning it to me. I have to present it on Thursday and I've been stuck on it for days. – Haseeb Aslam Dec 10 '19 at 14:50