I want a Broadcastreceiver to be called every time Intent.ACTION_BATTERY_CHANGED gets broacasted so I can track some data.
What I have now:
public class ReceiverApplication extends Application {
@Override
public void onCreate() {
// Register Receiver
}
public static BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Start Service to progress data
}
};
}
This works fine UNTIL I use the Recent Apps "Taskmanager" to swipe away one of my preference Screens or my main activity. Then the BroadcastReceiver doesnt get called anymore. If I start one of my activities, onCreate() of ReceiverApplication gets called and it starts working again.
I could work around that by having a empty service running all the time. The service doesn't seem to get killed by swiping an activity away and onCreate() gets called after some time and restarts the BroadcastReceiver without doing anything. The problem here is that I don't want a service to run all the time.
So, how can I get a Broadcastreceiver outside of any Acitivity or Service which can receive Broadcasts as long as the user wants?
I want a Broadcastreceiver to be called every time Intent.ACTION_BATTERY_CHANGED gets broacasted so I can track some data.
This broadcast may be sent a lot. Hence, Android only allows running applications to receive this broadcast, so it does not have to fork a bunch of processes just to tell a bunch of apps "hey, the battery level changed".
This works fine UNTIL I use the Recent Apps "Taskmanager" to swipe away one of my preference Screens or my main activity. Then the BroadcastReceiver doesnt get called anymore.
That act terminates your process.
So, how can I get a Broadcastreceiver outside of any Acitivity or Service which can receive Broadcasts as long as the user wants?
Normally, you would register for the broadcast in the manifest. For ACTION_BATTERY_CHANGED
, this is not possible.
Bear in mind that you can poll ACTION_BATTERY_CHANGED
-- instead of calling registerReceiver()
with an actual BroadcastReceiver
, pass in null
. The return value of registerReceiver()
will be the last ACTION_BATTERY_CHANGED
Intent
. So, if you can get away with finding the battery level every few minutes, use AlarmManager
to wake up every so often and check the current battery level.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With