Android 通知自定义视图和按钮按下
Android Notifications custom view and button press
我收到了包含按钮的自定义视图的通知。当用户按下通知中的按钮时,它应该会收到一些 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);
我的广播接收器class
public static class AudioControlListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Button pressed", Toast.LENGTH_SHORT).show();
}
}
您正在使用 PendingIntent.getService()
和具有 BroadcastReceiver
目标的 Intent
。您需要改用 PendingIntent.getBroadcast()
。并确保您的接收器已在清单中注册。
我收到了包含按钮的自定义视图的通知。当用户按下通知中的按钮时,它应该会收到一些 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);
我的广播接收器class
public static class AudioControlListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Button pressed", Toast.LENGTH_SHORT).show();
}
}
您正在使用 PendingIntent.getService()
和具有 BroadcastReceiver
目标的 Intent
。您需要改用 PendingIntent.getBroadcast()
。并确保您的接收器已在清单中注册。