Skip to content

Instantly share code, notes, and snippets.

@tanerjn
Created November 9, 2018 18:41
Show Gist options
  • Save tanerjn/3e2215e34c474b0173b0204155e3c735 to your computer and use it in GitHub Desktop.
Save tanerjn/3e2215e34c474b0173b0204155e3c735 to your computer and use it in GitHub Desktop.
package connect5g.com.a5geo;
import android.Manifest;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.Api;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
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.OnSuccessListener;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;
import static connect5g.com.a5geo.Main.REQUEST_DENIED;
import static connect5g.com.a5geo.Main.permissionsList;
public class LocationBackgroundService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{
Context context = getApplicationContext();
private LocationManager mLocationManager = null;
public FusedLocationProviderClient mFusedLocationProviderClient;
private SharedPreferences mSharedPreferences;
private LocationListener mLocationListener;
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location fBGLocation;
private static final int LOC_INTERVAL = 30000;
private static final int LOC_FAST_INTERVAL = 15000;
private static final int LOC_DISTANCE = 0;
private String sPrefID;
String TAG_BGSERVICE = "LOC BACKGROUND SERVICE:";
Double mLatitude, mLongtitude;
boolean isServiceAllowed;
private Main main = new Main();
private class LocationListener implements com.google.android.gms.location.LocationListener{
public LocationListener(){ }
@Override
public void onLocationChanged(Location location) {
Log.i(TAG_BGSERVICE,"onLocationChanged");
mLatitude = location.getLatitude();
mLongtitude = location.getLongitude();
}
}
/* gets invoked by call of bindService, so another component can bind with the service. Return null
unless no client is required to communicate, else return IBinder to provide client an interface.
*/
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.v("LOC BACKGROUND SERVICE","BOUND");
return null;
}
/* gets invoked by call of startService() by another component(i.e activity), then
service keeps running in the background until gets one of stopSelf()[called inner]/
stopService()[called outer]. if only binding is required, no need to implement onStartCommand().
* */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v("LOC BACKGROUND SERVICE","onStartCommand");
boolean stopService = false;
if ( intent != null )
stopService = intent.getBooleanExtra("Stop", false);
mLocationListener = new LocationListener();
if( stopService )
stopLocationUpdates();
else{
if (!mGoogleApiClient.isConnected())
mGoogleApiClient.connect();
}
return START_STICKY;
}
/* Service class run tasks on the main thread. new threads can be added at onStartCommand() [Careful with UI operations.] */
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG_BGSERVICE, "onCreate");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
mSharedPreferences = getSharedPreferences("driver_app", MODE_PRIVATE);
sPrefID = mSharedPreferences.getString("driver_id", "");
createGoogleApiClient();
}
protected synchronized void createGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
LocationCallback mLocationCallBack = new LocationCallback(){
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
for( Location location : locationResult.getLocations()){
Log.i(TAG_BGSERVICE,"onLocationResult"+Double.toString(location.getLatitude())+"\t"+Double.toString(location.getLongitude()));
}
}
};
void makeLocationRequest(){
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(LOC_INTERVAL);
mLocationRequest.setFastestInterval(LOC_FAST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
/*if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED){
mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallBack, Looper.myLooper());
}*/
}
public void startLocationUpdates(){
if(checkPermission()) {
mFusedLocationProviderClient.getLastLocation().addOnSuccessListener(main, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if ( location != null){
Log.i(TAG_BGSERVICE,"BG location service");
fBGLocation = location ;
}
}
});
}
}
public void stopLocationUpdates(){
mFusedLocationProviderClient.removeLocationUpdates(mLocationCallBack);
}
@Override
public void onConnected(@Nullable Bundle bundle) {
makeLocationRequest();
startLocationUpdates();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.v("LOC BACKGROUND SERVICE","FAILED");
}
/* the last call for the service to clean sources(threads), unregister listeners/receivers */
@Override
public void onDestroy() {
Log.v("LOC BACKGROUND SERVICE","DESTROY");
super.onDestroy();
}
@Override
public void onConnectionSuspended(int i) {
Log.v("LOC BACKGROUND SERVICE","SUSPENDED");
}
public boolean checkPermission() {
if (ContextCompat.checkSelfPermission(context, permissionsList[0]) == PackageManager.PERMISSION_GRANTED ){
if (ContextCompat.checkSelfPermission(context, permissionsList[1]) == PackageManager.PERMISSION_GRANTED){
if (ContextCompat.checkSelfPermission(context, permissionsList[2]) == PackageManager.PERMISSION_GRANTED) {
isServiceAllowed = true;
}
}
}
else if (ContextCompat.checkSelfPermission(context, permissionsList[0]) == PackageManager.PERMISSION_DENIED ||
ContextCompat.checkSelfPermission(context, permissionsList[2]) == PackageManager.PERMISSION_DENIED){
Toast.makeText(context, "Location share is not permitted, application will not function as supposed to.", Toast.LENGTH_LONG).show();
Log.i(REQUEST_DENIED, "DENIAL OF SERVICE REQUEST.");
isServiceAllowed = false;
}
return isServiceAllowed;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment