如何从广播接收器启动前台服务?

2 service android foreground-service

我正在创建一个与电池相关的应用程序。我创建了一个在清单中声明的​​广播接收器:

显现 :

<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>
Run Code Online (Sandbox Code Playgroud)

接收者 :

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想添加一个前台通知(就像这个)但是我应该如何从广播接收器添加它?(即我如何从广播接收器启动服务?)

Hey*_*lex 5

在onReceive()中启动服务:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    context.startForegroundService(intent);
} else {
   context.startService(intent); 
}
Run Code Online (Sandbox Code Playgroud)

在服务 onCreate() 中做类似的事情:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
   startForeground(1, new Notification());
}
Run Code Online (Sandbox Code Playgroud)

一些制造商在 Android N 上向后移植了这些新的后台限制,这就是您也可能支持此 api 的原因。