Search code examples
androidbackgroundlocationlistener

Prevent Oreo or Pie to pause LocationListener when in background


I've done an application for my personal use (GPS tracking when trekking, with sending position to another phone, for survey).

It was under Lolipop and working fine.

New phone, under Pie.

Working fine if application is in foreground, but set in pause by Pie when in background.

How to keep it working in background ?

I tried in "Device Care" > "Battery" > "App power management" unchecking "Adaptive battery" or "Put unsued apps to sleep" not work. I put my app in "Apps that won't be put to sleep" but don't work too.

Is there a "simple way" to programmaticaly keep my application active in background ?.

AndroidManifest ? Or same as for screen: getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

My app is based on onLocationChanged(final Location location)

Thanks for help Regards


Solution

  • After searching a lot, I think I found the solution here : https://developer.android.com/training/location/permissions

    The problem is that I got API29 (android 10) that require new permissions (not necessary in android 8 or 9).

    it's in androidManifest.xml

    If in foreground:

    <!-- Recommended for Android 9 (API level 28) and lower. -->
    <!-- Required for Android 10 (API level 29). -->
    <service
        android:name="MyNavigationService"
        android:foregroundServiceType="location" ... >
        <!-- Any inner elements would go here. -->
    </service>
    

    or if in background:

    <manifest ... >
      <!-- Required only when requesting background location access on
           Android 10 (API level 29). -->
      <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    </manifest>
    

    I only test foreground solution android:foregroundServiceType="location" and it is working fine.

    Programming is hard job. Knowledge is harder.

    Have fun. Thanks.