之前:
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.mile.projectorctrl", "com.mile.projectorctrl.OffScreenPowerService"));
startService(intent);
但是报错,Not allowed to start service Intent
查了百度,说要改成
context.startForegroundService(intent);
服务内的oncreate内部添加:
@Override
public void onCreate() {
super.onCreate();
startForeground(1349, new Notification());
}
当然,不添加可以不可以,我还么时间试验
得这样改:
//适配8.0service
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel mChannel = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mChannel = new NotificationChannel(CHANNEL_ID_STRING, "投影仪将关闭", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(mChannel);
Notification notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID_STRING).build();
startForeground(1349, notification);
}
参考: