位置问题

时间:2010-11-27 12:01:10

标签: android

大家好我刚接触到android并且我有一个小问题,如果有人可以帮助我,我真的很感激

首先我试图显示所有可用的位置提供商及其无法工作和第二次,当我运行它我没有从最好的可用提供商获得任何位置信息(我有我的wifi和网络提供商) 提前谢谢

package com.paad.whereami;

import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;

public class WhereAmI extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    LocationManager locationManager;
    String context = Context.LOCATION_SERVICE;
    locationManager = (LocationManager)getSystemService(context);
    boolean enabledOnly = true;
    List<String> providers = locationManager.getProviders(enabledOnly);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setSpeedRequired(true);
    String provider = locationManager.getBestProvider(criteria, true);   

      Location location = locationManager.getLastKnownLocation(provider);
    updateWithNewLocation(location);

    locationManager.requestLocationUpdates(provider, 2000, 1,
                                           locationListener);
  }


  private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
      updateWithNewLocation(location);
    }

    public void onProviderDisabled(String provider){
      updateWithNewLocation(null);
    }



 public void onProviderEnabled(String provider){ }
    public void onStatusChanged(String provider, int status,
                                Bundle extras){ }
  };

  private void updateWithNewLocation(Location location) {
    String latLongString;
    TextView myLocationText;
    myLocationText = (TextView)findViewById(R.id.myLocationText);

    String addressString = "No address found";

    if (location != null) {
      double lat = location.getLatitude();
      double lng = location.getLongitude();
      latLongString = "Lat:" + lat + "\nLong:" + lng;

      double latitude = location.getLatitude();
      double longitude = location.getLongitude();
      Geocoder gc = new Geocoder(this, Locale.getDefault());
      try {
        List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
        StringBuilder sb = new StringBuilder();
        if (addresses.size() > 0) {
          Address address = addresses.get(0);

          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());
        }
        addressString = sb.toString();
      } catch (IOException e) {}
    } else {
      latLongString = "No location found";
    }
    myLocationText.setText("Your Current Position is:\n" +
                            latLongString + "\n" + addressString);
  }
}

2 个答案:

答案 0 :(得分:2)

之前我也遇到过同样的问题,经过大量的搜索......来到解决方案并通过以下代码可以获得设备的即时位置...实际上我们不能让gps立即响应所以我们可以拥有我们的位置在细胞塔或wifi的基础上。因此,请让其中一个人获得您设备的即时位置..

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

            FindLocation(this);
        }


        public void FindLocation(Context context) {

            locationManager = (LocationManager) context
                    .getSystemService(Context.LOCATION_SERVICE);

            gps_enabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            network_enabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (network_enabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, 0, 0,
                        locationListenerNetwork);
                Log.i("@@@@@@@@@@ Network provider is enabled", "Network Provider");
            } else {
                Toast.makeText(LeopardScreen.this,
                        "Network provider is not enabled", 2000);
            }

            if (gps_enabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, 0, 0, locationListenerGPS);
                Log.i("@@@@@@@@@@ GPS provider is enabled", "GPS Provider");
            } else {
                Toast.makeText(LeopardScreen.this, "GPS provider is not enabled",
                        2000);
            }

            if(!network_enabled && !gps_enabled) {
                currentLocation = getMyLastKnownLocation();
                currentLatitude = currentLocation.getLatitude();
                currentLongitude = currentLocation.getLongitude();

                Log.i("@@@@@@@@ Both location provider disabled",
                        "getMylastKnownLocation = "+String.valueOf(currentLatitude)
                        + " : " + String.valueOf(currentLongitude));
                Toast.makeText(LeopardScreen.this,"LastKnownLocation\n"+String.valueOf(currentLatitude) + "\n"
                                + String.valueOf(currentLongitude), 3000).show();
                Intent intent = new Intent(LeopardScreen.this, mainActivity.class);
                startActivity(intent);
            }

        }

        LocationListener locationListenerNetwork = new LocationListener() {
            public void onLocationChanged(Location location) {
                updateLocation(location);
                handler.removeCallbacks(runnable);
                Log.i("@@@@@@@@ Inside FindLocation", "Inside FindLocation");
                Toast.makeText(
                        LeopardScreen.this,"Network Location \n"+
                        String.valueOf(currentLatitude) + "\n"
                                + String.valueOf(currentLongitude), 5000).show();

            }

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

            }

            public void onProviderEnabled(String provider) {
            }

            public void onProviderDisabled(String provider) {
            }

        };

        LocationListener locationListenerGPS = new LocationListener() {

            @Override
            public void onLocationChanged(Location location) {
                updateLocation(location);

                Log.i("@@@@@@@@@@ Inside onLocationChangedGPS", String
                        .valueOf(currentLatitude)
                        + " : " + String.valueOf(currentLongitude));

                Toast.makeText(
                        LeopardScreen.this,
                        "GPS Location \n" + String.valueOf(currentLatitude) + "\n"
                                + String.valueOf(currentLongitude), 5000).show();

            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProviderEnabled(String provider) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProviderDisabled(String provider) {
                // TODO Auto-generated method stub

            }

        };

        public Location getMyLastKnownLocation () {


                Location locNetwrok = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                Location locGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if(locNetwrok != null)
                    return locNetwrok;
                else if(locGPS != null)
                    return locGPS;

                return null;
        }

        void updateLocation(Location location) {
            currentLocation = location;
            currentLatitude = currentLocation.getLatitude();
            currentLongitude = currentLocation.getLongitude();

            Log.i("@@@@@@@@ Inside LeopardScreen locationChanged",
                    "locationChanged");

        }

不要忘记添加Menifeast

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

答案 1 :(得分:0)

使用以下课程获取位置。

package com.example.location;

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;

public class GPSTracker extends Service implements LocationListener{

private Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;

Location location;
double latitude,longitude;

LocationManager locationManager;
AlertDialogManager am = new AlertDialogManager();
public GPSTracker(Context context){
    this.context = context;
    getLocation();
}
private Location getLocation() {
    // TODO Auto-generated method stub
    try{
        locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);

        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);


        if (!isGPSEnabled && !isNetworkEnabled){

        } else {
            this.canGetLocation = true;

            if (isNetworkEnabled){

                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 3, this);

                if (locationManager != null){
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null){
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }

            if (isGPSEnabled){
                if (location == null){
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 3, this);
                    if (locationManager != null){
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null){
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            } else {
                showAlertDialog();
            }
        }
    }catch(Exception e){
        e.printStackTrace();
    }
    return location;
}


public void showAlertDialog(){
    am.showAlertDialog(GPSTracker.this, "GPS Setting", "Gps is not enabled. Do you want to enabled it ?", false);
}
public double getLatitude(){
    if (location != null){
        latitude = location.getLatitude();
    }

    return latitude;
}

public double getLongitude(){
    if (location != null){
        longitude = location.getLongitude();
    }

    return longitude;
}

public boolean canGetLocation(){
    return this.canGetLocation;
}
@Override
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub
    if (location != null){
        this.location = location;
    }
}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

 }

并在下面的主要活动中创建此类的对象。

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

不要忘记取得Manifest的许可。

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