简体   繁体   中英

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.

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.

<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.

Note:addAction() method will only work with api level >=4.1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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