Android:从通知写入领域数据库

时间:2017-04-18 08:33:50

标签: java android database notifications realm

我正在构建一个应用程序并遇到了一个我无法找到答案的问题。 我有一个领域数据库,用于存储一些非常简单的信息。现在我想要做的是每天在设定的时间提示用户通知其上有几个按钮。根据用户点击的按钮,我想为realm数据库写一个不同的值。首选,无需打开应用程序。这可能吗?

提前致谢!

1 个答案:

答案 0 :(得分:-1)

你可以这样做。
首先,创建一个带有操作的通知。

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级别&gt; = 4.1