Выбор места немедленно закрывается - PullRequest
1 голос
/ 05 марта 2019

мой PlacePicker закрывается, когда я его открываю, он остается открытым в течение примерно 3 секунд, я вижу местоположение и могу его переместить, но он закрывается, я уже попробовал все, уже активировал API в консоли Google, я изменилключ, это не дает никакой ошибки в logcat, и ни одна из вкладок RUN не поможет мне!

МОЙ МАНИФЕСТ ANDROID

 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>



    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyCD70mX9tljEfiDiLaCdHEUNMvq40AJDyI"/>
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity android:name=".activity.TelefoneActivity" />
        <activity android:name=".activity.CadastrarActivity" />
        <activity android:name=".activity.MainActivity" />
        <activity android:name=".activity.PassageiroActivity" />

        <uses-library android:name="org.apache.http.legacy" android:required="false"/>


        <meta-data
            android:name="com.facebook.sdk.App.Application"
            android:value="@string/facebook_app_id" />
        <!-- Facebook API Key -->
        <meta-data
            tools:replace="android:value"
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />


        <activity
            android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
        </activity>

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/. 
        -->
        <activity
            android:name=".activity.SplashActivity"
            android:theme="@style/AppCompat.TelaCheia">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

ДЕЯТЕЛЬНОСТЬ, ГДЕ ВЫПОЛНЯЕТСЯ ПЕРЕКЛЮЧАТЕЛЬ

import static android.Manifest.permission.ACCESS_FINE_LOCATION;

public class PassageiroActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {


    int PLACE_PICKER_REQUEST = 1;
    private String placeId;
    TextView btnChamarMoto;
    /**
     * Mapa da aplicação
     */
    private GoogleMap mMap;

    /**
     * Responsável por disponibilizar a localização do smartphone
     */
    private GoogleApiClient mGoogleApiClient;

    /**
     * Guarda a ultima posição do smartphone.
     */
    private Location mLastLocation;



    private TextInputEditText editMeuLocal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_passageiro);
      SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
      mapFragment.getMapAsync(this);
      iniciaComponentes();
      placesApi();
      btnChamarMoto = (TextView) findViewById(R.id.btnChamarMoto);

      if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
          .addConnectionCallbacks(this) // Interface ConnectionCallbacks
          .addOnConnectionFailedListener(this) //Interface OnConnectionFailedListener
          .addApi(LocationServices.API) // Vamos a API do LocationServices
          .build();
      }
    }


    public void placePiker(View view) {

      PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
      try {

        try {
          startActivityForResult(builder.build(PassageiroActivity.this), PLACE_PICKER_REQUEST);
        } catch (GooglePlayServicesNotAvailableException e) {
          e.printStackTrace();
        }

      } catch (GooglePlayServicesRepairableException e) {
        e.printStackTrace();
      }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

      if (requestCode == PLACE_PICKER_REQUEST) {
        if (resultCode == RESULT_OK) {

          Place place = (Place) PlacePicker.getPlace(PassageiroActivity.this, data);
          btnChamarMoto.setText(place.getAddress());

        }
      }

    }
    protected void onStart() {
      mGoogleApiClient.connect();
      super.onStart();
    }

    protected void onStop() {
      mGoogleApiClient.disconnect();
      super.onStop();
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
      mMap = googleMap;
    }


    @Override
    public void onConnected(Bundle bundle) {

      if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
      }
      mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
      if (mLastLocation != null) {
        if (mMap != null) {
          // Criamos o LatLng através do Location
          final LatLng latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
          // Adicionamos um Marker com a posição...
          mMap.addMarker(new MarkerOptions().position(latLng).title("Minha Posição"));
          // Um zoom no mapa para a seua posição atual...
          mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18));

        }

      }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }


    //Place Api
    private void placesApi() {

      Places.initialize(getApplicationContext(), "AIzaSyDxFTRAaJ-FecUs8SZj6MBYwwzD447Nces");
      final PlacesClient placesClient = Places.createClient(this);
      AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
      getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
      autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));
      autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
          //
          // Double latitude = place.getLatLng().latitude;
          Log.i("Places", "Place: " + place.getName() + ", " + place.getId());
          placeId = place.getId();

        }

        @Override
        public void onError(Status status) {
          // TODO: Handle the error.
          Log.i("errorOccurred", "An error occurred: " + status);
        }


      });

    }

    private void meuLocal(PlacesClient placesClient) {
      List < Place.Field > placeFields = Arrays.asList(Place.Field.NAME);

      FindCurrentPlaceRequest request =
        FindCurrentPlaceRequest.builder(placeFields).build();

      if (ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        Task < FindCurrentPlaceResponse > placeResponse = placesClient.findCurrentPlace(request);
        placeResponse.addOnCompleteListener(task - > {
          if (task.isSuccessful()) {
            FindCurrentPlaceResponse response = task.getResult();
            for (PlaceLikelihood placeLikelihood: response.getPlaceLikelihoods()) {
              Log.i("likelihood", String.format("Place '%s' has likelihood: %f",
                placeLikelihood.getPlace().getName(),
                placeLikelihood.getLikelihood()));
              LatLng nome = placeLikelihood.getPlace().getLatLng();

              double latitude = nome.latitude;
              double longitude = nome.longitude;
              Toast.makeText(this, "latitude: " + latitude + "longitude: " + longitude, Toast.LENGTH_SHORT).show();
            }
          } else {
            Exception exception = task.getException();
            if (exception instanceof ApiException) {
              ApiException apiException = (ApiException) exception;
              Log.e("notFound", "Place not found: " + apiException.getStatusCode());
            }
          }
        });
      } else {

      }
    }

    private void verificaIdPlaces(PlacesClient placesClient) {

      List < Place.Field > placeFields = Arrays.asList(Place.Field.ID, Place.Field.NAME);

      FetchPlaceRequest request = FetchPlaceRequest.builder(placeId, placeFields).build();
      String nome = request.getPlaceId();

      placesClient.fetchPlace(request).addOnSuccessListener((response) - > {
        Place place = response.getPlace();
        Log.i("PlaceFOund", "Place found: " + place.getName() + "," + place.getLatLng());


      }).addOnFailureListener((exception) - > {
        if (exception instanceof ApiException) {
          ApiException apiException = (ApiException) exception;
          int statusCode = apiException.getStatusCode();
          // Handle error with given status code.
          Log.e("Place not found", "Place not found: " + exception.getMessage());
        }
      });
    }

    private void iniciaComponentes() {
      btnChamarMoto = findViewById(R.id.btnChamarMoto);

    }

1 Ответ

0 голосов
/ 30 мая 2019

Пожалуйста, проверьте ваш ключ API

Обратите внимание, что есть два ключа API, один для debug, а другой для release, поэтому убедитесь, что вы используете правильный ключ для правильной версии

...