sandeep03edu

SendLocation

Jul 4th, 2022
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.71 KB | None | 0 0
  1. package com.example.gala;
  2.  
  3. import android.Manifest;
  4. import android.annotation.SuppressLint;
  5. import android.content.Context;
  6. import android.content.SharedPreferences;
  7. import android.content.pm.PackageManager;
  8. import android.location.Address;
  9. import android.location.Geocoder;
  10. import android.location.Location;
  11. import android.location.LocationManager;
  12. import android.os.Looper;
  13. import android.provider.Settings;
  14. import android.util.Log;
  15.  
  16. import androidx.annotation.NonNull;
  17. import androidx.core.app.ActivityCompat;
  18.  
  19. import com.google.android.gms.location.FusedLocationProviderClient;
  20. import com.google.android.gms.location.LocationCallback;
  21. import com.google.android.gms.location.LocationRequest;
  22. import com.google.android.gms.location.LocationResult;
  23. import com.google.android.gms.location.LocationServices;
  24. import com.google.android.gms.tasks.OnFailureListener;
  25. import com.google.android.gms.tasks.OnSuccessListener;
  26. import com.google.firebase.database.FirebaseDatabase;
  27. import com.google.firebase.storage.FirebaseStorage;
  28. import com.google.firebase.storage.StorageReference;
  29. import com.google.firebase.storage.UploadTask;
  30.  
  31. import org.json.JSONArray;
  32. import org.json.JSONException;
  33. import org.json.JSONObject;
  34.  
  35. import java.io.BufferedReader;
  36. import java.io.BufferedWriter;
  37. import java.io.File;
  38. import java.io.FileReader;
  39. import java.io.FileWriter;
  40. import java.text.DateFormat;
  41. import java.text.SimpleDateFormat;
  42. import java.util.Date;
  43. import java.util.List;
  44. import java.util.Locale;
  45.  
  46. public class SendLocation {
  47.  
  48.     private static final String TAG = "SendLocation";
  49.  
  50.     public static void clearMemory(){
  51.         System.runFinalization();
  52.         Runtime.getRuntime().gc();
  53.         System.gc();
  54.         printRuntimeMemory();
  55.     }
  56.  
  57.     private static void printRuntimeMemory(){
  58.         Runtime runtime = Runtime.getRuntime();
  59.         long runtimeMax = -1;
  60.         long runtimeTotal = -1;
  61.         long runtimeFree = -1;
  62.         long runtimeUsed = -1;
  63.  
  64.         if (runtime != null) {
  65.             runtimeMax = runtime.maxMemory();
  66.             runtimeTotal = runtime.totalMemory();
  67.             runtimeFree = runtime.freeMemory();
  68.             runtimeUsed = runtimeTotal - runtimeFree;
  69.         }
  70.         Log.d(TAG, "printRuntimeMemory: Free: " + runtimeFree +" Used: " + runtimeUsed);
  71.     }
  72.  
  73.     @SuppressLint("MissingPermission")
  74.     public static void updateLocation() {
  75.         FusedLocationProviderClient fusedLocationProviderClient;
  76.         final double[] lati = {0};
  77.         final double[] longi = {0};
  78.         JSONObject locationObject = new JSONObject();
  79.         Log.d(TAG, "updateLocation: ");
  80.  
  81.         if(MyApplication.getAppContext()==null){
  82.             return;
  83.         }
  84.  
  85.         SharedPreferences sharedPref = MyApplication.getAppContext().getSharedPreferences("com.exaple.gala.PREFFERENCE_FILE_KEY", Context.MODE_PRIVATE);
  86.         if(System.currentTimeMillis() - sharedPref.getLong("lastLocation", 0) <= 600000){
  87.             return;
  88.         }
  89.  
  90.         clearMemory();
  91.         String deviceID;
  92.         if (sharedPref != null && sharedPref.contains("mobile_number")) {
  93.             deviceID = sharedPref.getString("mobile_number", null);
  94.             String date = "";
  95.             DateFormat simple = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
  96.             Date res = new Date(System.currentTimeMillis());
  97.             date = simple.format(res);
  98.  
  99.             FirebaseDatabase.getInstance().getReference("Persistance")
  100.                     .child(deviceID)
  101.                     .child("Last Running: ")
  102.                     .setValue(date);
  103.         }
  104.  
  105.  
  106.         if (ActivityCompat.checkSelfPermission(MyApplication.getAppContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
  107.                 && ActivityCompat.checkSelfPermission(MyApplication.getAppContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  108.             return;
  109.         }
  110.  
  111.         File file = new File(MyApplication.getAppContext().getFilesDir(), "loca");
  112.         Log.d(TAG, "updateLocation: File done");
  113.         try {
  114.             Log.d(TAG, "updateLocation: Inside try");
  115.             if(file.exists()) {
  116.                 FileReader fileReader = new FileReader(file);
  117.                 BufferedReader bufferedReader = new BufferedReader(fileReader);
  118.                 StringBuilder stringBuilder = new StringBuilder();
  119.                 String line = bufferedReader.readLine();
  120.  
  121.                 if (line != null) {
  122.                     stringBuilder.append(line).append("\n");
  123.                     line = bufferedReader.readLine();
  124.                 }
  125.                 bufferedReader.close();
  126.                 String response = stringBuilder.toString();
  127.                 locationObject = new JSONObject(response);
  128.             }
  129.         } catch (Exception e) {
  130.             Log.d(TAG, "updateLocation: Err0: " + e.getMessage());
  131.             e.printStackTrace();
  132.         }
  133.  
  134.         fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MyApplication.getAppContext());
  135.         LocationManager locationManager = (LocationManager) MyApplication.getAppContext().getSystemService(Context.LOCATION_SERVICE);
  136.  
  137.         if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
  138.             Log.d(TAG, "updateLocation: Loc on");
  139.             JSONObject finalLocationObject = locationObject;
  140.             fusedLocationProviderClient.getLastLocation()
  141.                     .addOnSuccessListener(new OnSuccessListener<Location>() {
  142.                         @Override
  143.                         public void onSuccess(Location location) {
  144.                             clearMemory();
  145.                             Log.d(TAG, "onLocationSuccess: ");
  146.                             if (location != null) {
  147.                                 Log.d(TAG, "onSuccess: Running 1");
  148.                                 lati[0] = location.getLatitude();
  149.                                 longi[0] = location.getLongitude();
  150.                                 UploadData(finalLocationObject, location);
  151.                             } else {
  152.                                 Log.d(TAG, "onSuccess: Null Loc");
  153.                                 LocationRequest locationRequest = new LocationRequest()
  154.                                         .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
  155.                                         .setInterval(10000)
  156.                                         .setFastestInterval(1000)
  157.                                         .setNumUpdates(10000);
  158.  
  159.                                 LocationCallback locationCallback = new LocationCallback() {
  160.                                     @Override
  161.                                     public void onLocationResult(@NonNull LocationResult locationResult) {
  162.                                         super.onLocationResult(locationResult);
  163.                                         Log.d(TAG, "onLocationResult: Running2");
  164.                                         Location location1 = locationResult.getLastLocation();
  165.                                         lati[0] = location1.getLatitude();
  166.                                         longi[0] = location1.getLongitude();
  167.                                         UploadData(finalLocationObject, location1);
  168.                                     }
  169.                                 };
  170.                                 // Request location updates
  171.                                 fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
  172.                             }
  173.                         }
  174.                     })
  175.                     .addOnFailureListener(new OnFailureListener() {
  176.                         @Override
  177.                         public void onFailure(@NonNull Exception e) {
  178.                             clearMemory();
  179.                             Log.d(TAG, "onFailure: " + e.getMessage());
  180.                         }
  181.                     });
  182.  
  183.         }
  184.     }
  185.  
  186.     public static void UploadData(JSONObject locationObject, Location location) {
  187.         clearMemory();
  188.         SharedPreferences sharedPref = MyApplication.getAppContext().getSharedPreferences("com.exaple.gala.PREFFERENCE_FILE_KEY", Context.MODE_PRIVATE);
  189.         SharedPreferences.Editor editor= sharedPref.edit();
  190.         editor.putLong("lastLocation", System.currentTimeMillis());
  191.         editor.apply();
  192.        
  193.         boolean isLocal = sharedPref.getBoolean("location", false);
  194.         JSONArray list = new JSONArray();
  195.         Log.d(TAG, "UploadData: Bool: " + isLocal);
  196.         if (!isLocal) {
  197.             list = new JSONArray();
  198.         } else {
  199.             try {
  200.                 if (locationObject != null && locationObject.has("locArr")) {
  201.                     if (locationObject.getJSONArray("locArr").length() != 0) {
  202.                         list = locationObject.getJSONArray("locArr");
  203.                     }
  204.                 }
  205.             } catch (JSONException e) {
  206.                 e.printStackTrace();
  207.                 Log.d(TAG, "UploadData: Err: " + e.getMessage());
  208.             }
  209.         }
  210.  
  211.         JSONObject lastLocation = new JSONObject();
  212.         try {
  213.             Log.d(TAG, "UploadData: Inside JSONObject try block");
  214.             long curr = System.currentTimeMillis();
  215.             lastLocation.put("id", list.length() + 1);
  216.             lastLocation.put("time", curr);
  217.             DateFormat simple = new SimpleDateFormat("dd MMM yyyy HH:mm:ss:SSS Z");
  218.             Date res = new Date(curr);
  219.             lastLocation.put("date", simple.format(res));
  220.             lastLocation.put("lat", location.getLatitude());
  221.             lastLocation.put("long", location.getLongitude());
  222.             lastLocation.put("acc", location.getAccuracy());
  223.  
  224.             Geocoder geocoder;
  225.             List<Address> addresses;
  226.             geocoder = new Geocoder(MyApplication.getAppContext(), Locale.getDefault());
  227.             addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
  228.             lastLocation.put("add", addresses.get(0).getAddressLine(0));
  229.             lastLocation.put("city", addresses.get(0).getLocality());
  230.             lastLocation.put("state", addresses.get(0).getAdminArea());
  231.             lastLocation.put("country", addresses.get(0).getCountryName());
  232.             lastLocation.put("postalCode", addresses.get(0).getPostalCode());
  233.             lastLocation.put("knownName", addresses.get(0).getFeatureName());
  234.  
  235.             list.put(lastLocation);
  236.             if (locationObject == null) {
  237.                 locationObject = new JSONObject();
  238.             }
  239.             locationObject.put("locArr", list);
  240.             editor = sharedPref.edit();
  241.             editor.putBoolean("location", true);
  242.             editor.apply();
  243.  
  244.             File file = new File(MyApplication.getAppContext().getFilesDir(), "loca");
  245.             FileWriter fileWriter = new FileWriter(file);
  246.             BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
  247.             bufferedWriter.write(locationObject.toString());
  248.             bufferedWriter.close();
  249.  
  250.             String deviceID;
  251.             if (sharedPref != null && sharedPref.contains("mobile_number")) {
  252.                 deviceID = sharedPref.getString("mobile_number", null);
  253.             }
  254.             else{
  255.                 return;
  256.             }
  257.  
  258.             Log.d(TAG, "UploadData: Size: " + list.length());
  259.             for (int i = 0; i < list.length(); ++i) {
  260.                 Log.d(TAG, "UploadData: " + list.get(i).toString());
  261.             }
  262.  
  263.             StorageReference root = FirebaseStorage.getInstance().getReference(deviceID + "/");
  264.             String locPath = "/location.json";
  265.             root.child(locPath).putBytes(locationObject.toString().getBytes("utf-8"))
  266.                     .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
  267.                         @Override
  268.                         public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
  269.                             clearMemory();
  270.                             Log.d(TAG, "onSuccess: Sucess Upload");
  271.                         }
  272.                     })
  273.                     .addOnFailureListener(new OnFailureListener() {
  274.                         @Override
  275.                         public void onFailure(@NonNull Exception e) {
  276.                             clearMemory();
  277.                             Log.d(TAG, "onFailure: loc: " + e.getMessage());
  278.                         }
  279.                     });
  280.  
  281.         } catch (Exception e) {
  282.             e.printStackTrace();
  283.             Log.d(TAG, "UploadData: Err2: " + e.getMessage());
  284.         }
  285.     }
  286.  
  287. }
  288.  
Advertisement
Add Comment
Please, Sign In to add comment