你可以这样做。
首先,创建一个带有操作的通知。
Intent intentLike = new Intent("MY_ACTION");
intentLike.putExtra("KEY","LIKE");
PendingIntent likePendingIntent = PendingIntent.getBroadcast(context,0,intentLike,PendingIntent.FLAG_UPDATE_CURRENT);
Intent intentShare = new Intent("MY_ACTION");
intentShare.putExtra("KEY","SHARE");
PendingIntent sharePendingIntent = PendingIntent.getBroadcast(context,1,intentShare,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.addAction(R.drawable.notification_action_like, "Like", likePendingIntent)
.addAction(R.drawable.notification_action_share, "Share", sharePendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());
现在创建一个 BroadcastReceiver 类来接收值。
public class LikeShareReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String receivedValue = intent.getExtra("KEY");
if (receivedValue.equals("LIKE")) {
//update like in Realm database.
}else if (receivedValue.equals("SHARE")) {
//update share in Realm database.
}
}
}
在清单文件中添加此 BroadcastReceiver。
<receiver android:enabled="true" android:name="LikeShareReceiver">
<intent-filter>
<action android:name="MY_ACTION" />
</intent-filter>
</receiver>
这将如何运作?
当用户点击一个动作按钮时,它将触发一个带有值的广播。 BroadcastReceiver 将接收此广播并相应地更新数据库。
注意:addAction() 方法仅适用于 API 级别 >=4.1