我正在尝试请求一个具有位置权限的对话框来激活它,但我不知道该怎么做。如果你能帮助我,谢谢。
这是我的完整代码:
public class DialogEntrar extends BlurDialogFragment implements GoogleApiClient.OnConnectionFailedListener,
GoogleApiClient.ConnectionCallbacks,
LocationListener {
private static final String TAG = DialogEntrar.class.getSimpleName();
private SignInButton btnSignInGlg;
static GoogleApiClient apiClient;
private static final int RC_SIGN_IN = 1001;
private static final String LOGTAG = "android-localizacion";
private static final int PETICION_PERMISO_LOCALIZACION = 101;
private static final int PETICION_CONFIG_UBICACION = 201;
private ProgressDialog progressDialog;
private View v;
//Datos de usuario entrado
String personName;
String personGivenName;
String personFamilyName;
String personEmail;
String personId;
Uri personPhoto;
public DialogEntrar() {
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return createLoginDialogo();
}
@Override
public void onDestroy() {
super.onDestroy();
apiClient.stopAutoManage((FragmentActivity) getActivity());
apiClient.disconnect();
}
//Lo que sale una vez apretas el boton de jugar
private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage(getResources().getString(R.string.Entrando));
progressDialog.setIndeterminate(true);
}
progressDialog.show();
}
private void hideProgressDialog() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.hide();
}
}
public AlertDialog createLoginDialogo() {
//ROLLO DE LA API DE GOOGLE SIGN IN
GoogleSignInOptions gso =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
apiClient = new GoogleApiClient.Builder(getActivity())
.enableAutoManage((FragmentActivity) getActivity(), this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso).addApi(LocationServices.API)
.build();
//INFLADOR DIALOGO
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
v = inflater.inflate(R.layout.activity_dialog_entrar, null);
builder.setView(v);
//BOTON Desconectarse
Button desconectarse = (Button) v.findViewById(R.id.btnDialogDesconnect);
desconectarse.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
if(apiClient.isConnected()) {
Log.i(TAG, String.valueOf(apiClient.isConnected()));
desconnectUser();
Toast.makeText(getActivity(), getResources().getString(R.string.Desconectar), Toast.LENGTH_SHORT).show();
}else if(!apiClient.isConnected()){
FragmentManager fragmentManager = getFragmentManager();
DialogFragment newFragment = new OneActionDesconectado();
newFragment.show(fragmentManager, "TAG");
}
}
}
);
//BOTON CREAR NUEVO USUARIO
Button btnCrearNewUSU = (Button)v.findViewById(R.id.btnDiaUsuNew);
btnCrearNewUSU.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Uri uri = Uri.parse("https://accounts.google.com/SignUp?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&hl=es"); // missing 'http://' will cause crashed
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
btnSignInGlg = (SignInButton)v.findViewById(R.id.sign_in_button);
btnSignInGlg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showProgressDialog();
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(apiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
hideProgressDialog();
}
});
return builder.create();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
private void handleSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
//Usuario logueado --> Mostramos sus datos
GoogleSignInAccount acct = result.getSignInAccount();
if(acct.getDisplayName() != null){
personName = acct.getDisplayName();
}
personGivenName = acct.getGivenName();
personFamilyName = acct.getFamilyName();
personEmail = acct.getEmail();
personId = acct.getId();
personPhoto = acct.getPhotoUrl();
Log.i(TAG, personName);
Log.i(TAG, personGivenName);
Log.i(TAG, personFamilyName);
Log.i(TAG, personEmail);
Log.i(TAG, personId);
Log.i(TAG, String.valueOf(personPhoto));
Intent intent = new Intent(getActivity(), InicioJuegoActivity.class);
intent.putExtra("personName", personName);
intent.putExtra("personGivenName", personGivenName);
intent.putExtra("personFamilyName", personFamilyName);
intent.putExtra("personEmail", personEmail);
intent.putExtra("personId", personId);
intent.putExtra("personPhoto", String.valueOf(personPhoto));
startActivity(intent);
getActivity().finish();
Toast.makeText(getActivity(), "Conectado",Toast.LENGTH_SHORT).show();
hideProgressDialog();
} else {
//Usuario no logueado --> Lo mostramos como "Desconectado"
Toast.makeText(getActivity(), "Desconectado",Toast.LENGTH_SHORT).show();
}
}
public void desconnectUser(){
Auth.GoogleSignInApi.signOut(apiClient).setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
if(apiClient.isConnected()) {
Toast.makeText(getActivity(), getResources().getString(R.string.Desconectar), Toast.LENGTH_SHORT).show();
}else if(apiClient == null){
FragmentManager fragmentManager = getFragmentManager();
DialogFragment newFragment = new OneActionDesconectado();
newFragment.show(fragmentManager, "TAG");
}
}
});
}
//PERMISSIONS
@Override
public void onConnected(@Nullable Bundle bundle) {
//Conectado correctamente a Google Play Services
if (ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PETICION_PERMISO_LOCALIZACION);
} else {
Location lastLocation =
LocationServices.FusedLocationApi.getLastLocation(apiClient);
updateUI(lastLocation);
}
}
@Override
public void onConnectionSuspended(int i) {
//Se ha interrumpido la conexión con Google Play Services
Log.e(LOGTAG, "Se ha interrumpido la conexión con Google Play Services");
}
private void updateUI(Location loc) {
if (loc != null) {
Log.e(LOGTAG, "Latitud: " + String.valueOf(loc.getLatitude()) + " Longitud: " + String.valueOf(loc.getLongitude()));
} else {
Log.e(LOGTAG, "Latitud: (desconocida) Longitud: (desconocida)");
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == PETICION_PERMISO_LOCALIZACION) {
if (grantResults.length == 1
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Permiso concedido
@SuppressWarnings("MissingPermission")
Location lastLocation =
LocationServices.FusedLocationApi.getLastLocation(apiClient);
updateUI(lastLocation);
} else {
//Permiso denegado:
//Deberíamos deshabilitar toda la funcionalidad relativa a la localización.
Log.e(LOGTAG, "Permiso denegado");
}
}
}
@Override
public void onLocationChanged(Location location) {
Log.i(LOGTAG, "Recibida nueva ubicación!");
//Mostramos la nueva ubicación recibida
updateUI(location);
}
只是不显示对话框,我不知道为什么..如果你能帮助我,谢谢..
最佳答案
方法 onConnected() 永远不会被调用,因为您需要使用方法 connect() 来调用它。 .
public abstract void connect ()
Connects the client to Google Play services. This method returns immediately, and connects to the service in the background. If the connection is successful, onConnected(Bundle) is called and enqueued items are executed. On a failure, onConnectionFailed(ConnectionResult) is called.
If the client is already connected or connecting, this method does nothing.
例如,在您的代码中,您需要包含:apiClient.connect();
Start a manually managed connection:
In an activity context the best practice is to call connect() in your activity's onStart() method and disconnect() in your activity's onStop() method.
关于java - 尝试在 Android Studio 中请求具有位置权限的对话框,但它不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42799694/