【问题标题】:Check notification has closed in android [duplicate]检查通知已在android中关闭[重复]
【发布时间】:2016-06-17 10:11:38
【问题描述】:

我想检查通知是否被用户关闭?这可能吗?我的意思是,如果通过滑动关闭通知,那么我想为 DB 设置一个值。

我知道如何检查通知是否处于活动状态,但不确定如何通过滑动关闭通知?

怎么做?有人可以帮帮我吗?

谢谢!

【问题讨论】:

标签: android notifications android-notifications


【解决方案1】:

试试这个可能对你有帮助

1) 制作发送通知的方法

public void sendNotification(String message, int notificationId) {
    Bundle b = new Bundle();
    Intent intent = new Intent(this, NotificationDismissedReceiver.class);
    intent.putExtra("com.stack.notificationId", notificationId);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(getString(R.string.app_name))
            .setContentText(message)
            .setAutoCancel(true)
            .setDeleteIntent(createOnDismissedIntent(this, 11))
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);
    Notification note = notificationBuilder.build();
    note.defaults |= Notification.DEFAULT_VIBRATE;
    note.defaults |= Notification.DEFAULT_SOUND;

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(notificationId /* ID of notification */, notificationBuilder.build());
}

2) 使BroadcastReciver 用于检测滑动Notification

public class NotificationDismissedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
  int notificationId = intent.getExtras().getInt("com.stack.notificationId");
  /* Your code to handle the event here */
  Log.d("TAG","GET "+notificationId);
}
}

3) 创建解除意图方法

private PendingIntent createOnDismissedIntent(Context context, int notificationId) {
    Intent intent = new Intent(context, NotificationDismissedReceiver.class);
    intent.putExtra("com.stack.notificationId", notificationId);

    PendingIntent pendingIntent =
            PendingIntent.getBroadcast(context.getApplicationContext(),
                    notificationId, intent, PendingIntent.FLAG_ONE_SHOT);
    return pendingIntent;
}

4) 在manifest中添加BroadcastReciver

   <receiver
        android:name=".NotificationDismissedReceiver"
        android:exported="false" >
    </receiver>

5) Notification 的调用方法

sendNotification("hello world",11);

【讨论】:

  • 太棒了。谢谢!如何检查通知是否已被点击?这可能吗?
  • @SanjanaNair 你得到答案了吗?我也需要帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
  • 1970-01-01
相关资源
最近更新 更多