在android中使用gps无法获取位置

在android中使用gps无法获取位置,android,gps,Android,Gps,我正在尝试使用gps服务获取位置的示例代码。bt不获取位置。 下面是我的代码- public class MainActivity extends Activity implements LocationListener{ Location mLocation; LocationManager mManager; LocationListener mlistener; Geocoder mcoder; Context context; Te

我正在尝试使用gps服务获取位置的示例代码。bt不获取位置。 下面是我的代码-

   public class MainActivity extends Activity implements LocationListener{

    Location mLocation;
    LocationManager mManager;
    LocationListener mlistener;
    Geocoder mcoder;
    Context context;
    TextView txtLat;
    String lat;
    String provider;
    protected String latitude,longitude; 
    protected boolean gps_enabled,network_enabled;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    mManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    txtLat = (TextView) findViewById(R.id.tv);
    }

    public void getMyLocation(){

            String addressString = "";

        final Geocoder gc = new Geocoder(this, Locale.getDefault());

        try
        {
            final List<Address> addresses = gc.getFromLocation(18.5203, 73.8567, 4);
            final StringBuilder sb = new StringBuilder();
            System.out.println("location..."+sb);
            if ( addresses.size() > 0 )
            {
                final 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 ( final IOException e )
        {
        }

    txtLat.setText("Your Current Position is:\n" +
             "\n" + addressString);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public void onLocationChanged(Location location) {
    getMyLocation();
}

@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

}

 }
public类MainActivity扩展活动实现LocationListener{
位置;
地点经理;
位置监听器;
地理编码器;
语境;
TextView-txtLat;
弦拉特;
字符串提供者;
保护字符串纬度、经度;
受保护布尔值gps_启用,网络_启用;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mManager=(LocationManager)getSystemService(Context.LOCATION\u服务);
mManager.RequestLocationUpdate(LocationManager.GPS_提供程序,0,0,此);
txtLat=(TextView)findViewById(R.id.tv);
}
public void getMyLocation(){
字符串地址字符串=”;
final Geocoder gc=新的Geocoder(这个,Locale.getDefault());
尝试
{
最终列表地址=gc.getFromLocation(18.5203,73.8567,4);
最终StringBuilder sb=新StringBuilder();
系统输出打印项次(“位置…”+sb);
如果(地址.size()>0)
{
最终地址=地址。获取(0);
对于(int i=0;i
尝试以这种方式实施gps

gps = new GPSTracker(MainActivity .this);
                 // check if GPS enabled    
                if(gps.canGetLocation()){

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();
                    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();
                }
现在创建GPSTracker.java

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

}
更新:

如果您必须使用
纬度
经度
要求位置名称,则

Geocoder gcd = new Geocoder(context, Locale.getDefault());
List<Address> addresses = gcd.getFromLocation(lat, lng, 1);
if (addresses.size() > 0) 
    System.out.println(addresses.get(0).getLocality());
Geocoder gcd=new Geocoder(context,Locale.getDefault());
列表地址=gcd.getFromLocation(lat,lng,1);
如果(地址.size()>0)
System.out.println(addresses.get(0.getLocality());
在这段代码中,我刚刚添加了您所在位置的toast消息,现在您可以根据需要使用

如果您需要任何帮助,请发表评论


快乐编码。

您的代码只需要一些小改动

  • 您必须实现侦听器的所有方法,以了解提供程序是否可用,设备中是否内置了任何提供程序,以及您是否仍然可以期望位置更新
  • getMyLocation()
    中,使用硬编码的纬度和经度调用
    Geocoder.getFromLocation()
    。这是为了调试吗
  • 然后是一个新创建的空StringBuilder的
    System.println()
    。如果您想打印出一些内容,最好使用
    Log.d()
  • 最后,如果其他一切正常,但在文本视图中仍然没有地址,那么尝试
    Toast
    地址。它出错的可能性较小,但当信息在一秒钟后消失时,你需要盯着屏幕

我的猜测是,你的模拟器没有配置GPS,或者你没有得到更新——要么是因为没有卫星,要么是因为你没有等待足够长的时间进行卫星连接。

输出是什么?例如,TextView上有什么?只是显示您当前的位置是:考虑在
getMyLocation()
中的“if”条件中添加一个日志。这样可以确保调用方法并检索地址。还要检查
addresses.size()
是否为零。我需要位置。我正在获取经纬度。使用经纬度我想要好的地名。获取此警告。我正在使用emulator。09-10 10:23:39.196:W/System.err(1494):java.io.IOException:服务不可用09-10 10:23:39.196:W/System.err(1494):在android.location.Geocoder.getFromLocation(Geocoder.java:117)@yuva你能检查一下设备吗?