【问题标题】:How can I retrieve the title of the action button that has been clicked?如何检索已单击的操作按钮的标题?
【发布时间】:2018-01-29 11:34:46
【问题描述】:

我目前正在构建一个需要通过通知栏的操作按钮工作的 Android 应用。

我添加了通知栏和操作按钮。我还添加了一个BroadcastReceiver 来对按钮单击执行一些操作。我的问题是操作是根据单击的操作按钮的标题执行的。请指导我如何获取点击按钮的标题。

这是我的通知创建代码:

 Intent intent = new Intent();
    intent.setAction(AppConstants.YES_ACTION);

    // Open receiver
    PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    //Create Notification using NotificationCompat.Builder
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            // Set Icon
            .setSmallIcon(R.mipmap.ic_launcher)
            // Set Ticker Message
            // .setTicker(getString(R.string.notificationticker))
            // Set Title
            .setContentTitle(getString(R.string.app_name))
            // Set Text
            .setContentText(getString(R.string.notificationtext))
            // Add an Action Button below Notification
            .addAction(R.mipmap.ic_launcher, "Action Button", pIntent)
            // Set PendingIntent into Notification
            .setContentIntent(pIntent)
            // Dismiss Notification
            .setAutoCancel(true);

    for(int l = 0; l<btnNames.length; l++){
        if(!btnNames[l].isEmpty()){
            builder.addAction(R.mipmap.ic_launcher, btnNames[l],pIntent);
       //     intent.putExtra("Btn"+(l+1), btnNames[1]);
        }
    }

    // Create Notification Manager
    NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    // Build Notification with Notification Manager
    notificationmanager.notify(0, builder.build());

下面是广播接收器代码:

public class notificationReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        String notificationAction = intent.getAction();

        //the title retrieval code goes here

        if(notificationAction.equals(AppConstants.YES_ACTION)){
            //some work is done here
        }

    }
}

【问题讨论】:

  • btnNames 是一个字符串数组。我使用这些作为我的操作按钮名称。它是动态加载的。

标签: android notifications android-notifications


【解决方案1】:

第 1 步:将所有 Intent/PendingIntent/Notification 创建逻辑移到循环内

第 2 步:将操作按钮的标识符作为附加到您用于 PendingIntentIntent

第 3 步:为 getBroadcast() 方法的第二个参数为每个 PendingIntent 使用一个不同的数字,以便为每个 PendingIntent 获得不同的实例

第 4 步:让您的 BroadcastReceiver 阅读额外内容以确定被点击的操作

或者……

第 1 步:将所有 Intent/PendingIntent/Notification 创建逻辑移到循环内

第 2 步:在每个 Intent 对象中使用唯一的操作字符串

第 3 步:让您的 BroadcastReceiver 读取操作字符串以确定被点击的操作

或者……

第 1 步:为每个操作按钮使用不同的 BroadcastReceivers

【讨论】:

  • 这对我有用。我能够获得操作按钮来运行方法。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-14
  • 2019-02-09
  • 1970-01-01
  • 2013-01-02
  • 1970-01-01
  • 1970-01-01
  • 2015-06-05
相关资源
最近更新 更多