Not getting Latitude and longitude after every 1 minute in android

こ雲淡風輕ζ 提交于 2019-12-13 05:49:42

问题


I want to make an android program in that I get latitude and longitude in Toast after each 1 minute interval and populated on toast even after my application closed.

I have tried as below,But I only getting on time latitude and longitude,Please tell me what should i do for it to get continuously lat long in toast.My code is as below: GPStracker.java

package com.epe.trucktrackers;

import java.util.Timer;
import java.util.TimerTask;

import utils.Const;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;
    // flag for GPS status
    boolean canGetLocation = false;
    private Timer timer;
    private long UPDATE_INTERVAL;
    public static final String Stub = null;
    LocationManager mlocmag;
    LocationListener mlocList;
    private double lat, longn;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 5; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        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 {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

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

        return location;
    }

    /**
     * Stop using GPS listener Calling this function will stop using GPS in your
     * app
     * */
    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * 
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog On pressing Settings button will
     * lauch Settings Options
     * */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog
                .setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(
                                Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        mContext.startActivity(intent);
                    }
                });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {

        String message = String.format(
                "Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude());
        System.out.println(":::::::::::Ne lat longs............!!!" + message);
        longitude = location.getLongitude();
        latitude = location.getLatitude();
        Toast.makeText(mContext, latitude + " " + longitude, Toast.LENGTH_LONG)
                .show();
        /* UpdateWithNewLocation(location); */
        System.out.println(":Location chane");
    }

    @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;
    }

}

Activity.java

package com.epe.trucktrackers;

import org.json.JSONException;
import org.json.JSONObject;

import utils.Const;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import backend.BackendAPIService;

public class MainActivity extends Activity {
    EditText et_registration_no;
    Button btn_register;
    static GPSTracker gps;;
    String lat, lng;
    private ProgressDialog pDialog;
    String udid;
    String status;
    String tracking_id;
    String UDID;
    String lati;
    String longi;
    String registration_no;
    int flag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et_registration_no = (EditText) findViewById(R.id.et_truck_no);
        btn_register = (Button) findViewById(R.id.btn_reg);

        TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        udid = TelephonyMgr.getDeviceId();
        gps = new GPSTracker(MainActivity.this);

        btn_register.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                gps = new GPSTracker(MainActivity.this);
                if (gps.canGetLocation()) {

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                    // \n is for new line
                    Toast.makeText(
                            getApplicationContext(),
                            "Your Location is - \nLat: " + latitude
                                    + "\nLong: " + longitude, Toast.LENGTH_LONG)
                            .show();
                    lat = latitude + "";
                    lng = longitude + "";

                } else {
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();
                }
                new RegistartionApi().execute();

