【问题标题】:How to start a foreground service from broadcast receiver?如何从广播接收器启动前台服务?
【发布时间】:2017-12-20 18:10:50
【问题描述】:

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

清单:

<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一个) 但是我应该如何从广播接收器添加它? (即如何从广播接收器启动服务?)

【问题讨论】:

    标签: android service foreground-service


    【解决方案1】:

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

    【讨论】:

    • @Rahulrr2602 是的,您也可以在 onStartCommand 中创建 startForeground。在某些情况下,您应该这样做。如果你做绑定服务(通过bindService),你不能让这个服务前台,直到startServiceonStartCommand使它成为startForeground 。如您所见,在某些情况下,这是将服务作为前台的唯一方法:D
    • 绑定一个服务到底是什么意思?对不起,我有点新。
    • startForegroundService 适用于Build.VERSION_CODES.O 及以上,而不是Build.VERSION_CODES.N
    • @OmarShawky 确实如此,但正如我所说的“一些制造商在 Android N 上向后移植了这些新的背景限制,这就是为什么你也可能支持这个 api。”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多