简体   繁体   English

尝试在Android Studio中请求具有位置权限的对话框,但它不起作用

[英]Trying to request a dialog with the location permission in Android Studio but it doesn't work

I'm trying to request a dialog with the location permission to activate it, but I don't know how to do it exactly.. If you can help me, thanks. 我正在尝试请求一个具有位置权限的对话框来激活它,但我不知道该怎么做。如果你可以帮助我,谢谢。

This is my full code: 这是我的完整代码:

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);
}

It just, don't show the dialog and I don't know why.. If you can help me, thanks.. 它只是,不显示对话框,我不知道为什么..如果你可以帮助我,谢谢..

The method onConnected() is never called because you need to call it by using the method connect() . 永远不会调用onConnected()方法,因为您需要使用connect()方法调用它。

public abstract void connect () public abstract void connect()

Connects the client to Google Play services. 将客户端连接到Google Play服务。 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. 如果连接成功,则调用onConnected(Bundle)并执行入队项。 On a failure, onConnectionFailed(ConnectionResult) is called. 失败时,调用onConnectionFailed(ConnectionResult)。

If the client is already connected or connecting, this method does nothing. 如果客户端已连接或已连接,则此方法不执行任何操作。


For example in your code you need to include: apiClient.connect(); 例如,在您的代码中,您需要包括: 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. 在活动方面的最佳做法是调用connect()在您的活动的在onStart()方法,并断开()在您的活动的的onStop()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM