在 android 后手动启动计时器
Start a timer manually in android
我需要使用计时器在特定时间间隔检查更新。检查当前位置。但是,我需要在获得用户的当前位置后启动计时器。因此,我需要手动启动计时器。有什么办法可以根据这个检查来启动定时器的定时任务吗?
您不能使用timer
获取位置更新。已经有一种获取用户当前位置更新的方法。
您应该调用 requestLocationUpdates()
方法来获取 lastKnownLocation
的更新。
方法就像,
requestLocationUpdates(String networkProvider, int timeInMillis, int distanceInMeters, this);
其中 String networkProvider
可以是 LocationManager.NETWORK_PROVIDER
或 LocationManager.GPS_PROVIDER
你应该像这样使用它,
LocationManager mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 100, this);
这将在 1000 毫秒和 100 米后获得最后已知位置更新。
并获取经纬度,
Location location;
if (mLocMgr != null) {
location = mLocMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
System.out.println(latitude+" "+longitude);
}
}
请参阅 documentation
中的 位置管理器
我需要使用计时器在特定时间间隔检查更新。检查当前位置。但是,我需要在获得用户的当前位置后启动计时器。因此,我需要手动启动计时器。有什么办法可以根据这个检查来启动定时器的定时任务吗?
您不能使用timer
获取位置更新。已经有一种获取用户当前位置更新的方法。
您应该调用 requestLocationUpdates()
方法来获取 lastKnownLocation
的更新。
方法就像,
requestLocationUpdates(String networkProvider, int timeInMillis, int distanceInMeters, this);
其中 String networkProvider
可以是 LocationManager.NETWORK_PROVIDER
或 LocationManager.GPS_PROVIDER
你应该像这样使用它,
LocationManager mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 100, this);
这将在 1000 毫秒和 100 米后获得最后已知位置更新。
并获取经纬度,
Location location;
if (mLocMgr != null) {
location = mLocMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
System.out.println(latitude+" "+longitude);
}
}
请参阅 documentation
中的 位置管理器