要在Android中创建位置请求对话框并在回调中获取位置,可以按照以下步骤进行操作:
import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_LOCATION_PERMISSION = 1;
private Button locationButton;
private TextView locationText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationButton = findViewById(R.id.location_button);
locationText = findViewById(R.id.location_text);
locationButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION_PERMISSION);
} else {
getCurrentLocation();
}
}
});
}
private void getCurrentLocation() {
// 获取位置逻辑
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_LOCATION_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getCurrentLocation();
} else {
showLocationPermissionDeniedDialog();
}
}
}
private void showLocationPermissionDeniedDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("位置权限被拒绝");
builder.setMessage("需要位置权限以获取您的位置信息,请授予该权限。");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
}
以上代码示例中,点击位置获取按钮时,会首先检查是否有位置权限。如果没有权限,则会弹出对话框请求权限。如果用户授予了权限,将会执行获取位置的逻辑。如果权限被拒绝,则会显示一个对话框提示用户授予权限。
注意:在运行代码之前,请确保已经在AndroidManifest.xml文件中添加了位置权限。