检测通知栏中的左滑操作?

5

我希望能够检测用户在通知上向左滑动的动作,这可以是任何通知,因为我将使用通知监听器来检测最近被取消的通知。

是否有一种“全局”手势滑动可以监听,并且只有当我检测到我的通知被取消时才触发我的应用程序特定事件?


2
据我所知,除非使用自定义ROM,否则这是不可能的。 - CommonsWare
2
不可能,但是你可以使用通知按钮。 - Nirel
1个回答

11

尝试以下步骤:

1) 创建一个接收器来处理滑动取消事件:

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

2)在清单文件中添加一条目录:

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

3) 使用唯一id(此处使用通知id)创建待处理意图,否则相同的额外信息将被重复使用于每个取消事件:

3)使用唯一的ID(此处为通知ID)创建待处理操作,否则相同的附加信息将重复用于每个取消事件:

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

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

4) 构建你的通知:

Notification notification = new NotificationCompat.Builder(context)
              .setContentTitle("My App")
              .setContentText("hello world")
              .setWhen(notificationTime)
              .setDeleteIntent(createOnDismissedIntent(context, notificationId))
              .build();

NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, notification);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接