Get GPS Location in a Broadcast Receiver/or Service to Broadcast Receiver data transfer
From BroadcastReceiver I could not start Location Manager as well. So I started a service on BroadcastReceiver and in that service I manipulated Location Manager. I think I found this solution in Android development documentation. You also can start Activity instead of Service.
Here is the code of switch to Service on BroadcastReceiver:
write this in onReceive
method
Intent serviceIntent = new Intent(context,MyService.class);
serviceIntent.putExtra("locateRequest", "locateRequest"); // if you want pass parameter from here to service
serviceIntent.putExtra("queryDeviceNumber", results[1]);
context.startService(serviceIntent); //start service for get location
How with broadcast receiver should I subscribe to listen for location services change
This is useful when user want to trigger any action on turn On/Off location provides
You should add this action in manifest
<action android:name="android.location.PROVIDERS_CHANGED" />
and after add this action you can trigger your broadcast receiver
<receiver android:name=".GpsLocationReceiver">
<intent-filter>
<action android:name="android.location.PROVIDERS_CHANGED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
And in your BroadcastReceiver
class you have to implement LocationListener
in that class which is given following below..
public class GpsLocationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
Toast.makeText(context, "in android.location.PROVIDERS_CHANGED",
Toast.LENGTH_SHORT).show();
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if( !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ) {
//NO GPS
}else{
//Gps is on
}
}
}
}
How to get device location when a BTLE event triggers in broadcast receiver?
fusedLocationClient.lastLocation
can return null location if no recent location fix exists. Using the below code to get current location works as it gets fresh location:
fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY, object : CancellationToken() {
override fun onCanceledRequested(p0: OnTokenCanceledListener) = CancellationTokenSource().token
override fun isCancellationRequested() = false
})
.addOnSuccessListener { location: Location? ->
//Update location in shared preferences
}
Make sure to use the latest location package in gradle based on this post
implementation "com.google.android.gms:play-services-location:17.1.0"
How to periodically find gps location in Android
Use receiver and service together. For this purpose you can find a complete sample in this link. There is a listener in it. Listener can be used in your activity to be noticed that a new location is ready for you.
BroadcastReceiver for location
I think what you are looking for is something like this. There is a version of LocationManager.requestLocationUpdates()
that takes a PendingIntent
as a parameter, and this Intent could be used to fire a BroadcastReceiver
. This code will register a custom broadcast to fire with the location updates.
Intent intent = new Intent("UNIQUE_BROADCAST_ACTION_STRING_HERE");
LocationManager manager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
long minTime; //This should probably be fairly long
float minDistance; //This should probably be fairly big
String provider; //GPS_PROVIDER or NETWORK_PROVIDER
PendingIntent launchIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
manager.requestLocationUpdates(provider, minTime, minDistance, launchIntent);
Then you just have to register your BroadcastReceiver
with the same Intent action and it will receive the location updates for processing. And, of course, keep that PendingIntent
around because you'll need to call manager.removeUpdates(launchIntent)
at some point!
Final Note:
Because it sounds like you are trying to implement regular location updates while your app isn't in the foreground, keep this in mind. Unless you want your app branded as a battery killer, be extremely careful with how you implement this functionality.
You will want to greatly reduce the frequency up location updates with either a large minTime or minDistance parameter to allow the location service to rest. This feature should also be attached to a user controlled preference so they can enable/disable your app from tracking location in the background.
Hope that Helps!
Related Topics
Gradle Error:Execution Failed for Task ':App:Processdebuggoogleservices'
Map View Draw Directions Using Google Directions API - Decoding Polylines
Enable and Disable Auto Rotate Programmatically
Onclicklistener - X,Y Location of Event
Taking Screenshot Programmatically Doesnt Capture the Contents of Surfaceview
How to Create Parallelogram Shape Background
How to Play an Mp3 in the Res/Raw Folder of My Android App
How to Blur Some Portion of Image in Android
Sms Manager Send Mutlipart Message When There Is Less Than 160 Characters
How to Record Video from Background of Application:Android
How to Pop Fragment Off Backstack
Anr Keydispatchingtimedout Error
Difference Between Content_Main.Xml and Activity_Main.Xml
Set Permission for Getting User's Email Id from Facebook Login
Fragment-Fragment Communication in Android