我有一个接受推送通知的应用程序。我必须将推送通知写入数据库。问题是在数据库中它只写入最后一条消息(在我重新进入应用程序之后)以及应用程序在后台和前台时。当新数据到货时,可以采取哪些措施使数据库保持最新状态?
我接受推送,之后我将其数据写入变量
[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class MyFirebaseMessagingService : FirebaseMessagingService
{
const string TAG = "MyFirebaseMsgService";
public override void HandleIntent(Intent intent)
{
try
{
if (intent.Extras != null)
{
var builder = new RemoteMessage.Builder("MyFirebaseMessagingService");
foreach (string key in intent.Extras.KeySet())
{
builder.AddData(key, intent.Extras.Get(key).ToString());
}
this.OnMessageReceived(builder.Build());
}
else
{
base.HandleIntent(intent);
}
}
catch (Exception)
{
base.HandleIntent(intent);
}
}
public override void OnMessageReceived(RemoteMessage message)
{
Log.Debug(TAG, "From: " + message.From);
Log.Debug(TAG, "Notification Message Body: " + message.GetNotification().Body);
SendNotification(message.GetNotification().Body, message.Data, message.GetNotification().Title);
// Here I write the push - notification data into variables
X.Instance.title = message.GetNotification().Title;
X.Instance.body = message.GetNotification().Body;
}
private void OnStartCommand()
{
throw new NotImplementedException();
}
public class X
{
public static X Instance = new X();
public string title;
public string body;
}
在这个课程中,我填写了数据库:
[Service]
[Activity(Label = "Message")]
public class FormMessageActivity : Activity
{
ListView lstData;
List<Message> lstSource = new List<Message>();
DataBase db;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.FormMessage);
db = new DataBase();
db.CreateDataBase();
lstData = FindViewById<ListView>(Resource.Id.listView);
Message message = new Message()
{
//And here I add to the database
Some = MyFirebaseMessagingService.X.Instance.title,
Notification = MyFirebaseMessagingService.X.Instance.body
};
if (message.Notification != null)
{
db.InsertIntoTableMessage(message);
LoadData();
}
LoadData();
lstData.ItemClick += (s, e) =>
{
//Set background for selected item
for (int i = 0; i < lstData.Count; i++)
{
if (e.Position == i) StartActivity(typeof(MessageActivity));
}
};
}
public void LoadData()
{
lstSource = db.SelectTableMessage();
var adapter = new ListViewAdapter(this, lstSource);
lstData.Adapter = adapter;
}
}
答案 0 :(得分:0)
从您的代码中,您似乎在onCreate中创建数据库实例并在同一onCreate方法中输入数据。我无法看到您的数据库是如何实现的,或者它是什么类型的数据库,但我建议您在OnMessageReceived处理程序中的Db中输入通知,该处理程序在您收到新通知时调用,而不是在您的onCreate因为onCreate被谨慎调用,并且由于某些设备配置(如方向更改)而被调用。