Android - 如何将正在进行的事件放在状态栏上但不在通知屏幕上?

时间:2016-07-22 10:26:43

标签: android notifications

在我的应用中,我添加了持续通知。通知在状态栏上有一个图标,通知区域中有更多详细信息。

此图片来自Google。这是通知区域:

This image is from Google. This is the notification area

我需要状态栏上的图标始终保持在那里,但用户可以在通知屏幕中关闭通知,这样用户只能使用状态栏上的图标。 我该怎么办?

我的服务代码:

   @SuppressWarnings("static-access")
   @Override
   public int onStartCommand(Intent intent, int flag, int startId)
   {
        super.onStartCommand(intent, START_STICKY, startId);

        ...

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setContentTitle(getString(R.string.myNotificationString))
            .setContentText(string1 + "  |  " + string2)
            .setLargeIcon(appIcon)
            .setSmallIcon(getResources().getIdentifier("icon_" + getCurrentIconNumber(),"drawable", getPackageName()));  // the icon changes every day

        Intent resultIntent = new Intent(this, MainActivity.class);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0 ,resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        Notification notification = mBuilder.build();
        notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;

        mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mNotifyMgr.notify(myRequestCode, notification);

        return START_STICKY;
    }

1 个答案:

答案 0 :(得分:0)

尝试定义resultPendingIntent,如下所示

PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0 ,resultIntent, PendingIntent.FLAG_ONGOING_EVENT);

编辑1

   @SuppressWarnings("static-access")
   @Override
   public int onStartCommand(Intent intent, int flag, int startId)
   {
        super.onStartCommand(intent, START_STICKY, startId);

        ...

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setContentTitle(getString(R.string.myNotificationString))
            .setContentText(string1 + "  |  " + string2)
            .setLargeIcon(appIcon)
            .setSmallIcon(getResources().getIdentifier("icon_" + getCurrentIconNumber(),"drawable", getPackageName()));  // the icon changes every day

        Intent resultIntent = new Intent(this, MainActivity.class);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0 ,resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        Notification notification = mBuilder.build();
        notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;

        mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mNotifyMgr.notify(myRequestCode, notification);

        return START_STICKY;
    }