【发布时间】:2013-05-29 07:32:30
【问题描述】:
我是 android 开发新手,我了解 android 活动生命周期。请看以下代码。
public class MyTest extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cont = getApplicationContext();
final MyLocation my_loc = new MyLocation ();
my_loc.initialize(cont);
myMethod();
}
Public void myMethod()
{
//here when I retrieve the values, it always shows 0.0.
}
}
public class MyLocation implements LocationListener {
public double user_lat;
public double user_lng;
private LocationManager locationManager;
private Context ctx;
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
user_lat = location.getLatitude();
user_lng = location.getLongitude();
//here i save the values for constands to use in myMethod
}
}
public void initialize(Context context) {
this.ctx = context;
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
}
}
为什么我无法在同一个活动中初始化 GPS 并检索经纬度值?
【问题讨论】:
-
当你移动你的设备一小段距离然后自动触发 onChangeLocation() 方法。并根据这个新位置获得经纬度。
-
你能详细说明什么是行不通的吗? (例外,没有回调,...)并且:您是否在 Manifest 文件中声明了适当的权限?
-
@sunil 和 Patrick 一旦我启动我的活动,GPS 应该初始化并获取 GPS 坐标,因为我将在 myMethod 中使用它们。我不能随身携带设备来触发 onLocationChanged 方法来获取正确的值吗?应用程序在几秒钟内加载。为什么我使用我的代码得到 0.0 的 long 和 lat?
-
lastKnownLoaction() 有一个方法。此方法返回存储在设备中的最新更新。如果它没有更新,则返回 0.0 。在这种情况下,呼叫位置更改以移动您的设备。现在您的设备存储最新的纬度和经度。然后你的 lastKnownLoaction 给出纬度和经度。希望你理解
-
在初始化类时尝试使用这个方法:locationManager.requestLocationUpdates(provider,60000,10,listener)。
标签: android