获取当前位置有以下代码:
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”吐司,因此我的位置不会更新。请告诉我,我需要获取当前位置 - 如何解决我的问题?我使用网络位置提供商。
答案 0 :(得分:0)
你真的附上了听众吗?如果没有附加监听器,它的代码就没用了,但是还有afaik:如果LocationManager没有连接监听器,它将不会更新任何位置。
答案 1 :(得分: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
}
您还必须为清单添加权限:访问粗略位置和访问精确位置