向Android自定义通知添加操作

时间:2015-07-07 12:25:49

标签: android notifications android-notifications android-pendingintent

我已阅读有关通知的Android开发人员指南,并且我创建了一个类似于以下内容的显示:

private static void initNotificationCompatObject()
{
    mBuilder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.icon).setContentTitle("My notification")
            .setContentText("Test!");
    Intent resultIntent = new Intent(context, MainActivity.class);
    PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
}

通知本身已显示并正常工作。

我想要做的是在按下通知后添加要执行的其他操作。我想在我的活动中(或在构建器的某种动作监听器中)读取通知ID并执行某些操作取决于Id。如何才能实现这样的目标?

1 个答案:

答案 0 :(得分:0)

  public static final int NOTIFICATION_ID_FIRST = 1000;
  public static final int NOTIFICATION_ID_SECOND = 1002;
  notify(NOTIFICATION_ID_FIRST);
  notify(NOTIFICATION_ID_SECOND);

通知:

    private static void notify(int id)
    {

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.icon).setContentTitle("My notification")
                .setContentText("Test!");
        Intent resultIntent = new Intent(context, MainActivity.class);
        resultIntent.putExtra("NOTIFICATION_ID", String.valueOf(id));
        PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);


        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(id , mBuilder.build());
    }

MainActivity:

        int notificationId = Integer.parseInt(getIntent().getStringExtra("NOTIFICATION_ID"));
        if(notificationId == NOTIFICATION_ID_FIRST){
            //handle
        }else if (notificationId == NOTIFICATION_ID_SECOND){
            ...
        }