                System.out
                        .println("::::::::::::::service started:::::::::::::");
            }
        });

        // api call for the REGISTARTION ..!!

    }

    class RegistartionApi extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
            System.out
                    .println("==========inside preexecute===================");

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            String registrationURL = Const.API_REGISTRATION + "?UDID=" + udid
                    + "&latitude=" + lat + "&longitude=" + lng
                    + "&registration_no="
                    + et_registration_no.getText().toString().trim();
            registrationURL = registrationURL.replace(" ", "%");

            BackendAPIService sh = new BackendAPIService();
            System.out.println(":::::::::::::Registration url:::::::::::;"
                    + registrationURL);
            String jsonStr = sh.makeServiceCall(registrationURL,
                    BackendAPIService.POST);

            Log.d("Response: ", "> " + jsonStr);
            System.out.println("=============MY RESPONSE==========" + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    JSONObject c = new JSONObject(jsonStr);

                    if (jsonObj.has("status")) {
                        status = jsonObj.getString("status");
                        {
                            if (status.equalsIgnoreCase("success")) {
                                flag = 1;
                                c = jsonObj.getJSONObject("truck_tracking");
                                tracking_id = c.getString("tracking_id");
                                UDID = c.getString("UDID");
                                lati = c.getString("latitude");
                                longi = c.getString("longitude");
                                registration_no = c
                                        .getString("registration_no");

                            } else {
                                flag = 2;
                                Toast.makeText(MainActivity.this, "Failed",
                                        Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            if (flag == 1) {
                Toast.makeText(MainActivity.this, "Registration Done",
                        Toast.LENGTH_SHORT).show();
                /*Intent i = new Intent(getApplicationContext(), GPSTracker.class);
                startService(i);*/

            }

        }
    }

}

回答1:


Try this one. package com.sample.location;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class MyLocation {
    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled = false;
    boolean network_enabled = false;

    public boolean getLocation(Context context, LocationResult result) {
        // I use LocationResult callback class to pass location value from
        // MyLocation to user code.
        locationResult = result;
        if (lm == null)
            lm = (LocationManager) context
            .getSystemService(Context.LOCATION_SERVICE);

        // exceptions will be thrown if provider is not permitted.
        try {
            gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
        }
        try {
            network_enabled = lm
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
        }

        // don't start listeners if no provider is enabled
        if (!gps_enabled && !network_enabled)
            return false;

        if (gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
                    locationListenerGps);
        if (network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
                    locationListenerNetwork);
        timer1 = new Timer();
        timer1.schedule(new GetLastLocation(), 60*1000);
        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
        }

        /**
         * Called when the provider is disabled by the user. If requestLocationUpdates is called on an already disabled provider, this method is called immediately.
         * @param provider  
         *      the name of the location provider associated with this update.  
         */
        @Override
        public void onProviderDisabled(String provider) {
        }
        /**
         * Called when the provider is enabled by the user.
         * @param provider  
         *      the name of the location provider associated with this update.  
         */
        @Override
        public void onProviderEnabled(String provider) {
        }
        /**
         * Called when the provider status changes. This method is called when a provider is unable to fetch a location or if the provider has recently become available after a period of unavailability.
         * @param provider  
         *      the name of the location provider associated with this update. 
         * @param status  
         *      OUT_OF_SERVICE if the provider is out of service, and this is not expected to change in the near future; TEMPORARILY_UNAVAILABLE if the provider is temporarily unavailable but is expected to be available shortly; and AVAILABLE if the provider is currently available. 
         * @param extras  
         *      an optional Bundle which will contain provider specific status variables. 
                A number of common key/value pairs for the extras Bundle are listed below. Providers that use any of the keys on this list must provide the corresponding value as described below. 
                satellites - the number of satellites used to derive the fix 
         */
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    };

    LocationListener locationListenerNetwork = new LocationListener() {
        /**
         * Called when the location has changed. 
         * There are no restrictions on the use of the supplied Location object.
         * @param location  
         *      The new location, as a Location object.  
         */
        @Override
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }
        /**
         * Called when the provider is disabled by the user. If requestLocationUpdates is called on an already disabled provider, this method is called immediately.
         * @param provider  
         *      the name of the location provider associated with this update.  
         */
        @Override
        public void onProviderDisabled(String provider) {
        }
        /**
         * Called when the provider is enabled by the user.
         * @param provider  
         *      the name of the location provider associated with this update.  
         */
        @Override
        public void onProviderEnabled(String provider) {
        }
        /**
         * Called when the provider status changes. This method is called when a provider is unable to fetch a location or if the provider has recently become available after a period of unavailability.
         * @param provider  
         *      the name of the location provider associated with this update. 
         * @param status  
         *      OUT_OF_SERVICE if the provider is out of service, and this is not expected to change in the near future; TEMPORARILY_UNAVAILABLE if the provider is temporarily unavailable but is expected to be available shortly; and AVAILABLE if the provider is currently available. 
         * @param extras  
         *      an optional Bundle which will contain provider specific status variables. 
                A number of common key/value pairs for the extras Bundle are listed below. Providers that use any of the keys on this list must provide the corresponding value as described below. 
                satellites - the number of satellites used to derive the fix 
         */
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    };

    /**
     * The GPS location and Network location to be calculated
     * in every 5 seconds with the help of this class  
     *
     */
    class GetLastLocation extends TimerTask {
        @Override
        public void run() {
            lm.removeUpdates(locationListenerGps);
            lm.removeUpdates(locationListenerNetwork);

            Location net_loc = null, gps_loc = null;
            if (gps_enabled)
                gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (network_enabled)
                net_loc = lm
                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            // if there are both values use the latest one
            if (gps_loc != null && net_loc != null) {
                if (gps_loc.getTime() > net_loc.getTime())
                    locationResult.gotLocation(gps_loc);
                else
                    locationResult.gotLocation(net_loc);
                return;
            }

            if (gps_loc != null) {
                locationResult.gotLocation(gps_loc);
                return;
            }
            if (net_loc != null) {
                locationResult.gotLocation(net_loc);
                return;
            }
            locationResult.gotLocation(null);
        }
    }

    /**
     * This abstract class is used to get the location from other class.
     *
     */
    public static abstract class LocationResult {
        public abstract void gotLocation(Location location);
    }

}

In your Activity.java

LocationManager myLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
MyLocation myLocation = new MyLocation();
myLocation.getLocation(getApplicationContext(), locationResult);


    LocationResult locationResult = new LocationResult() {

        @Override
        public void gotLocation(Location location) {


            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
}
};


来源:https://stackoverflow.com/questions/23926311/not-getting-latitude-and-longitude-after-every-1-minute-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!