0

获取当前位置的代码如下:

final LocationManager manager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener listener=new LocationListener() {

    @Override
    public void onLocationChanged(Location location) {

        manager.removeUpdates(this);
        Toast.makeText(MainActivity.this, "2", Toast.LENGTH_LONG).show();
        if (location!=null) {
                                doSomeAction();
        }
        else {
            Toast.makeText(MainActivity.this, LOCATION_IS_NULL_MESSAGE, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
        manager.removeUpdates(this);
        String newProvider=provider.equals(LocationManager.GPS_PROVIDER) ? LocationManager.NETWORK_PROVIDER : null; 
        if (newProvider==null) {
            Toast.makeText(MainActivity.this, LOCATION_PROVIDERS_ARE_DISABLED_MESSAGE, Toast.LENGTH_LONG).show();
        }
        else {
            manager.requestLocationUpdates(newProvider, 0, 0, this);
        }
    }

    @Override
    public void onProviderEnabled(String provider) {}

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

};
String provider=manager.isProviderEnabled(LocationManager.GPS_PROVIDER) ? LocationManager.GPS_PROVIDER : 
    LocationManager.NETWORK_PROVIDER;
Location location=manager.getLastKnownLocation(provider);
if (location!=null) {
                doSomeAction();
}
else {
    Toast.makeText(this, "1", Toast.LENGTH_LONG).show();
    manager.requestLocationUpdates(provider, 0, 0, listener);
}

我每次看到吐司“1”,但我从未见过“2”吐司,因此我的位置没有更新。请告诉我,我需要获取当前位置 - 如何解决我的问题?我使用网络位置提供商。

4

2 回答 2

0

你真的附上了听众吗?如果没有附加监听器,它的代码是无用的,但此外 afaik:如果 LocationManager 没有附加监听器,它将不会更新任何位置。

于 2013-01-06T12:48:19.363 回答
0

试试这样:

public class Locato extends Activity implements LocationListener {

LocationManager locman;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.idlayout);
locman = (LocatonManager) getSystemService(Context.LOCATION_SERVICE);

}

 public void onStatusChanged(String pr, int s, Bundle a) {}

 @Override
    public void onProviderDisabled(String provider) {
       Log.d("MyApp", "Provider disabled : " + provider);
    }

    @Override
    public void onProviderEnabled(String provider) {
Log.d("MyApp", "Provider enabled : " + provider);
}

 @Override
    public void onLocationChanged(Location location) {
// do something
    }

您还必须向清单添加权限:访问粗略位置和访问精细位置

于 2013-01-06T13:31:41.217 回答