java - 奥利奥前台服务异常
问题描述
我在上下文中调用了 startForegroundService 而不是 startService:
final Intent intent = new Intent(this, LocationService.class);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
}else {
startService(intent);
}
它在 LocationService 中调用了 onStartCommand:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String CHANNEL_ID = "channel_01";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"Channel of Location",
NotificationManager.IMPORTANCE_DEFAULT);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("")
.setContentText("")
.setAutoCancel(true)
.build();
startForeground(1, notification);
} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentTitle("")
.setContentText("")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true);
Notification notification = builder.build();
startForeground(1, notification);
}
return START_NOT_STICKY;
}
我有一个这样的错误:
致命异常:android.app.RemoteServiceException:Context.startForegroundService() 没有在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:2101) 在 android.os.Handler.dispatchMessage(Handler .java:108) 在 android.os.Looper.loop(Looper.java:166) 在 android.app.ActivityThread.main(ActivityThread.java:7425) 在 java.lang.reflect.Method.invoke(Method.java)在 com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
解决方案
推荐阅读
- iframe - Youtube 嵌入显示不需要的顶部栏,即使 showinfo=0
- c - 关于 C 函数
- java - 导入 java.util.* 和 java.util.concurrent.* 的区别
- python - 如何在 matplotlib 中生成密钥
- swift - 可选数组??NSNull() - 表达式太复杂,无法在合理的时间内解决
- python - put_object into s3 boto3 给出了一个损坏的文件
- python - 如何修改 contenteditable 元素的 innerHTML
- python - 无法从scrapy中的html获取电子邮件
- python - 从 Python 3.5 编译 Oracle 包时,Oracle 12c DBA_IDENTIFIERS 未填充
- angular - VS Code:如何在 Angular 模板文件中重构(重命名变量)?