我正在创建一个与电池相关的应用程序。 我创建了一个在 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/