在android中没有获取移动数据的位置

时间:2014-01-31 09:47:57

标签: android gps location

移动数据打开时,我无法收到任何位置信息。当wifi打开但我的代码在移动数据上没有输出时,我的代码工作正常

我的代码:

    private void locationInit() {
    // TODO Auto-generated method stub
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
            0, this);

    statusOfGPS = locationManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);

    if (statusOfGPS) {
        speak = "You are in Home Page";
        tts = new TextToSpeech(this, this);
        Toast.makeText(this,"in location init", Toast.LENGTH_SHORT).show();
    } else {
        temp = 1;
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivityForResult(intent, 0);
    }

    gps = requestUpdatesFromProvider(LocationManager.GPS_PROVIDER,
            "GPS Not Supported");
    network = requestUpdatesFromProvider(LocationManager.NETWORK_PROVIDER,
            "Network Not Supported");

    if (gps != null && network != null) {
        location = getBetterLocation(gps, network);
    } else if (gps != null) {
        location = gps;
    } else if (network != null) {
        location = network;
    }

    if (location != null) {
        onLocationChanged(location);
    } else {
        latitude = 0.0;
        longitude = 0.0;
        address = "Unable to get address!";
    }
}


@Override
public void onLocationChanged(Location arg0) {
    // TODO Auto-generated method stub
    try {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        accuracy = location.getAccuracy();
        try {
            address = findAddress(latitude, longitude);
            tvAddress.setText(address);

        } catch (Exception e) {
            address = "Unable to get address";
        }
    } catch (Exception e) {
        Log.v("TEST", e.getMessage());
    }
}

private String findAddress(double l1, double l2) {
    // TODO Auto-generated method stub
    String addr, address;
    Geocoder geocoder;
    List<Address> addresses = null;
    geocoder = new Geocoder(this, Locale.getDefault());
    try {
        addresses = geocoder.getFromLocation(l1, l2, 1);
    } catch (IOException e1) {
        addresses = null;
    }

    addr = "Unable to get address";

    if (addresses != null) {
        address = addresses.get(0).getAddressLine(0);
        addrs = address;
        city = addresses.get(0).getAddressLine(1);
        country = addresses.get(0).getAddressLine(2);
        if (address == null)
            address = "";
        if (city == null)
            city = "";
        addr = address + " " + city + " " + country;
    }
    return addr;
}


private Location requestUpdatesFromProvider(final String provider,
        final String string) {
    Location location = null;
    if (locationManager.isProviderEnabled(provider)) {
        locationManager.requestLocationUpdates(provider, 1000 * 10, 10,
                this);
        location = locationManager.getLastKnownLocation(provider);
    } else {
        Toast.makeText(this, string, Toast.LENGTH_LONG).show();
    }
    return location;
}

protected Location getBetterLocation(Location newLocation,
        Location currentBestLocation) {
    if (currentBestLocation == null) {
        return newLocation;
    }

    long timeDelta = newLocation.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > 1000 * 120;
    boolean isSignificantlyOlder = timeDelta < -1000 * 120;
    boolean isNewer = timeDelta > 0;

    if (isSignificantlyNewer) {
        return newLocation;
    } else if (isSignificantlyOlder) {
        return currentBestLocation;
    }

    int accuracyDelta = (int) (newLocation.getAccuracy() - currentBestLocation
            .getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

    boolean isFromSameProvider = isSameProvider(newLocation.getProvider(),
            currentBestLocation.getProvider());

    if (isMoreAccurate) {
        return newLocation;
    } else if (isNewer && !isLessAccurate) {
        return newLocation;
    } else if (isNewer && !isSignificantlyLessAccurate
            && isFromSameProvider) {
        return newLocation;
    }
    return currentBestLocation;
}

private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) {
        return provider2 == null;
    }
    return provider1.equals(provider2);
}

我在onCreate和onResume中调用了locationInit()函数。 我的清单中有以下权限。

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

1 个答案:

答案 0 :(得分:0)

按如下方式创建GPSTracker类。

