Android Notifications自定义视图和按钮按下

时间:2016-10-12 10:08:53

标签: android android-notifications

我收到包含按钮的自定义视图的通知。当用户在通知中按下按钮时,它应该获得一些Toast消息。但是Toast永远不会显示,因为永远不会调用onReceive。我做错了什么?

        int icon = R.drawable.play;
    long when = System.currentTimeMillis();
    Notification notification = new Notification(icon, "Custom Notification", when);

    RemoteViews notificationView = new RemoteViews(this.getPackageName(),R.layout.notification);
    PendingIntent listenerIntent = PendingIntent.getService(this, 0, new Intent(this, AudioControlListener.class), 0);
    notificationView.setOnClickPendingIntent(R.id.background, listenerIntent);

    notification.contentView = notificationView;

    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.contentIntent = contentIntent;

    startForeground(1, notification);

我的广播接收机课程

 public static class AudioControlListener extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "Button pressed", Toast.LENGTH_SHORT).show();
        }
    }

1 个答案:

答案 0 :(得分:2)

您正在使用PendingIntent.getService(),其中Intent的目标为BroadcastReceiver。您需要使用PendingIntent.getBroadcast()代替。并确保您的Receiver已在清单中注册。