Showing posts with label Android GPS Location Service Listener run in background. Show all posts
Showing posts with label Android GPS Location Service Listener run in background. Show all posts

Tuesday 25 June 2019

Android GPS Location LocationListener for run in background Service

Here sharing code for make running background Service to Listen updated Location on particular time interval with using Time

Here Code for background Service

LocationUpdate.java

package com.ksample;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.*;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class LocationUpdate extends Service implements LocationListener {

     Context mContext;

     int USRMTM = 2000;

    // GPS status
    boolean isGPSEnabled = false;

    // Network status
    boolean isNetworkEnabled = false;

    // GPS status
    boolean canGetLocation = false;

    // Notify from background started
    public static String str_receiver = "messageSent";

    private Handler mHandler = new Handler();

    long notify_interval = 1000;

    Intent mintent;

    Location location; // location
    // The minimum distance to change Updates in meters

    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
    // Update to improve performance

    private static final long MIN_TIME_BW_UPDATES = 180000 * 1; // 1 minute
    // Declaring a Location Manager

    protected LocationManager locationManager;

    public static Boolean SingleEntry = true;

    String currentLongitude,currentLatitude,currentAddress;

    public LocationUpdate(Context context) {
        this.mContext = context;
        mintent = new Intent();
        // commented        mintent.setAction(str_receiver);

        Timer t = new Timer();
        t.scheduleAtFixedRate(new TimerTask() {
            @Override            public void run() {
                // Do your stuff                
                 ((MainActivity) mContext).runOnUiThread(new Runnable() {
                    @Override                    
                     public void run() {
                        try {
                            getLocation();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

        }, 0, USRMTM);
    }


    private static final int TWO_MINUTES = 3000 * 60 * 1;

    public Location getLocation() {
        //Update to Accurate Location        
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setPowerRequirement(Criteria.POWER_HIGH);
        criteria.setAltitudeRequired(false);
        criteria.setSpeedRequired(false);
        criteria.setCostAllowed(true);
        criteria.setBearingRequired(false);

        //API level 9 and up        criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
        criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);

        //29-08-2018 Upate End
        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
           // getting GPS status
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            // getting network status
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                // First get location from Network Provider
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, criteria, this, null);
                    //criteria                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        try {
                            location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                            this.canGetLocation = true;
                            fn_update(location);
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, criteria, this, null);
                    }

                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                            this.canGetLocation = true;
                            fn_update(location);
                        }
                    }

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }


    @Override    
     public void onLocationChanged(Location mlocation) {
        try {
            if (mlocation != null) {
                latitude = mlocation.getLatitude();
                longitude = mlocation.getLongitude();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override    
    public void onProviderDisabled(String provider) {
    }

    @Override    
     public void onProviderEnabled(String provider) {
    }

    @Override    
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override    
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override    
    public void onCreate() {
        super.onCreate();
    }

    private class TimerTaskToGetLocation extends TimerTask {
        @Override        public void run() {
            mHandler.post(new Runnable() {
                @Override                public void run() {
                    fn_getlocation();
                }
            });
        }
    }

    boolean mGPSEnable = false;
    boolean isNetworkEnable = false;
    double latitude, longitude;

    private void fn_getlocation() {
        locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
        mGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (!mGPSEnable && !isNetworkEnable) {
        } else {
            if (isNetworkEnable) {
                location = null;
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        Log.e("latitude", location.getLatitude() + "");
                        Log.e("longitude", location.getLongitude() + "");
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        fn_update(location);
                    }
                }
            }

            if (mGPSEnable) {
                location = null;
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (location != null) {
                        Log.e("latitude", location.getLatitude() + "");
                        Log.e("longitude", location.getLongitude() + "");
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        fn_update(location);
                    }
                }
            }
        }
    }

    private void fn_update(Location location) {

        currentLongitude = String.valueOf(location.getLongitude());
        currentLatitude = String.valueOf(location.getLatitude());
        getAddressFromLocation(location.getLatitude(), location.getLongitude(), mContext);
    }

    public static class MyReceiver extends BroadcastReceiver {
        public MyReceiver() {
        }

        @Override        public void onReceive(Context context, Intent intent) {

            final double latitude = Double.valueOf(intent.getStringExtra("latutide"));
            final double longitude = Double.valueOf(intent.getStringExtra("longitude"));
            final String Liveaddress = intent.getStringExtra("address");
            currentAddress = Liveaddress;
            Location startPoint = new Location("locationA");
            startPoint.setLatitude(latitude);
            startPoint.setLongitude(longitude);
            double mlatitude = 0;
            try {
                if (!TextUtils.isEmpty(currentLatitude)) {
                    mlatitude = Double.parseDouble(currentLatitude);
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            double mlongitude = 0;

            try {

                if (!TextUtils.isEmpty(currentLongitude)) {
                    mlongitude = Double.parseDouble(currentLongitude);
                }

            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            //=======================Match 2 Location Start =-================
            double mlatitude2 = 0;
            try {

                if (!TextUtils.isEmpty(currentLatitude)) {
                    mlatitude = Double.parseDouble(currentLatitude);
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            double mlongitude2 = 0;
            try {

                if (!TextUtils.isEmpty(currentLongitude)) {
                    mlongitude = Double.parseDouble(currentLongitude);
                }


            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            //======================================Match Seconnd Location End==================
            Location endPoint = new Location("locationB");
            endPoint.setLatitude(mlatitude);
            endPoint.setLongitude(mlongitude);

            //===========================Location C==========
            Location endPointC = new Location("locationC");
            endPointC.setLatitude(mlatitude2);
            endPointC.setLongitude(mlongitude2);


            //==================================End            // Location 1 get Distnace
            double distance = startPoint.distanceTo(endPoint);
            // Location 2 get Distnace
            double distance2 = startPoint.distanceTo(endPointC);

            boolean isAllowLogin;

            if (distance <= 2 || distance2<=2) {
                isAllowLogin = true;
                //=============                String isChecked ="false" ;
                try {
                    if(!Boolean.parseBoolean(isChecked)){
                        Toast.makeText(mContext,"Checked Enable True Location from Settting  ", Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                isAllowLogin = false;
            }
        }
    }

    @Override    
     public void onTaskRemoved(Intent rootIntent) {

        Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
        restartServiceIntent.setPackage(getPackageName());
        PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(
                AlarmManager.ELAPSED_REALTIME,
                SystemClock.elapsedRealtime() + 1000,
                restartServicePendingIntent);
        super.onTaskRemoved(rootIntent);
    }

    ///Address Encoding
    private static final String TAG = "LocationAddress";

    public void getAddressFromLocation(final double latitude, final double longitude, final Context context) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                Geocoder geocoder = new Geocoder(context, Locale.getDefault());
                String result = null;
                try {
                    List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
                    if (addressList != null && addressList.size() > 0) {
                        Address address = addressList.get(0);
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                            sb.append(address.getAddressLine(i)).append("\n");
                        }
                        sb.append(address.getLocality()).append("\n");
                        sb.append(address.getPostalCode()).append("\n");
                        sb.append(address.getCountryName());

                        //===============Updated Address
                        StringBuilder msb = new StringBuilder();

                        String maddress = addressList.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()                        String mcity = addressList.get(0).getLocality();
                        String mstate = addressList.get(0).getAdminArea();
                        String mcountry = addressList.get(0).getCountryName();
                        String mpostalCode = addressList.get(0).getPostalCode();
                        String mknownName = addressList.get(0).getFeatureName();

                        msb.append(maddress).append("\n");
                        result = msb.toString();

                        Log.e(TAG, "" + result.toString());
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Unable connect to Geocoder", e);
                } finally {
                    if (result != null) {

                        currentAddress = result;

                        try {
                            intent.putExtra("latutide", location.getLatitude() + "");
                            intent.putExtra("longitude", location.getLongitude() + "");
                            intent.putExtra("address", result + "");
                            mContext.sendBroadcast(intent);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else {

                        try {

                            intent.putExtra("latutide", location.getLatitude() + "");
                            intent.putExtra("longitude", location.getLongitude() + "");
                            intent.putExtra("address", "Unable to get address for this lat-long");
                            mContext.sendBroadcast(intent);

                            // Here we can Api call
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        };
        thread.start();
    }

}

Find Hours Diffrence in Kotlin

  In Kotlin, determining the difference in hours between two timestamps is a common task, especially in scenarios involving time-based calcu...