如何在内容更新时发出不唤醒屏幕的通知?

时间:2019-01-05 13:44:16

标签: java android notifications

我正在使用后台服务来定期获取设备的位置并使用通知显示设备的当前地址。每次在新位置上,我都必须更改通知的内容(地址),这会导致我的设备唤醒。我应该对代码进行哪些更改,以使每次获取新位置时设备都不会唤醒?

我尝试将通知重要性设置为min,它可以工作,但是它禁用了LED,应用程序顶部的栏中没有通知图标,并且扩展的通知不再停留在顶部。

NotificationManager.IMPORTANCE_MIN

每次位置更新时,IMPORTANCE_MIN除外的其他标志都会使通知显示在阴影中,这会导致屏幕从睡眠中唤醒。

private NotificationManager mNotificationManager;

    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.app_name);
        // Create the channel for the notification
        NotificationChannel mChannel =
                new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_MIN);
        // Set the Notification Channel for the Notification Manager.
        mNotificationManager.createNotificationChannel(mChannel);
    }

通知构建器代码

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setLargeIcon(BitmapFactory.decodeResource(this.getResources(),
                    R.mipmap.ic_launcher))
        .addAction(R.drawable.ic_launch, getString(R.string.launch_activity),
                    activityPendingIntent)
        .addAction(R.drawable.ic_cancel, getString(R.string.remove_location_updates),
                    servicePendingIntent)
        .setContentTitle(Utils.getLocationTitle(this))
        .setContentText(Utils.getLocationName(mLocation, this))
        .setOngoing(true)
        .setPriority(Notification.PRIORITY_LOW)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setTicker(text)
        .setDefaults(Notification.DEFAULT_LIGHTS)
        .setLights(Color.GREEN, 100, 2000)

    // Set the Channel ID for Android O.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        builder.setChannelId(CHANNEL_ID); // Channel ID
    }

    return builder.build();

并用于更新内容。

 // Update notification content if running as a foreground service.
 if (serviceIsRunningInForeground(this)) {
     Log.i(TAG, "(onNewLocation) : Notification content updated.");
     mNotificationManager.notify(NOTIFICATION_ID, getNotification());
 }

是否有可能将通知扩展到顶部并具有最低优先级,以免频繁唤醒?

0 个答案:

没有答案