我正在尝试在通知按钮上实现广播接收器。 问题是我没看到祝酒。
带按钮的自定义通知功能,按钮点击应发出通知:
public void CustomNotification() {
RemoteViews remoteViews = new RemoteViews(getPackageName(),
R.layout.customnotification);
String strtitle = getString(R.string.customnotificationtitle);
String strtext = getString(R.string.customnotificationtext);
Intent intent = new Intent(this, NotificationView.class);
intent.putExtra("title", strtitle);
intent.putExtra("text", strtext);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.desktop_icon)
.setTicker(getString(R.string.customnotificationticker))
.setAutoCancel(true)
.setContentIntent(pIntent)
.setContent(remoteViews);
remoteViews.setImageViewResource(R.id.imagenotileft,R.drawable.ic_launcher);
remoteViews.setImageViewResource(R.id.imagenotiright,R.drawable.icon_connected_phone);
remoteViews.setTextViewText(R.id.title,getString(R.string.customnotificationtitle));
remoteViews.setTextViewText(R.id.text,getString(R.string.customnotificationtext));
//On button click
Intent BRintent = new Intent("MyCustomIntent");
BRintent.putExtra("message", "TST");
BRintent.setAction("com.example.notificationtest.CUSTOM_INTENT");
sendBroadcast(intent);
PendingIntent pIntent2 = PendingIntent.getActivity(this, 0, BRintent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.notif_btn, pIntent2);
//End on button click
NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationmanager.notify(0, builder.build());
}
在清单上添加:
<receiver android:name="MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.notificationtest.CUSTOM_INTENT">
</action>
</intent-filter>
</receiver>
广播接收器类:
public class MyBroadcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Extract data included in the Intent
CharSequence intentData = intent.getCharSequenceExtra("message");
Toast.makeText(context, "Test Notification"+intentData, Toast.LENGTH_LONG).show();
Log.d("MyTag", "Test");
}
}
答案 0 :(得分:1)
在此电话会议中:
PendingIntent pIntent2 = PendingIntent.getActivity(this, 0, BRintent,
PendingIntent.FLAG_UPDATE_CURRENT);
您正在呼叫getActivity()
,这将返回启动活动的PendingIntent
。那不是你想要的。你想要一个广播意图。这样做:
PendingIntent pIntent2 = PendingIntent.getBroadcast(this, 0, BRintent,
PendingIntent.FLAG_UPDATE_CURRENT);