我希望在离线时获取当前locatoin的经度和纬度值,并将当前位置保存到其数据库中。当移动数据和wifi关闭但GPS开启时,是否可以获得设备的经度和纬度?
答案 0 :(得分:10)
只需使用此代码即可。确保用户未在其位置设置中选择仅限wifi或仅选择网络。它必须是高精度或仅限GPS。这段代码将起作用。
public class Location extends AppCompatActivity {
LocationManager locationManager;
Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
mContext=this;
locationManager=(LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,
2000,
10, locationListenerGPS);
isLocationEnabled();
}
LocationListener locationListenerGPS=new LocationListener() {
@Override
public void onLocationChanged(android.location.Location location) {
double latitude=location.getLatitude();
double longitude=location.getLongitude();
String msg="New Latitude: "+latitude + "New Longitude: "+longitude;
Toast.makeText(mContext,msg,Toast.LENGTH_LONG).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
protected void onResume(){
super.onResume();
isLocationEnabled();
}
private void isLocationEnabled() {
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
AlertDialog.Builder alertDialog=new AlertDialog.Builder(mContext);
alertDialog.setTitle("Enable Location");
alertDialog.setMessage("Your locations setting is not enabled. Please enabled it in settings menu.");
alertDialog.setPositiveButton("Location Settings", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
AlertDialog alert=alertDialog.create();
alert.show();
}
else{
AlertDialog.Builder alertDialog=new AlertDialog.Builder(mContext);
alertDialog.setTitle("Confirm Location");
alertDialog.setMessage("Your Location is enabled, please enjoy");
alertDialog.setNegativeButton("Back to interface",new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
AlertDialog alert=alertDialog.create();
alert.show();
}
}
}
requestLocationUpdates方法的参数如下:
provider:我们要注册的提供者的名称。 minTime:位置更新之间的最小时间间隔(以毫秒为单位)。 minDistance:位置更新之间的最小距离(以米为单位)。 listener:一个LocationListener,它的onLocationChanged(Location)方法将为每个位置更新调用。
权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
为低于棒棒糖的版本添加以上权限,以及为marshmallow及更高版本添加运行时权限。