Saraphin34
Saraphin34

Reputation: 37

How to save label value when app is closed and reopened when using Foreground Service

I have a foreground Service, which updates phonebook every 24h and uploads data from local databse to server every 2 minutes. I'm using MessagingCenter to get the exact time, when the data upload was successful and when the contacts were last updated. Then print this data to labels on the main screen. The problem, is that the labels are always resetting whenever I stop my service, or close and reopen my app.

Is there a way to save labels text, without creating a new database?

Method for sending all data after every call:

public async Task SendData(List<PhoneCall> phoneCalls)
    {
        Device.BeginInvokeOnMainThread(() =>
        {
            MessagingCenter.Send<object, string>(this, "Bandyta", DateTime.Now.ToString());
        });

        if (NetworkCheck.IsInternet())
        {
            
            var uri = new Uri("http://mmmmmmmmmmm.aspx");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response;

            foreach (var item in phoneCalls)
            {
                string json = JsonConvert.SerializeObject(item);

                var content = new StringContent(json, Encoding.UTF8, "application/json");
                response = await client.PostAsync(uri, content);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        MessagingCenter.Send<object, string>(this, "Sekmingai", DateTime.Now.ToString());
                    });
                }
                else
                {
                    await App.Database.SaveLogAsync(new Logs
                    {
                        deviceno = item.deviceno,
                        phoneno = item.phoneno,
                        direction = item.direction,
                        dt = item.dt,
                        action = item.action
                    });

                }
            }
        }
        else
        {
            foreach (var item in phoneCalls)
            {
                await App.Database.SaveLogAsync(new Logs
                {
                    deviceno = item.deviceno,
                    phoneno = item.phoneno,
                    direction = item.direction,
                    dt = item.dt,
                    action = item.action
                });
            }
        }
    }

Foreground service:

 public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
    {
        IntentFilter filter = new IntentFilter();
        filter.AddAction(TelephonyManager.ActionPhoneStateChanged);

        switch (intent.Action)
        {
            case null:
                GetWakelock();
                myReceiver = new MyReceiver();
                var notif = DependencyService.Get<INotificationHelper>().ReturnNotif();
                StartUploadingContactsToServer();
                RegisterReceiver(myReceiver, filter);
                StartForeground(1001, notif);
                break;
            case "stopService":
                callServiceHelper.UnsubscribeMessages();
                UnregisterReceiver(myReceiver);
                wl.Release();
                callServiceHelper.StopMyService();
                break;
        }

        return StartCommandResult.NotSticky;
    }

Label ViewModel class:

public class LabelModel : BindableObject
{
    string dataSentSuccessful = "Paskutinį kartą pavyko išsiųsti duomenis sėkmingai: ";
    string dataSentTried = "Paskutinį kartą bandyta išsiųsti duomenis: ";
    string lastTimeContactsUpdated = "Paskutinį kartą kontaktai buvo atnaujinti: ";

    public LabelModel()
    {
        MessagingCenter.Subscribe<object, string>(this, "Atnaujinti", (sender, args) =>
        {
            LastTimeContactsUpdated = $"Paskutinį kartą kontaktai buvo atnaujinti: \n {args}";
        });
        MessagingCenter.Subscribe<object, string>(this, "Sekmingai", (sender, args) =>
        {
            DataSentSuccessful = $"Paskutinį kartą pavyko išsiųsti duomenis sėkmingai: \n {args}";
        });
        MessagingCenter.Subscribe<object, string>(this, "Bandyta", (sender, args) =>
        {
            DataSentTried = $"Paskutinį kartą bandyta išsiųsti duomenis: \n {args}";
        });
    }

    public string DataSentTried
    {
        get => dataSentTried;
        set
        {
            dataSentTried = value;
            OnPropertyChanged(nameof(DataSentTried));
        }
    }
    public string DataSentSuccessful
    {
        get => dataSentSuccessful;
        set
        {
            dataSentSuccessful = value;
            OnPropertyChanged(nameof(DataSentSuccessful));
        }
    }
    public string LastTimeContactsUpdated
    {
        get => lastTimeContactsUpdated;
        set
        {
            lastTimeContactsUpdated = value;
            OnPropertyChanged(nameof(LastTimeContactsUpdated));
        }
    }
}

MainPage:

public partial class MainPage : ContentPage
{
    IContactsHelper contactsHelper = DependencyService.Get<IContactsHelper>();

    public MainPage()
    {
        InitializeComponent();

        if (!DependencyService.Get<ICallServiceHelper>().IsMyServiceRunning())
        {
            BindingContext = new LabelModel();
            deviceNoLabel.Text = contactsHelper.GetIdentifier();
        }
    }
}

MainActivity:

 protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

        var permissions = new string[]
        {
            Manifest.Permission.WakeLock,
            Manifest.Permission.ForegroundService,
            Manifest.Permission.ReadPhoneState,
            Manifest.Permission.ReadCallLog,
            Manifest.Permission.ReadContacts,
            Manifest.Permission.WriteContacts,
        };
        ActivityCompat.RequestPermissions(this, permissions, 123);

        LoadApplication(new App());
    }

    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum]Permission[] grantResults)
    {
        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 123 && grantResults.Length > 0 && grantResults[0] == Permission.Granted)
        {
            if (!DependencyService.Get<ICallServiceHelper>().IsMyServiceRunning())
            {
                DependencyService.Get<ICallServiceHelper>().StartMyService();
            }
        }
    }

Upvotes: 0

Views: 49

Answers (0)

Related Questions