1

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..

  • Possible duplicate of [Request Location Permissions from a service Android M](http://stackoverflow.com/questions/33867088/request-location-permissions-from-a-service-android-m) – Komal12 Mar 15 '17 at 02:53
  • @user2025187 it doesnt gives the solution... – AlbusAllDay Mar 15 '17 at 11:07

1 Answers1

0

The method onConnected() is never called because you need to call it by using the method 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.


For example in your code you need to include: 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.

Effie
  • 11
  • 4
  • I put apiclient.connect() in the createLoginDialog() and it don't call the permission.. – AlbusAllDay Mar 15 '17 at 11:26
  • hmm you called `apiClient.connect()` **after** the initialization _(`apiClient = new GoogleApiClient.Builder(....)`)_ and didn't work? – Effie Mar 15 '17 at 11:59