Android 中如何获取当前位置?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (66)

我使用下面的代码来获取当前位置,但我没有获取当前位置。

package com.ram.currentlocation;

import android.app.Activity;    
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;

public class Location_Gps extends Activity
{

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      /* Use the LocationManager class to obtain GPS locations */
      LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

      LocationListener mlocListener = new MyLocationListener();
      mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
    }

    /* Class My Location Listener */
    public class MyLocationListener implements LocationListener
    {

      @Override
      public void onLocationChanged(Location loc)
      {

        loc.getLatitude();
        loc.getLongitude();

        String Text = "My current location is: " +
        "Latitud = " + loc.getLatitude() +
        "Longitud = " + loc.getLongitude();

        Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
      }

      @Override
      public void onProviderDisabled(String provider)
      {
        Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
      }

      @Override
      public void onProviderEnabled(String provider)
      {
        Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
      }

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

      }
    }
}

PS:我在manifest文件中使用以下权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_CORSE_LOCATION"/>
提问于
用户回答回答于

你的清单文件中有错误。正确的是:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
用户回答回答于

你必须将位置修复发送到模拟器,因为模拟器是您需要提供位置修复的软件:

发送loc loc之后,你可以使用 :

Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

扫码关注云+社区