android 离线定位吗,android – 让位置离线

只需使用此代码.确保用户未在其位置设置中选择仅限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)方法将为每个位置更新调用.

权限:

对于低于棒棒糖的版本以及marshmallow和更高版本使用运行时权限的清单文件添加以上权限.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值