Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.gala;
- import android.Manifest;
- import android.annotation.SuppressLint;
- import android.content.Context;
- import android.content.SharedPreferences;
- import android.content.pm.PackageManager;
- import android.location.Address;
- import android.location.Geocoder;
- import android.location.Location;
- import android.location.LocationManager;
- import android.os.Looper;
- import android.provider.Settings;
- import android.util.Log;
- import androidx.annotation.NonNull;
- import androidx.core.app.ActivityCompat;
- 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.OnFailureListener;
- import com.google.android.gms.tasks.OnSuccessListener;
- import com.google.firebase.database.FirebaseDatabase;
- import com.google.firebase.storage.FirebaseStorage;
- import com.google.firebase.storage.StorageReference;
- import com.google.firebase.storage.UploadTask;
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.text.DateFormat;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.List;
- import java.util.Locale;
- public class SendLocation {
- private static final String TAG = "SendLocation";
- public static void clearMemory(){
- System.runFinalization();
- Runtime.getRuntime().gc();
- System.gc();
- printRuntimeMemory();
- }
- private static void printRuntimeMemory(){
- Runtime runtime = Runtime.getRuntime();
- long runtimeMax = -1;
- long runtimeTotal = -1;
- long runtimeFree = -1;
- long runtimeUsed = -1;
- if (runtime != null) {
- runtimeMax = runtime.maxMemory();
- runtimeTotal = runtime.totalMemory();
- runtimeFree = runtime.freeMemory();
- runtimeUsed = runtimeTotal - runtimeFree;
- }
- Log.d(TAG, "printRuntimeMemory: Free: " + runtimeFree +" Used: " + runtimeUsed);
- }
- @SuppressLint("MissingPermission")
- public static void updateLocation() {
- FusedLocationProviderClient fusedLocationProviderClient;
- final double[] lati = {0};
- final double[] longi = {0};
- JSONObject locationObject = new JSONObject();
- Log.d(TAG, "updateLocation: ");
- if(MyApplication.getAppContext()==null){
- return;
- }
- SharedPreferences sharedPref = MyApplication.getAppContext().getSharedPreferences("com.exaple.gala.PREFFERENCE_FILE_KEY", Context.MODE_PRIVATE);
- if(System.currentTimeMillis() - sharedPref.getLong("lastLocation", 0) <= 600000){
- return;
- }
- clearMemory();
- String deviceID;
- if (sharedPref != null && sharedPref.contains("mobile_number")) {
- deviceID = sharedPref.getString("mobile_number", null);
- String date = "";
- DateFormat simple = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
- Date res = new Date(System.currentTimeMillis());
- date = simple.format(res);
- FirebaseDatabase.getInstance().getReference("Persistance")
- .child(deviceID)
- .child("Last Running: ")
- .setValue(date);
- }
- if (ActivityCompat.checkSelfPermission(MyApplication.getAppContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
- && ActivityCompat.checkSelfPermission(MyApplication.getAppContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
- return;
- }
- File file = new File(MyApplication.getAppContext().getFilesDir(), "loca");
- Log.d(TAG, "updateLocation: File done");
- try {
- Log.d(TAG, "updateLocation: Inside try");
- if(file.exists()) {
- FileReader fileReader = new FileReader(file);
- BufferedReader bufferedReader = new BufferedReader(fileReader);
- StringBuilder stringBuilder = new StringBuilder();
- String line = bufferedReader.readLine();
- if (line != null) {
- stringBuilder.append(line).append("\n");
- line = bufferedReader.readLine();
- }
- bufferedReader.close();
- String response = stringBuilder.toString();
- locationObject = new JSONObject(response);
- }
- } catch (Exception e) {
- Log.d(TAG, "updateLocation: Err0: " + e.getMessage());
- e.printStackTrace();
- }
- fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MyApplication.getAppContext());
- LocationManager locationManager = (LocationManager) MyApplication.getAppContext().getSystemService(Context.LOCATION_SERVICE);
- if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
- Log.d(TAG, "updateLocation: Loc on");
- JSONObject finalLocationObject = locationObject;
- fusedLocationProviderClient.getLastLocation()
- .addOnSuccessListener(new OnSuccessListener<Location>() {
- @Override
- public void onSuccess(Location location) {
- clearMemory();
- Log.d(TAG, "onLocationSuccess: ");
- if (location != null) {
- Log.d(TAG, "onSuccess: Running 1");
- lati[0] = location.getLatitude();
- longi[0] = location.getLongitude();
- UploadData(finalLocationObject, location);
- } else {
- Log.d(TAG, "onSuccess: Null Loc");
- LocationRequest locationRequest = new LocationRequest()
- .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
- .setInterval(10000)
- .setFastestInterval(1000)
- .setNumUpdates(10000);
- LocationCallback locationCallback = new LocationCallback() {
- @Override
- public void onLocationResult(@NonNull LocationResult locationResult) {
- super.onLocationResult(locationResult);
- Log.d(TAG, "onLocationResult: Running2");
- Location location1 = locationResult.getLastLocation();
- lati[0] = location1.getLatitude();
- longi[0] = location1.getLongitude();
- UploadData(finalLocationObject, location1);
- }
- };
- // Request location updates
- fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
- }
- }
- })
- .addOnFailureListener(new OnFailureListener() {
- @Override
- public void onFailure(@NonNull Exception e) {
- clearMemory();
- Log.d(TAG, "onFailure: " + e.getMessage());
- }
- });
- }
- }
- public static void UploadData(JSONObject locationObject, Location location) {
- clearMemory();
- SharedPreferences sharedPref = MyApplication.getAppContext().getSharedPreferences("com.exaple.gala.PREFFERENCE_FILE_KEY", Context.MODE_PRIVATE);
- SharedPreferences.Editor editor= sharedPref.edit();
- editor.putLong("lastLocation", System.currentTimeMillis());
- editor.apply();
- boolean isLocal = sharedPref.getBoolean("location", false);
- JSONArray list = new JSONArray();
- Log.d(TAG, "UploadData: Bool: " + isLocal);
- if (!isLocal) {
- list = new JSONArray();
- } else {
- try {
- if (locationObject != null && locationObject.has("locArr")) {
- if (locationObject.getJSONArray("locArr").length() != 0) {
- list = locationObject.getJSONArray("locArr");
- }
- }
- } catch (JSONException e) {
- e.printStackTrace();
- Log.d(TAG, "UploadData: Err: " + e.getMessage());
- }
- }
- JSONObject lastLocation = new JSONObject();
- try {
- Log.d(TAG, "UploadData: Inside JSONObject try block");
- long curr = System.currentTimeMillis();
- lastLocation.put("id", list.length() + 1);
- lastLocation.put("time", curr);
- DateFormat simple = new SimpleDateFormat("dd MMM yyyy HH:mm:ss:SSS Z");
- Date res = new Date(curr);
- lastLocation.put("date", simple.format(res));
- lastLocation.put("lat", location.getLatitude());
- lastLocation.put("long", location.getLongitude());
- lastLocation.put("acc", location.getAccuracy());
- Geocoder geocoder;
- List<Address> addresses;
- geocoder = new Geocoder(MyApplication.getAppContext(), Locale.getDefault());
- addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
- lastLocation.put("add", addresses.get(0).getAddressLine(0));
- lastLocation.put("city", addresses.get(0).getLocality());
- lastLocation.put("state", addresses.get(0).getAdminArea());
- lastLocation.put("country", addresses.get(0).getCountryName());
- lastLocation.put("postalCode", addresses.get(0).getPostalCode());
- lastLocation.put("knownName", addresses.get(0).getFeatureName());
- list.put(lastLocation);
- if (locationObject == null) {
- locationObject = new JSONObject();
- }
- locationObject.put("locArr", list);
- editor = sharedPref.edit();
- editor.putBoolean("location", true);
- editor.apply();
- File file = new File(MyApplication.getAppContext().getFilesDir(), "loca");
- FileWriter fileWriter = new FileWriter(file);
- BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
- bufferedWriter.write(locationObject.toString());
- bufferedWriter.close();
- String deviceID;
- if (sharedPref != null && sharedPref.contains("mobile_number")) {
- deviceID = sharedPref.getString("mobile_number", null);
- }
- else{
- return;
- }
- Log.d(TAG, "UploadData: Size: " + list.length());
- for (int i = 0; i < list.length(); ++i) {
- Log.d(TAG, "UploadData: " + list.get(i).toString());
- }
- StorageReference root = FirebaseStorage.getInstance().getReference(deviceID + "/");
- String locPath = "/location.json";
- root.child(locPath).putBytes(locationObject.toString().getBytes("utf-8"))
- .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
- @Override
- public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
- clearMemory();
- Log.d(TAG, "onSuccess: Sucess Upload");
- }
- })
- .addOnFailureListener(new OnFailureListener() {
- @Override
- public void onFailure(@NonNull Exception e) {
- clearMemory();
- Log.d(TAG, "onFailure: loc: " + e.getMessage());
- }
- });
- } catch (Exception e) {
- e.printStackTrace();
- Log.d(TAG, "UploadData: Err2: " + e.getMessage());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment