Android - Shared-preferences in Broadcast

2019-08-31 02:03发布

问题:

In my BroadcastReceiver class I am using ISharedPreferences to store a string coming from a service and compare it with the previous string (which is stored in my Preferences).

BroadcastReceiver.cs

[BroadcastReceiver]
[IntentFilter(new[] { "TEST" })]
public class Receiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        ISharedPreferences pref = PreferenceManager.GetDefaultSharedPreferences(context);
        ISharedPreferencesEditor editor = pref.Edit();
        string old = pref.GetString("MYKEY", "nothing");
        Log.Error("lv", "OnReceive");
        string new = intent.GetStringExtra("alltotale");
        editor.PutString("MYKEY", new);
        editor.Commit();
        Notification.Builder builder = new Notification.Builder(context);
        builder.SetContentTitle("Old:" + old);
        builder.SetContentText("New" + new);
        builder.SetSmallIcon(Resource.Drawable.Icon);
        Notification notif = builder.Build();
        NotificationManager notifmanager = context.GetSystemService(Context.NotificationService) as NotificationManager;
        notifmanager.Notify(12, notif);
     }
 }

Now the weird thing is that the two strings (the old and the new) which are showing in the Notification are the same, although I am pretty sure that they are not. Which indicates that there are something wrong going on with the storage process. I don't know why it is giving the same string in the Notification, I don't see any problem with the Logic, so what is causing that to happen ?