简体   繁体   English

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

[英]Android: writing to realm database from notification

I am building an app and ran into a problem that I couldn't find an answer to. 我正在构建一个应用程序,遇到无法找到答案的问题。 I have a realm database that I use to store some very simple information. 我有一个领域数据库,用于存储一些非常简单的信息。 Now what I want to do is every day at a set time prompt the user with a notification with a few buttons on it. 现在,我要做的是每天在设定的时间提示用户一个带有几个按钮的通知。 And depending on what button the user clicks, I want to write a different value to the realm database. 根据用户单击的按钮,我想向领域数据库写入一个不同的值。 PREFERABLY without opening the app. 最好不打开应用程序。 Is this possible? 这可能吗?

Thanks in advance! 提前致谢!

You can do it in this way. 您可以通过这种方式进行。
First, create a Notification with actions on it. 首先,创建一个带有通知的通知。

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());  

Now create a BroadcastReceiver class to receive values. 现在创建一个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.
   }

  }    
}  

Add this BroadcastReceiver in the manifest file. 在清单文件中添加此BroadcastReceiver。

<receiver android:enabled="true" android:name="LikeShareReceiver">
  <intent-filter>
    <action android:name="MY_ACTION" />
  </intent-filter>
</receiver>  

How this will work? 这将如何工作?
When a user clicks on an action button it will trigger a broadcast with an intent having values in it. 当用户单击一个动作按钮时,它将触发具有意图的广播。 BroadcastReceiver will receive this broadcast and update the database accordingly. BroadcastReceiver将接收此广播并相应地更新数据库。

Note:addAction() method will only work with api level >=4.1 注意:addAction()方法仅适用于api级别> = 4.1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM