简体   繁体   English

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

[英]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? 我想添加前景通知(就像这个 )但是我应该如何从广播接收器中添加它? (ie how can i start a service from broadcast receiver?) (即我如何从广播接收器开始服务?)

in onReceive() start service: 在onReceive()启动服务:

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

And in service onCreate() make something like that: 在服务onCreate()做类似的东西:

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. 一些制造商已经在Android N上支持这些新的背景限制,这就是为什么你也可以支持这个api的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM