簡體   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