Advertisement
Guest User

GoogleApiClient Location Service

a guest
Apr 3rd, 2015
1,626
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.77 KB | None | 0 0
  1. package hu.company.testproject.service;
  2.  
  3. import hu.company.testproject.async.requests.SendLocationAsync;
  4. import hu.company.testproject.async.requests.SendLocationAsync.SendLocationListener;
  5. import hu.company.testproject.async.util.AsyncResult;
  6. import hu.company.testproject.async.util.Boat;
  7. import hu.company.testproject.async.util.Boat.LaunchQueeListener;
  8. import hu.company.testproject.database.DatabaseHelper;
  9. import hu.company.testproject.debug.BatteryUtil;
  10. import hu.company.testproject.debug.FileLogger;
  11. import hu.company.testproject.modul.LocationWrapper;
  12. import hu.company.testproject.modul.StageUnit;
  13. import hu.company.testproject.modul.User;
  14. import hu.company.testproject.util.Bear;
  15. import hu.company.testproject.util.LocationJSONMaker;
  16. import hu.company.testproject.util.NotificationUtil;
  17. import hu.company.testproject.util.NumFormatter;
  18. import hu.company.testproject.util.ScreenUtil;
  19.  
  20. import java.util.Random;
  21. import java.util.Set;
  22.  
  23. import org.json.JSONException;
  24. import org.json.JSONObject;
  25.  
  26. import android.app.Service;
  27. import android.content.Intent;
  28. import android.location.Location;
  29. import android.os.Build;
  30. import android.os.Bundle;
  31. import android.os.Debug;
  32. import android.os.IBinder;
  33. import android.support.v4.content.LocalBroadcastManager;
  34. import android.util.Log;
  35.  
  36. import com.google.android.gms.common.ConnectionResult;
  37. import com.google.android.gms.common.api.GoogleApiClient;
  38. import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
  39. import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
  40. import com.google.android.gms.location.LocationListener;
  41. import com.google.android.gms.location.LocationRequest;
  42. import com.google.android.gms.location.LocationServices;
  43. import com.google.android.gms.maps.LocationSource;
  44.  
  45. public class GpsService extends Service implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener, LaunchQueeListener, SendLocationListener {
  46.  
  47.     private static long UPDATE_INTERVAL = 5000; // /< location update interval
  48.     // private static long FASTEST_INTERVAL = 3000; // /< fatest location update interval
  49.     // private static float DISPLACE_METERS = 0.0f; // displacement in meters
  50.     private LocationRequest mLocationRequest;
  51.     private final String TAG = "Locationing_GpsService_testproject";
  52.     private final boolean DEBUG = true;
  53.     private GoogleApiClient mGoogleApiClient;
  54.     private LocationWrapper mLastLocation;
  55.     private Boat boat;
  56.     private User user;
  57.     private StageUnit stageUnit;
  58.     private String TAG2 = "Debug_service";
  59.  
  60.     public static final String LOCATION_CHANGED = "location_changed";
  61.  
  62.     private void log(Object o) {
  63.         if (DEBUG) {
  64.             Log.i(TAG, o.toString());
  65.             FileLogger.appendToLog(o);
  66.         }
  67.     }
  68.  
  69.    
  70.     @Override
  71.     public void onCreate() {
  72.  
  73.         Log.i(TAG2, "onCreate!");
  74.  
  75.         log("======================================================================");
  76.         log("onCreate:SESSION_START|===============================================");
  77.         log("======================================================================");
  78.         log("Device_manufacturer:" + Build.MANUFACTURER);
  79.         log("Device_model:" + Build.MODEL);
  80.         log("Android_ver_number:" + Build.VERSION.RELEASE);
  81.         log("Android_SDK_ver:" + Build.VERSION.SDK_INT);
  82.         log("State:onCreate");
  83.         log("VmHeapSizeLimit: " + Runtime.getRuntime().maxMemory() / 1048576);
  84.  
  85.         user = DatabaseHelper.getInstance(this).readLoggedInUser();
  86.  
  87.    
  88.         if (user == null) {
  89.             stopSelf();
  90.         } else {
  91.             stageUnit = DatabaseHelper.getInstance(this).readRunningStageForUser(user);
  92.             //
  93.             boat = new Boat(1, 5);
  94.             boat.addListener(this);
  95.         }
  96.  
  97.     }
  98.  
  99.    
  100.     @Override
  101.     public int onStartCommand(Intent intent, int flags, int startId) {
  102.         log("onStartCommand:now");
  103.  
  104.         Log.i(TAG2, "onStartCommand!");
  105.  
  106.         Bundle extras = intent.getExtras();
  107.         String userIdParam = extras.getString("user_id");
  108.  
  109.         // A paraméterből kapott user nem egyezik a bejelentkezett userrel, így nem futtatható a location service
  110.         if (user != null && user.getUserId().equals(userIdParam)) {
  111.             log("userCheck:" + "logged in user is equals param user");
  112.         } else {
  113.             log("userCheck:" + "logged in user is NOT equals param user");
  114.             stopSelf();
  115.         }
  116.  
  117.         initGoogleApiClient();
  118.         googleApiClientConnect();
  119.  
  120.         return START_REDELIVER_INTENT;
  121.     }
  122.  
  123.     /**
  124.      * initing google api client
  125.      */
  126.     private void initGoogleApiClient() {
  127.  
  128.         Log.i(TAG2, "initGoogleApiClient!");
  129.  
  130.         mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API).addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
  131.         log("Google_API_client:initing");
  132.     }
  133.  
  134.    
  135.     @Override
  136.     public IBinder onBind(Intent intent) {
  137.         return null;
  138.     }
  139.  
  140.     /**
  141.      * Creating location request object with locationing parameters
  142.      * */
  143.     private void initLocationRequest() {
  144.  
  145.         if (mLocationRequest == null) {
  146.  
  147.             mLocationRequest = new LocationRequest();
  148.             mLocationRequest.setInterval(UPDATE_INTERVAL);
  149.             mLocationRequest.setFastestInterval(UPDATE_INTERVAL);
  150.             // mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
  151.             mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  152.             // mLocationRequest.setSmallestDisplacement(DISPLACE_METERS); // 10 meters
  153.  
  154.             log("initLocationRequest:initing_now");
  155.         } else {
  156.             log("initLocationRequest:already_inited");
  157.         }
  158.  
  159.         log("initLocationRequest:interval_" + mLocationRequest.getInterval());
  160.         log("initLocationRequest:priority_" + mLocationRequest.getPriority());
  161.  
  162.     }
  163.  
  164.     /**
  165.      * Starts location listenint
  166.      */
  167.     private void startLocationListening() {
  168.  
  169.         Log.i(TAG2, "startLocationListening!");
  170.         log("Starting_location_listening:now");
  171.         LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
  172.     }
  173.  
  174.     /**
  175.      * Stops location listening
  176.      */
  177.     private void stopLocationListening() {
  178.  
  179.         Log.i(TAG2, "Stopping_location_listening:now!");
  180.         log("Stopping_location_listening:now");
  181.  
  182.         if (mGoogleApiClient.isConnected())
  183.             LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
  184.     }
  185.  
  186.    
  187.     @Override
  188.     public void onDestroy() {
  189.         Log.i(TAG2, "onDestroy!");
  190.         log("State:onDestroy");
  191.         BatteryUtil.unregister(getApplicationContext());
  192.         if (boat != null) {
  193.             boat.removeListener();
  194.         }
  195.         stopLocationListening();
  196.         mGoogleApiClient.disconnect();
  197.  
  198.     }
  199.  
  200.     /**
  201.      *
  202.      * Calls when location is changed
  203.      */
  204.     @Override
  205.     public void onLocationChanged(Location location) {
  206.  
  207.         NotificationUtil.showLocationNotification(this, stageUnit, user);
  208.  
  209.         float bearing = 0;
  210.         // Már volt legalább 1 mérés
  211.         if (mLastLocation != null) {
  212.             bearing = Bear.getBearing(mLastLocation.getLatitude(), mLastLocation.getLongitude(), location.getLatitude(), location.getLongitude());
  213.             Log.i("bearing_szamitva", bearing + "");
  214.         }
  215.  
  216.         if (location.getAccuracy() <= 99) {
  217.             mLastLocation = new LocationWrapper(location);
  218.  
  219.             mLastLocation.setBearing(bearing);
  220.             mLastLocation.setStageId(stageUnit.id);
  221.             mLastLocation.setUserId(user.getUserId());
  222.  
  223.             DatabaseHelper.getInstance(this).insertLocation(mLastLocation);
  224.  
  225.             boat.addAll(DatabaseHelper.getInstance(this).readNotSentLocations(stageUnit, user));
  226.  
  227.             Intent locationChangedIntent = new Intent(LOCATION_CHANGED);
  228.             locationChangedIntent.putExtra("location", mLastLocation);
  229.             LocalBroadcastManager.getInstance(this).sendBroadcast(locationChangedIntent);
  230.  
  231.             logLocation(mLastLocation);
  232.         } else {
  233.             log("LocationAccuracyWasTooHigh:droppingLocation");
  234.         }
  235.  
  236.     }
  237.  
  238.     private void logLocation(LocationWrapper lw) {
  239.  
  240.         log("onLC:" + lw.toString());
  241.  
  242.         log("screenIsOn:" + ScreenUtil.isScreenOn(this));
  243.         log("VmHeapSize:" + Runtime.getRuntime().totalMemory() / 1048576);
  244.         log("VmAllocMem:" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1048576));
  245.         log("NativeAllocMem:" + Debug.getNativeHeapAllocatedSize() / 1048576);
  246.  
  247.         try {
  248.             BatteryUtil.logBatteryPercentage(this);
  249.         } catch (Exception ex) {
  250.             ex.printStackTrace();
  251.         }
  252.  
  253.     }
  254.  
  255.    
  256.     private void googleApiClientConnect() {
  257.         Log.i(TAG2, "Google_Api_Client:tries_to_connect!!");
  258.         log("Google_Api_Client:tries_to_connect!");
  259.         mGoogleApiClient.connect();
  260.     }
  261.  
  262.     /**
  263.      *
  264.      * Google API client connected, init location request instance with params like interval, accuracy, etc
  265.      */
  266.  
  267.     @Override
  268.     public void onConnected(Bundle bundle) {
  269.  
  270.         Log.i(TAG2, "Google_Api_Client:connected.");
  271.         log("Google_Api_Client:connected.");
  272.  
  273.        
  274.         if (mGoogleApiClient.isConnected()) {
  275.             log("Google_Api_Client: It was connected on (onConnected) function, working as it should.");
  276.  
  277.             initLocationRequest();
  278.             startLocationListening();
  279.         } else {
  280.             log("Google_Api_Client: It was NOT connected on (onConnected) function, It is definetly bugged.");
  281.         }
  282.  
  283.     }
  284.  
  285.     /**
  286.      *
  287.      * Google API client suspended
  288.      */
  289.  
  290.     @Override
  291.     public void onConnectionSuspended(int arg) {
  292.         log("Google_Api_Client:connection_suspended:" + arg);
  293.     }
  294.  
  295.    
  296.  
  297.     @Override
  298.     public void onConnectionFailed(ConnectionResult connectionResult) {
  299.         log("Google_Api_Client:connection_failed:" + connectionResult.getErrorCode());
  300.         googleApiClientConnect();
  301.     }
  302.  
  303.     @Override
  304.     public void handleQueeIsFull(Set<LocationWrapper> locationSet) {
  305.  
  306.         log("Handling launch with: " + locationSet);
  307.  
  308.         SendLocationAsync sa = new SendLocationAsync(getApplicationContext(), locationSet, stageUnit);
  309.         sa.addListener(this);
  310.         sa.execute();
  311.  
  312.     }
  313.  
  314.     @Override
  315.     public void handleSendLocation(AsyncResult result) {
  316.  
  317.         if (result.equals(AsyncResult.succes)) {
  318.             log("Status:data_sent_to_server");
  319.             // Adatbázisban átállítja "sent" re azokat a lokációkat amiket felküldtük a szerverre sikeresen.
  320.             DatabaseHelper.getInstance(this).setLocationsToSent(boat.getAllLocations());
  321.             boat.clear();
  322.  
  323.         } else {
  324.             log("Status:data_FAILED_to_sent_to_server");
  325.         }
  326.  
  327.     }
  328.  
  329. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement