我正在尝试创建一个应用程序,它将获取手机的当前位置并将其显示为地图上的标记。我正在使用具有不同类型的Android版本的设备。它在棒棒糖中运行良好并显示了我当前的位置,但它不适用于其他版本,它只显示地图。它没有向我提供错误消息,所以我不确定发生了什么。
这是我用来获取当前位置的代码:
{{1}}
谢谢!
答案 0 :(得分:0)
尝试this回答。有时getLastKnownLocation()返回null。所以你还要添加位置更新请求..
答案 1 :(得分:0)
对于Marshmallow及以上,您必须明确要求用户许可。您可以使用此代码来实现它
private void RequestAllPermissions() {
String[] PERMISSIONS = {Manifest.permission.CAMERA, Manifest.permission.RECEIVE_SMS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET, Manifest.permission.CALL_PHONE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.WRITE_CONTACTS};
if (!hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, REQUESTCODE_PERMISSION_ALL);
} else
}
public static boolean hasPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUESTCODE_PERMISSION_ALL: {
boolean allpermissiongranted = true;
if (grantResults.length > 0) {
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
allpermissiongranted = false;
break;
}
}
} else
allpermissiongranted = false;
if (allpermissiongranted) {
//do task
} else {
new SweetAlertDialog(mContext, SweetAlertDialog.WARNING_TYPE)
.setTitleText("Permission Not Granted")
.setContentText("Kindly grant all requested permission to proceed.")
.setConfirmText("Request")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.dismissWithAnimation();
RequestAllPermissions();
}
})
.setCancelText("Exit")
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.dismissWithAnimation();
finish();
}
})
.show();
}
}