如何使用GPS和网络提供商获取位置?

时间:2015-02-28 20:16:52

标签: android gps

我想实现以下代码来制作一个应用程序,该应用程序将使用GPS或NETWORK提供程序获取手机的位置。我不知道如何从活动中调用或触发此代码以获取按钮的onclick位置。 另外我不知道应该首先调用哪个方法以及应该调用哪些方法来获取location.Please帮助我知道以下代码的流程以获取位置。简而言之,我如何从下面的代码中创建一个应用程序来获取点击按钮点击手机的位置......请帮帮我。

Generic LocationTracker界面。允许我们拥有多种类型的位置跟踪器并轻松插入相应的位置跟踪器:

package com.gabesechan.android.reusable.location;
import android.location.Location;

public interface LocationTracker {
public interface LocationUpdateListener{
    public void onUpdate(Location oldLoc, long oldTime, Location newLoc, long newTime);
}

public void start();
public void start(LocationUpdateListener update);

public void stop();

public boolean hasLocation();

public boolean hasPossiblyStaleLocation();

public Location getLocation();

public Location getPossiblyStaleLocation();

}

ProviderLocationTracker-此类将跟踪GPS或网络的位置。

package com.gabesechan.android.reusable.location;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class ProviderLocationTracker implements LocationListener,   LocationTracker {

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

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

private LocationManager lm;

public enum ProviderType{
    NETWORK,
    GPS
};    
private String provider;

private Location lastLocation;
private long lastTime;

private boolean isRunning;

private LocationUpdateListener listener;

public ProviderLocationTracker(Context context, ProviderType type) {
    lm =  (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
    if(type == ProviderType.NETWORK){
        provider = LocationManager.NETWORK_PROVIDER;
    }
    else{
        provider = LocationManager.GPS_PROVIDER;
    }
}

public void start(){
    if(isRunning){
        //Already running, do nothing
        return;
    }

    //The provider is on, so start getting updates.  Update current location
    isRunning = true;
    lm.requestLocationUpdates(provider, MIN_UPDATE_TIME, MIN_UPDATE_DISTANCE, this);
    lastLocation = null;
    lastTime = 0;
    return;
}

public void start(LocationUpdateListener update) {
    start();
    listener = update;

}


public void stop(){
    if(isRunning){
        lm.removeUpdates(this);
        isRunning = false;
        listener = null;
    }
}

public boolean hasLocation(){
    if(lastLocation == null){
        return false;
    }
    if(System.currentTimeMillis() - lastTime > 5 * MIN_UPDATE_TIME){
        return false; //stale
    }
    return true;
}

public boolean hasPossiblyStaleLocation(){
    if(lastLocation != null){
        return true;
    }
    return lm.getLastKnownLocation(provider)!= null;
}

public Location getLocation(){
    if(lastLocation == null){
        return null;
    }
    if(System.currentTimeMillis() - lastTime > 5 * MIN_UPDATE_TIME){
        return null; //stale
    }
    return lastLocation;
}

public Location getPossiblyStaleLocation(){
    if(lastLocation != null){
        return lastLocation;
    }
    return lm.getLastKnownLocation(provider);
}

public void onLocationChanged(Location newLoc) {
    long now = System.currentTimeMillis();
    if(listener != null){
        listener.onUpdate(lastLocation, lastTime, newLoc, now);
    }
    lastLocation = newLoc;
    lastTime = now;
}

public void onProviderDisabled(String arg0) {

}

public void onProviderEnabled(String arg0) {

}

public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}

}

是FallbackLocationProvider,它将通过GPS和NETWORK进行跟踪,并使用更准确的位置。

package com.gabesechan.android.reusable.location;

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
 public class FallbackLocationTracker  implements LocationTracker,          LocationTracker.LocationUpdateListener {


    private boolean isRunning;

    private ProviderLocationTracker gps;
    private ProviderLocationTracker net;

    private LocationUpdateListener listener;

    Location lastLoc;
    long lastTime;

    public FallbackLocationTracker(Context context) {
        gps = new ProviderLocationTracker(context, ProviderLocationTracker.ProviderType.GPS);
        net = new ProviderLocationTracker(context,    ProviderLocationTracker.ProviderType.NETWORK);
    }

    public void start(){
        if(isRunning){
            //Already running, do nothing
            return;
        }

        //Start both
        gps.start(this);
        net.start(this);
        isRunning = true;
    }

     public void start(LocationUpdateListener update) {
        start();
        listener = update;
    }


    public void stop(){
        if(isRunning){
            gps.stop();
            net.stop();
            isRunning = false;
            listener = null;
        }
    }

    public boolean hasLocation(){
        //If either has a location, use it
        return gps.hasLocation() || net.hasLocation();
    }

    public boolean hasPossiblyStaleLocation(){
        //If either has a location, use it
        return gps.hasPossiblyStaleLocation() || net.hasPossiblyStaleLocation();
    }

    public Location getLocation(){
        Location ret = gps.getLocation();
        if(ret == null){
            ret = net.getLocation();
        }
        return ret;
    }

    public Location getPossiblyStaleLocation(){
        Location ret = gps.getPossiblyStaleLocation();
        if(ret == null){
            ret = net.getPossiblyStaleLocation();
        }
        return ret;
    }

public void onUpdate(Location oldLoc, long oldTime, Location newLoc, long newTime) {
    boolean update = false;

    //We should update only if there is no last location, the provider is the same, or the provider is more accurate, or the old location is stale
    if(lastLoc == null){
        update = true;
    }
    else if(lastLoc != null && lastLoc.getProvider().equals(newLoc.getProvider())){
        update = true;
    }
    else if(newLoc.getProvider().equals(LocationManager.GPS_PROVIDER)){
        update = true;
    }
    else if (newTime - lastTime > 5 * 60 * 1000){
        update = true;
    }

    if(update){
        lastLoc = newLoc;
        lastTime = newTime;
        if(listener != null){
            listener.onUpdate(lastLoc, lastTime, newLoc, newTime);                  
        }
    }

}

}

1 个答案:

答案 0 :(得分:0)

按照下面的代码,它会更加可控,并为您提供任何您想要的

创建类GPSTracker.java并输入以下代码---

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
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;

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;

    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 = 10; // 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;
                // First get location from Network Provider
                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) {
    }

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

}

如何在您的主要活动中使用

 Button btnShowLocation;
    GPSTracker gps;

    //////inside the onCreate

//wharever button id in your layout
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);


    btnShowLocation.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {        
                    // create class object
                    gps = new GPSTracker(AndroidGPSTrackingActivity.this);

                    // check if GPS enabled     
                    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();    
                    }else{
                        // can't get location
                        // GPS or Network is not enabled
                        // Ask user to enable GPS/network in settings
                        gps.showSettingsAlert();
                    }

                }
            });

现在,您可以使用GPS和NetworkProvider轻松获取纬度和经度。

别忘了在你的清单中添加权限。

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />    
    <uses-permission android:name="android.permission.INTERNET" />

感谢http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/提供了一个很好的解释。