【问题标题】:How to add listener on a button in a notification (custom layout)如何在通知中的按钮上添加侦听器(自定义布局)
【发布时间】:2013-11-27 11:11:07
【问题描述】:

我有一个类似这样的通知布局:

我的服务正在进行。我想在按下停止按钮时向我的服务发送通知/事件。不需要通知视图上的点击事件。

按下按钮时,我希望我的服务停止。

目前,我正在尝试通过向活动发送广播来做到这一点(因为我没有找到直接通知服务按钮按下的方法)。

我当前的代码是:

Intent intent = new Intent(this, MediaEventsReceiver.class);
PendingIntent pending = PendingIntent.getActivity(this, 1, intent, 0);
contentView.setOnClickPendingIntent(R.id.btnStop, pending);

我还在清单中添加了接收器:

<receiver android:name=".activities.SplashActivity$MediaEventsReceiver" />

请使用代码示例进行说明。

【问题讨论】:

    标签: android button notifications listener


    【解决方案1】:

    我正在使用 SINGLE 活动开发音乐播放器应用。您可以像这样将侦听器添加到您的按钮:

    1. 绑定意图

    Intent intent = new Intent("ACTION_NAME"); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); views.setOnClickPendingIntent(R.id.previousImageView, pendingIntent);

    1. 实现自定义广播接收器

    private class ActionBroadcastReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { switch (intent.getAction()) { case "ACTION_NAME": { doSomething(); break; } } } }

    1. 注册您的广播接收器

    IntentFilter filter = new IntentFilter(); filter.addAction("ACTION_NAME"); ActionBroadcastReceiver actionBroadcastReceiver = new ActionBroadcastReceiver(); registerReceiver(actionBroadcastReceiver, filter);

    【讨论】:

      【解决方案2】:

      已解决:

      我使用了另一个由 PendingIntent 调用按钮单击的活动。 新活动绑定服务并向其发送停止消息。 紧随其后,它会自行解除绑定并结束。

      仍然:

      我想要一个不涉及第三项活动的解决方案。应该有一种方法可以让单击通知中的按钮直接通知服务并且服务会自行停止。此任务不需要任何活动。

      【讨论】:

      • 没有。我按照上面提到的方式做到了。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-20
      • 1970-01-01
      • 1970-01-01
      • 2011-08-21
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多