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

标签 android service foreground-service

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

list :

<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>

接收者:

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();
        }
    }
}

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

最佳答案

在onReceive()中启动服务:

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

并在服务 onCreate() 中进行类似的操作:

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

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

关于android - 如何从广播接收器启动前台服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47912023/

相关文章:

windows - Google 云端硬盘即服务或后台操作

android - 前台服务和 WakeLocks 不适用于华为设备

java - startForegroundService() 没有调用 startForeground(),但它调用了

java - 自定义数组循环推送数据

android - 如何安装不同版本的 Android?

service - Angular2 - 在 routerOnDeactivate() 中停止/取消/清除可观察到的

powershell - 在Powershell中使用Export-Csv时,如何从输出中排除#TYPE Selected.System.Management.ManagementObject

Android - Foreground 在 Oreo 中不工作。操作系统在一段时间后终止服务

java - Android/java - 如何执行该循环等待执行操作

android - RelativeLayout 通过代码