2

I've used this BroadcastReceiver as GPS status receiver to monitor when user turns on/off his Location in top navigation menu. It suddenly stopped working (whole receiver onReceive() method is not called) 2 weeks ago (probably has something to do with Android 10 release). Do you know what could be wrong?

It worked perfectly before.

class GPSReceiver: BroadcastReceiver(){

    companion object{
        const val GPS_PAYLOAD = "gps_payload"
        const val GPS_STATE = "gps_state"
    }

    override fun onReceive(context: Context, intent: Intent) {
        App.log("IsGPSEnabled: callingonReceive")
        val action = intent.action
        if(action != null && action == LocationManager.PROVIDERS_CHANGED_ACTION){
            try {
                val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
                val int = Intent(GPS_PAYLOAD)
                if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                    int.putExtra(GPS_STATE, true)
                } else {
                    int.putExtra(GPS_STATE, false)
                }
                LocalBroadcastManager.getInstance(context).sendBroadcast(int)
            } catch (ex: Exception) {
                App.log("IsGPSEnabled: $ex")
            }
        }

    }
}

AndroidManifest:

<!-- GPS status receiver -->
        <receiver android:name=".services.GPSReceiver"
            android:exported="false">
            <intent-filter>
                <action android:name="android.location.PROVIDERS_CHANGED" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>

Android 8.0+ manifest receiver is obsolete

Registering object BroadcastReceiver monitoring intent in Activity:

registerReceiver(gpsStatusReceiver, IntentFilter("android.location.PROVIDERS_CHANGED"))

martin1337
  • 2,384
  • 6
  • 38
  • 85
  • As per your question, I understand you need to perform some action while GPS on/off ?? – Kintan Patel Oct 11 '19 at 09:05
  • Yes, this is correct. – martin1337 Oct 11 '19 at 09:15
  • Could be related to https://developer.android.com/about/versions/oreo/background.html#broadcasts Doc lists possible alternatives such as a foreground service to listen for the location state while the app is running but in the 'background' – Ryujin Oct 15 '19 at 03:17

1 Answers1

0

you must update your xml part like this:

<receiver
    android:name=".Util.GpsReceiver"
    android:enabled="true"> <!-- do this and try again -->
    <intent-filter>
         <action android:name="android.location.PROVIDERS_CHANGED" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>

don't forget this permissions:

<uses-permission 
android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission 
android:name="android.permission.ACCESS_COARSE_LOCATION"/>
alireza daryani
  • 787
  • 5
  • 16