import java.io.IOException;
import java.util.List;
import java.util.Locale;

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

    boolean canGetLocation = false;

    Location location;
    double latitude;
    double longitude;

    //The minimum distance to change updates in metters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 metters

    //The minimum time beetwen 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);
                        updateGPSCoordinates();
                    }
                }

                //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);
                            updateGPSCoordinates();
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            //e.printStackTrace();
            Log.e("Error : Location", "Impossible to connect to LocationManager", e);
        }

        return location;
    }

    public void updateGPSCoordinates()
    {
        if (location != null)
        {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }
    }

    /**
     * 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;
    }

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

        return longitude;
    }

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

    /**
     * Function to show settings alert dialog
     */
    public void showSettingsAlert()
    {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        //Setting Dialog Title
        alertDialog.setTitle("hi");

        //Setting Dialog Message
       alertDialog.setMessage("hello");

        //On Pressing Setting button
        alertDialog.setPositiveButton("ok", new DialogInterface.OnClickListener() 
        {   
            @Override
            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() 
        {   
            @Override
            public void onClick(DialogInterface dialog, int which) 
            {
                dialog.cancel();
            }
        });

        alertDialog.show();
    }

    /**
     * Get list of address by latitude and longitude
     * @return null or List<Address>
     */
    public List<Address> getGeocoderAddress(Context context)
    {
        if (location != null)
        {
            Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
            try 
            {
                List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
                return addresses;
            } 
            catch (IOException e) 
            {
                //e.printStackTrace();
                Log.e("Error : Geocoder", "Impossible to connect to Geocoder", e);
            }
        }

        return null;
    }

    /**
     * Try to get AddressLine
     * @return null or addressLine
     */
    public String getAddressLine(Context context)
    {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0)
        {
            Address address = addresses.get(0);
            String addressLine = address.getAddressLine(0);

            return addressLine;
        }
        else
        {
            return null;
        }
    }

    /**
     * Try to get Locality
     * @return null or locality
     */
    public String getLocality(Context context)
    {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0)
        {
            Address address = addresses.get(0);
            String locality = address.getLocality();

            return locality;
        }
        else
        {
            return null;
        }
    }

    /**
     * Try to get Postal Code
     * @return null or postalCode
     */
    public String getPostalCode(Context context)
    {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0)
        {
            Address address = addresses.get(0);
            String postalCode = address.getPostalCode();

            return postalCode;
        }
        else
        {
            return null;
        }
    }

    /**
     * Try to get CountryName
     * @return null or postalCode
     */
    public String getCountryName(Context context)
    {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0)
        {
            Address address = addresses.get(0);
            String countryName = address.getCountryName();

            return countryName;
        }
        else
        {
            return null;
        }
    }

    @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 intent) 
    {
        return null;
    }
}

并在您的活动中添加这段代码。并查看log cat。

GPSTracker gpsTracker = new GPSTracker(this);

        if (gpsTracker.canGetLocation())
        {
            String stringLatitude = String.valueOf(gpsTracker.latitude);
            textview = (TextView)findViewById(R.id.latitude);
            textview.setText(stringLatitude);

            String stringLongitude = String.valueOf(gpsTracker.longitude);
            textview = (TextView)findViewById(R.id.longitude);
            textview.setText(stringLongitude);

           /* String country = gpsTracker.getCountryName(this);
            textview = (TextView)findViewById(R.id.country);
            textview.setText(country);

            String city = gpsTracker.getLocality(this);
            textview = (TextView)findViewById(R.id.fieldcity);
            textview.setText(city);

            String postalCode = gpsTracker.getPostalCode(this);
            textview = (TextView)findViewById(R.id.postaladdress);
            textview.setText(postalCode);

            String addressLine = gpsTracker.getAddressLine(this);
            textview = (TextView)findViewById(R.id.address);
            textview.setText(addressLine);*/
        }
        else
        {
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings
          //  gpsTracker.showSettingsAlert();
            Toast.makeText(getApplicationContext(), "Please Enable GPS/WIFI to access.", Toast.LENGTH_SHORT).show();
        }
    }

    }