question

AravapalliManikishore-1338 avatar image
0 Votes"
AravapalliManikishore-1338 asked RobCaplan edited

Is Mobile Space issue for Background Services?

Hi Everyone,

I'm pretty new to Xamarin Forms Development.

I'm using Background Location Service to track the location from background for every X minutes and Repeating Alarm to send the locations tracks to API. It is working fine in few mobiles and not in few. (Android only)

I tested in two mobile phones which are having Android 7 OS. Working fine in one mobile only.
The one which is not working does not have space.

So, Is there any space concerns for Background location service or Alarm Manger?

Here is my code for Location Track Service

Binding Location

         locationRequest = new LocationRequest();
         locationRequest.SetPriority(LocationRequest.PriorityHighAccuracy);
         locationRequest.SetInterval(frequency * 60000);
         locationRequest.SetFastestInterval(frequency * 60000);

         fusedLocationProviderClient = LocationServices.GetFusedLocationProviderClient(this);
         fusedLocationProviderClient.RequestLocationUpdates(locationRequest, GetPendingIntent());

         private PendingIntent GetPendingIntent()
         {
            Intent intent = new Intent(this, typeof(MyLocationService));
            intent.SetAction(MyLocationService.ACTION_PROCESS_LOCATION);
            return PendingIntent.GetBroadcast(this, 0, intent, PendingIntentFlags.UpdateCurrent);
         }


Location Broadcast Receiver

 [BroadcastReceiver]
 public class MyLocationService : BroadcastReceiver
 {
     public static string ACTION_PROCESS_LOCATION = "LocationTrack.UPDATE_LOCATION";

     public static event EventHandler<int> LocationUpdatedEvent;

     public override void OnReceive(Context context, Intent intent)
     {
         if (intent != null)
         {
             string action = intent.Action;
             if (action.Equals(ACTION_PROCESS_LOCATION))
             {
                 LocationResult result = LocationResult.ExtractResult(intent);
                 if (result != null)
                 {
                     var location = result.LastLocation;
                     var locString = location.Longitude.ToString() + "/" + location.Latitude.ToString();

                       
                 }
             }
         }
     }

   }




Code for Alarm Manager

     void StartAlarmService()
     {
         string MessageText = "Message notification";
         var date = DateTime.Now.ToString("MM'-'dd'-'yyyy");
         var time = DateTime.Now.ToString("HH:mm");
         var dateTime = date + " " + time;
         var selectedDateTime = DateTime.ParseExact(dateTime, "MM-dd-yyyy HH:mm", CultureInfo.InvariantCulture);
         if (!string.IsNullOrEmpty(MessageText))
         {
             DependencyService.Get<ILocalNotificationService>().Cancel(0);
             DependencyService.Get<ILocalNotificationService>().LocalNotification("Local Notification", MessageText, 0, selectedDateTime);
         }
     }


     public void LocalNotification(string title, string body, int id, DateTime notifyTime)
     {

         //long repeateDay = 1000 * 60 * 60 * 24;    
         long repeateForMinute = 300000; // In milliseconds   - 15 Min
         long totalMilliSeconds = (long)(notifyTime.ToUniversalTime() - _jan1st1970).TotalMilliseconds;
         if (totalMilliSeconds < JavaSystem.CurrentTimeMillis())
         {
             totalMilliSeconds = totalMilliSeconds + repeateForMinute;
         }

         var intent = CreateIntent(id);
         var localNotification = new LocalNotification();
         localNotification.Title = title;
         localNotification.Body = body;
         localNotification.Id = id;
         localNotification.NotifyTime = notifyTime;

         if (_notificationIconId != 0)
         {
             localNotification.IconId = _notificationIconId;
         }
         else
         {
             localNotification.IconId = Resource.Drawable.abc_btn_check_material;
         }

         var serializedNotification = SerializeNotification(localNotification);
         intent.PutExtra(ScheduledAlarmHandler.LocalNotificationKey, serializedNotification);

         Random generator = new Random();
         _randomNumber = generator.Next(100000, 999999).ToString("D6");

         var pendingIntent = PendingIntent.GetBroadcast(Application.Context, 0, intent, PendingIntentFlags.Immutable);

         bool alarmUp = (PendingIntent.GetBroadcast(Application.Context, 0, new Intent(Utilities._packageName), PendingIntentFlags.NoCreate) != null);

         if (!alarmUp)
         {
             var alarmManager = GetAlarmManager();
             alarmManager.SetRepeating(AlarmType.RtcWakeup, totalMilliSeconds, repeateForMinute, pendingIntent);
         }
     }



Can anyone help me what wrong I've done.


Thanks in Advance.

dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

JarvanZhang-MSFT avatar image
0 Votes"
JarvanZhang-MSFT answered JarvanZhang-MSFT commented

Hello,​

Welcome to our Microsoft Q&A platform!

I tested in two mobile phones which are having Android 7 OS. Working fine in one mobile only. The one which is not working does not have space.

What's the API of the another mobile? Starting in Android 8.0 (API level 26), an Android application no longer have the ability to run freely in the background. When an application moves into the background, Android will grant the app a certain amount of time to start and use services. Once that time has elapsed, the app can no longer start any services and any services that were started will be terminated.

If you test the project on Android 8.0 or above, the background task cannot work all the time. To fix this, try using a foreground service instead.

Check the docs:
https://docs.microsoft.com/en-us/xamarin/android/app-fundamentals/services/#background-execution-limits-in-android-80
https://docs.microsoft.com/en-us/xamarin/android/app-fundamentals/services/foreground-services

Best Regards,

Jarvan Zhang



If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


· 7
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@JarvanZhang-MSFT

Thanks for the reply. I used both Android 7 version phones only. API is 24 for both the phones.

If the time is elapsed and service is not started by that time, is there any other option to start? or whenever app goes to background can we force start the services? Because, I cannot use the foreground service as I need to use the service for 24hrs a day. It drains the battery as I use the GPS.

Please suggest the best approach.


Thanks in Advance.

0 Votes 0 ·
JarvanZhang-MSFT avatar image JarvanZhang-MSFT AravapalliManikishore-1338 ·

What's the targetFramework of the Android project? Since Android adds limits to background services, we cannot run a background service always. Please use the foreground service instead, running a service all the time will consume more power.

Related link:
https://stackoverflow.com/questions/51289236/continually-running-background-service

0 Votes 0 ·

@JarvanZhang-MSFT

Target Framework is 9.0 and Minimum Android version is 5.0 (API 21).

0 Votes 0 ·
Show more comments