【问题标题】:Android: writing to realm database from notificationAndroid:从通知写入领域数据库
【发布时间】:2017-04-18 08:33:49
【问题描述】:

我正在构建一个应用程序并遇到了一个我找不到答案的问题。 我有一个领域数据库,用于存储一些非常简单的信息。现在我想做的是每天在设定的时间向用户提示一个带有几个按钮的通知。并且根据用户单击的按钮,我想将不同的值写入领域数据库。最好不打开应用程序。这可能吗?

提前致谢!

【问题讨论】:

  • @BradleyWilson 我已设法向用户发送预定通知,但我不确定在应用未打开时如何写入数据库。
  • 不幸的是,我不是这方面的专家,我希望你能在你的问题中添加一些代码,以帮助未来的读者了解你已经采取或试图采取的方向。

标签: java android database notifications realm


【解决方案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 级别 >=4.1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多