我正在尝试获取当前位置并将其LAt和LON发送到另一个班级。但是我的应用程序没有获得它显示最后位置的当前位置。请帮助我如何使用GPS获取当前位置和NETWORK提供商。
以下是代码:
public class location implements LocationListener
{
private LocationManager mgr;
private String best;
Location location;
public static double myLocationLatitude;
public static double myLocationLongitude;
public void locUpdate(Context context)
{
mgr = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
// criteria.setAccuracy(Criteria.ACCURACY_COARSE);
best = mgr.getBestProvider(criteria, true);
mgr.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER,0,0,this);
try{
Location location = mgr.getLastKnownLocation(best);
Intent i = new Intent();
i.setClass(context,sentsms.class);
i.putExtra("latitude", location.getLatitude());
i.putExtra("longitude", location.getLongitude());
i.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Launch the new activity and add the additional flags to the intent
context.getApplicationContext().startActivity(i);
}
catch(Exception e)
{
}
}
public void onLocationChanged(Location location) {
dumpLocation(location);
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
protected void onPause()
{
// super.onPause();
mgr.removeUpdates(this);
}
protected void onResume() {
// super.onResume();
mgr.requestLocationUpdates(best, 15000, 10, this);
}
private void dumpLocation(Location l) {
if (l != null){
myLocationLatitude = l.getLatitude();
myLocationLongitude = l.getLongitude();
}
}
}
答案 0 :(得分:0)
来自getLastKnownLocation()
的文档:
返回指示上一个已知位置的数据的位置 从给定的提供者处获得的修复。
这可以在不启动提供程序的情况下完成。请注意这一点 位置可能已过时,例如,如果设备已转动 关闭并搬到另一个地方。
如果当前禁用了提供程序,则返回null。
这意味着getLastKnownLocation()
将根据Location
的上次修复检索Provider
。如果您想要更新Locations
,请使用Location
onLocationChanged()
答案 1 :(得分:0)
请尝试这种方式
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
if (provider != null) {
location = locationManager.getLastKnownLocation(provider);
// locationManager.requestLocationUpdates(provider, 1000*60*60,
// 1000, this);
// update only in 1 hour and 1 km of distance
locationManager.requestLocationUpdates(provider, 100, 1, this);
}