user8660130
user8660130

Reputation:

How to start a foreground service from broadcast receiver?

I am creating a battery related app. I have created a broadcast receiver declared in manifest :

Manifest :

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

Receiver :

public class PowerConnectionReceiver extends 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();
        }
    }
}

I want to add a foreground notification (like this one) But how should i add it from broadcast receiver? (i.e how can i start a service from broadcast receiver?)

Upvotes: 2

Views: 10694

Answers (1)

HeyAlex
HeyAlex

Reputation: 1746

in onReceive() start service:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    context.startForegroundService(intent);
} else {
   context.startService(intent); 
}

And in service onCreate() make something like that:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
   startForeground(1, new Notification());
}

Some manufacturers have backport on Android N these new background limitations, that's why you might to support this api too.

Upvotes: 5

Related Questions