0

I have minor issue here.

I have taken all the necessary location permissions from the user.

I have created Broadcast Receiver as below :

public class GpsLocationReceiver : BroadcastReceiver() {
    private lateinit var mLocationManager: LocationManager
    override fun onReceive(context: Context, intent: Intent) {
        LogUtil.e(">>>On Receive","called")
        mLocationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            LogUtil.e(">>>On Receive","called inside")
            GetLocationAccessFragment().getAndSaveCurrentLocation()
        }
    }
}

In my manifest i have done as below :

<receiver android:name=".ui.user_profile.fragments.GetLocationAccessFragment$GpsLocationReceiver">
        <intent-filter>
            <action android:name="android.location.PROVIDERS_CHANGED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>

Now, for am registering it in my fragment init() method :

mContext.registerReceiver(
            GpsLocationReceiver(),
            IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION)

and, unregistered it when work finished :

mContext.unregisterReceiver(GpsLocationReceiver())

But, Unfortunately, OnReceive() method is not getting called when I TurnOn/TurnOff GPS in my device. What might be the issue ?

Jaimin Modi
  • 1,530
  • 4
  • 20
  • 72

2 Answers2

1

Are you running this on Oreo or above. If that is the case, this will not work as android limits the implicit broastcastreceivers. https://developer.android.com/about/versions/oreo/background.html#broadcasts

Use explicit broadcast. Another issue is

mContext.registerReceiver(
        GpsLocationReceiver(),
        IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION)

You are creating instanceA in register and unregistering a new instance in unregister which was not even registered.

mContext.unregisterReceiver(GpsLocationReceiver())

Use same instance in both the calls.

When you use explicit broadcast registration you do not need manifest to declare that. Hope this helps.

vishal_ratna
  • 116
  • 1
  • 5
  • then How can I know that GPS is being turned on? – Jaimin Modi Jan 21 '20 at 08:34
  • You will know it, currently you are registering receiver via 2 ways, implicit and explicit. By removing from manifest you will depend only on explicit registration. After android O, framework does not allow devs to register broadcast receiver via manifest file. We have to do it via register() and unregister() calls. – vishal_ratna Jan 21 '20 at 09:22
1

From the documentation:

It may take a while to receive the first location update. If an immediate location is required, applications may use the getLastKnownLocation(java.lang.String) method.

In my experience, location broadcast updates come only when location changes. This is done to optimize battery life of the device.