繁体   English   中英

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

[英]Android: writing to realm database from notification

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

提前致谢!

您可以通过这种方式进行。
首先,创建一个带有通知的通知。

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

暂无
暂无

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

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