我在stackoverflow上看到很多帖子,但我无法找到解决问题的方法。
我收到了一个自定义内容视图的通知,其中包含一个与RemoteViews链接的按钮。我按照此链接(Adding button action in custom notification)将操作附加到我的按钮,但我的BroadcastReceiver从未被触发。代码:
private void createNotification(int index){
final int id = index;
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification);
contentView.setInt(R.id.container,"setBackgroundColor",ContextCompat.getColor(this,BG_COLORS[index]));
contentView.setImageViewResource(R.id.logo,BUTTON_OFF[index]);
contentView.setTextViewText(R.id.sound, getString(SOUND_NAME[index]) );
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContent(contentView);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, id, notificationIntent, 0);
Notification notification = mBuilder.build();
notification.contentIntent = contentIntent;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent closeButton = new Intent(this,StopReceiver.class);
closeButton.setAction(StopReceiver);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, closeButton,0);
contentView.setOnClickPendingIntent(R.id.stop,pendingIntent);
mNotificationManager.notify(id, notification);
}
public static class StopReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//Never called
Log.d(LOGTAG,"Received Cancelled Event");
...
}
}
我还在我的AndroidManifest.xml中声明了我的接收器:
<receiver android:name="StopReceiver" android:enabled="true" />
谢谢。
答案 0 :(得分:0)
您将RemoteViews的setOnClickPendingIntent设置为通知的自定义RemoteView后设置。
在调用setContent之前尝试设置setOnClickPendingIntent。 E.g:
RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification);
contentView.setInt(R.id.container,"setBackgroundColor",ContextCompat.getColor(this,BG_COLORS[index]));
contentView.setImageViewResource(R.id.logo,BUTTON_OFF[index]);
contentView.setTextViewText(R.id.sound, getString(SOUND_NAME[index]) );
Intent closeButton = new Intent(this,StopReceiver.class);
closeButton.setAction(StopReceiver);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, closeButton,0);
contentView.setOnClickPendingIntent(R.id.stop,pendingIntent);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContent(contentView);
答案 1 :(得分:0)
如果您在小部件中使用列表视图,则在各个项目上设置PendingIntents会非常昂贵,因此是不允许的。而是可以在集合上设置一个PendingIntent模板,您可以使用setOnClickFillInIntent()
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_article_list_item);
Intent intent = new Intent(context, ArticleDetailActivity.class); //activity to start
intent.putExtra("article",articleList.get(position));//any data to send
//don't use pending intent here
views.setOnClickFillInIntent(R.id.widget_item, intent);
您可以在覆盖方法getViewAt(final int position) { ... }
中使用它