I am creating Background Location Tracker using Google FusedLocation API
. In requestLocationUpdates()
, I am using PendingIntent
for background operation. When I run my app, foreground location tracker works fine. However, my IntentService
class seems not working. I did not get any notification, nothing happens in background. This is how I am implementing Google FusedLocation API
in my Main Fragment Class:
@Override
public void onConnected(Bundle bundle) {
.......
//Starting Background Location Tracker
if (mRequestingLocationUpdates)
{
createLocationRequest();
startLocationUpdates();
}
}
protected void startLocationUpdates() {
locationIntent = new Intent(getActivity().getApplicationContext(), LocationHandlerService.class);
locationPendingIntent = PendingIntent.getService(getActivity().getApplicationContext(), 5,
locationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, locationRequest, locationPendingIntent);
}
This is my LocationHandlerService
class:
public class LocationHandlerService extends IntentService {
Location mLocation;
NotificationManager notificationManager;
public LocationHandlerService() {
super("Services.LocationHandlerService");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
protected void onHandleIntent(Intent intent) {
if (LocationResult.hasResult(intent)) {
LocationResult locationResult = LocationResult.extractResult(intent);
mLocation = locationResult.getLastLocation();
if (mLocation != null) {
setupNotification(mLocation);
}
}
}
//Setup Notification
private void setupNotification(Location location) {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.location_start_notification)
.setOngoing(true)
.setPriority(Notification.PRIORITY_HIGH)
.setContentTitle(getResources().getString(R.string.location_notification))
.setContentText("Lat: " + location.getLatitude() + ", Long: " + location.getLongitude());
notificationManager.notify(0, notification.build());
}
}
Can anyone tell what wrong with my code???