2017-04-18 41 views
1

我正在構建應用程序,並遇到無法找到答案的問題。 我有一個領域數據庫,我用它來存儲一些非常簡單的信息。現在我想要做的是在設定的時間每天都會提示用戶通知,並在其上放置幾個按鈕。取決於用戶點擊的按鈕,我想爲領域數據庫寫入不同的值。無需打開應用程序即可。這可能嗎?Android:從通知寫入領域數據庫

在此先感謝!

+0

你嘗試過什麼工作至今? –

+0

@BradleyWilson我已經設法發送預定的通知給用戶,但我不確定如何在應用程序未打開時寫入數據庫。 – JesperQv

+0

不幸的是,我不是這方面的專家,我希望你可以在你的問題中添加一些代碼,以幫助未來的讀者瞭解你已經採取或試圖採取的方向。 –

回答

-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