Skip to content

Instantly share code, notes, and snippets.

@mitchtabian
Last active March 6, 2021 17:40
Show Gist options
  • Save mitchtabian/d3fee0954426f55c94807513a5a18a96 to your computer and use it in GitHub Desktop.
Save mitchtabian/d3fee0954426f55c94807513a5a18a96 to your computer and use it in GitHub Desktop.
package com.codingwithmitch.googlemaps2018.services;
import android.Manifest;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.codingwithmitch.googledirectionstest.R;
import com.codingwithmitch.googledirectionstest.UserClient;
import com.codingwithmitch.googledirectionstest.models.User;
import com.codingwithmitch.googledirectionstest.models.UserLocation;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.GeoPoint;
public class LocationService extends Service {
private static final String TAG = "LocationService";
private FusedLocationProviderClient mFusedLocationClient;
private final static long UPDATE_INTERVAL = 4 * 1000; /* 4 secs */
private final static long FASTEST_INTERVAL = 2000; /* 2 sec */
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
if (Build.VERSION.SDK_INT >= 26) {
String CHANNEL_ID = "my_channel_01";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
"My Channel",
NotificationManager.IMPORTANCE_DEFAULT);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("")
.setContentText("").build();
startForeground(1, notification);
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand: called.");
getLocation();
return START_NOT_STICKY;
}
private void getLocation() {
// ---------------------------------- LocationRequest ------------------------------------
// Create the location request to start receiving updates
LocationRequest mLocationRequestHighAccuracy = new LocationRequest();
mLocationRequestHighAccuracy.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequestHighAccuracy.setInterval(UPDATE_INTERVAL);
mLocationRequestHighAccuracy.setFastestInterval(FASTEST_INTERVAL);
// new Google API SDK v11 uses getFusedLocationProviderClient(this)
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "getLocation: stopping the location service.");
stopSelf();
return;
}
Log.d(TAG, "getLocation: getting location information.");
mFusedLocationClient.requestLocationUpdates(mLocationRequestHighAccuracy, new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
Log.d(TAG, "onLocationResult: got location result.");
Location location = locationResult.getLastLocation();
if (location != null) {
User user = ((UserClient)(getApplicationContext())).getUser();
GeoPoint geoPoint = new GeoPoint(location.getLatitude(), location.getLongitude());
UserLocation userLocation = new UserLocation(user, geoPoint, null);
saveUserLocation(userLocation);
}
}
},
Looper.myLooper()); // Looper.myLooper tells this to repeat forever until thread is destroyed
}
private void saveUserLocation(final UserLocation userLocation){
try{
DocumentReference locationRef = FirebaseFirestore.getInstance()
.collection(getString(R.string.collection_user_locations))
.document(FirebaseAuth.getInstance().getUid());
locationRef.set(userLocation).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Log.d(TAG, "onComplete: \ninserted user location into database." +
"\n latitude: " + userLocation.getGeo_point().getLatitude() +
"\n longitude: " + userLocation.getGeo_point().getLongitude());
}
}
});
}catch (NullPointerException e){
Log.e(TAG, "saveUserLocation: User instance is null, stopping location service.");
Log.e(TAG, "saveUserLocation: NullPointerException: " + e.getMessage() );
stopSelf();
}
}
}
private void startLocationService(){
if(!isLocationServiceRunning()){
Intent serviceIntent = new Intent(this, LocationService.class);
// this.startService(serviceIntent);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){
MainActivity.this.startForegroundService(serviceIntent);
}else{
startService(serviceIntent);
}
}
}
private boolean isLocationServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)){
if("com.codingwithmitch.googledirectionstest.services.LocationService".equals(service.service.getClassName())) {
Log.d(TAG, "isLocationServiceRunning: location service is already running.");
return true;
}
}
Log.d(TAG, "isLocationServiceRunning: location service is not running.");
return false;
}
@grifterXcode
Copy link

@mitchtabian, this is so cool

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment