有关Andoid 9的startForeground的错误通知

时间:2019-07-11 15:58:13

标签: android androidx foreground-service foregroundnotification

前台服务通知适用于android 8,但不适用于Android9。在我授予所有权限并显示错误消息后,应用程序崩溃了

android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x42 color=0x00000000 vis=PRIVATE semFlags=0x0 semPriority=0 semMissedCount=0)

我的清单有权使用前台服务

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

代码

@Override
public void onCreate() {
    super.onCreate();
    mScheduler = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);

    startForeground(NOTIFICATION_ID, getNotification(R.string.notification_title, R.string.sensor_disconnected, R.drawable.ic_stat_disconnected));

    log(TAG, "Create Service");
}

public Notification getNotification(int title, int text, int icon) {
    NotificationCompat.Builder foregroundNotification = new NotificationCompat.Builder(this);
    foregroundNotification.setOngoing(true);

    foregroundNotification.setContentTitle(getText(title))
            .setContentText(getText(text))
            .setSmallIcon(icon);

    return foregroundNotification.build();
}

private void updateNotification(int title, int text, int icon) {
    Notification notification = getNotification(title, text, icon);

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(NOTIFICATION_ID, notification);
}

private void removeNotification() {
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.cancel(NOTIFICATION_ID);
}

private void setConnectionState(Boolean connected) {
    if (connected) {
        updateNotification(R.string.notification_title, R.string.sensor_connected, R.drawable.ic_stat_connected);
        Log.d("S: CONNECTION_STATUS", "sensor_connected");

        DateTime timestamp= new DateTime();

        HashMap<String, String> connectionStatus = new HashMap<>();
        connectionStatus.put(MOVISENS_CONNECTION_STATUS,"sensor_connected");

0 个答案:

没有答案