setAutoCancel()在API 26中不起作用

时间:2018-05-10 15:39:13

标签: java android alarmmanager android-notifications android-8.0-oreo

我想通过点击或使用android oreo setAutoCancel(true)滑动来解除通知。

所以这是我的代码:

public class AlarmService extends Service {


private NotificationManager mManager;
.
.
.

@SuppressLint("ClickableViewAccessibility")
@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);


    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        String CHANNEL_ID = getString(R.string.app_name);
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT);
        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);

        Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class);
        intent1.putExtra("code", 1);
        intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this.getApplicationContext(), 2, intent1, PendingIntent.FLAG_CANCEL_CURRENT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);


        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("title")
                .setSmallIcon(R.drawable.logo)
                .setContentIntent(pendingNotificationIntent)
                .setNumber(1)
                .setSound(defaultSoundUri)
                .setContentText("more")
                .setAutoCancel(true).build();

        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        startForeground(2, notification);


    } 

感谢。

1 个答案:

答案 0 :(得分:1)

当服务仍处于前台时,AutoCancel不起作用。 尝试从前台删除服务:

startForeground(2, notification);
stopForeground(false); //false - do not remove generated notification