谷歌地图Android权限被拒绝
我面临谷歌地图认证不一致的问题,当我运行我的应用程序时,它会连接并完美工作,但当我再次运行它时,它不会连接并抛出权限拒绝错误。此问题持续了很长时间,幸运的是它再次恢复连接。我试着检查我的谷歌api密钥,它看起来很好,因为有时应用程序会成功地进行身份验证 下面是我的代码:谷歌地图Android权限被拒绝,android,google-maps,Android,Google Maps,我面临谷歌地图认证不一致的问题,当我运行我的应用程序时,它会连接并完美工作,但当我再次运行它时,它不会连接并抛出权限拒绝错误。此问题持续了很长时间,幸运的是它再次恢复连接。我试着检查我的谷歌api密钥,它看起来很好,因为有时应用程序会成功地进行身份验证 下面是我的代码: public class PlacesAutoCompleteActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCal
public class PlacesAutoCompleteActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
View.OnClickListener, OnMapReadyCallback,
LocationListener {
protected GoogleApiClient mGoogleApiClient;
private boolean executeOnStart = false;
LocationRequest mLocationRequest;
private static final LatLngBounds BOUNDS_INDIA = new LatLngBounds(
new LatLng(-0, 0), new LatLng(0, 0));
public GoogleMap mMap;
Location mLastLocation;
Marker mCurrLocationMarker;
private String mapAddress = null;
private ImageView imageView;
private Button checkAvailability;
private StringBuilder sb = null;
private EditText mAutocompleteView;
private Geocoder geocoder;
private MarkerOptions markerOptions;
private LatLng latLng;
private boolean availabilityCheck = false;
private Marker marker;
private RecyclerView mRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
private PlacesAutoCompleteAdapter mAutoCompleteAdapter;
PlacesAutoCompleteAdapter.PlaceAutocomplete item;
String featureName, locality, countryName;
String placeId;
ImageView delete;
SupportMapFragment mapFragment;
private boolean allowEditTextChangeListener = true; // disable google maps autocomplete when user clicks on map to avoid fetching location of chosen place
private LatLng pos;
static boolean invalidLocation = false; // this value confirms whether we are able to deliver to users location
private LinearLayout linearLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
buildGoogleApiClient();
setContentView(R.layout.activity_search);
mAutocompleteView = (EditText) findViewById(R.id.autocomplete_places);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(PlacesAutoCompleteActivity.this);
linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
geocoder = new Geocoder(this, Locale.getDefault());
markerOptions = new MarkerOptions();
buildGoogleApiClient();
delete = (ImageView) findViewById(R.id.cross);
mAutoCompleteAdapter = new PlacesAutoCompleteAdapter(this, R.layout.searchview_adapter,
mGoogleApiClient, BOUNDS_INDIA, null);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mLinearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mRecyclerView.setAdapter(mAutoCompleteAdapter);
// mRecyclerView.setLayoutFrozen(true);
delete.setOnClickListener(this);
if (allowEditTextChangeListener) {
Log.d("allowEditTextChangz1",allowEditTextChangeListener + "");
mAutocompleteView.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
Log.d("allowEditTextChangz1","jo");
if (!s.toString().equals("") && mGoogleApiClient.isConnected()) {
Log.d("allowEditTextChangzQ",s.toString());
mAutoCompleteAdapter.getFilter().filter(s.toString());
} else if (!mGoogleApiClient.isConnected()) {
checkAvailability.setEnabled(false);
checkAvailability.setAlpha(0.3f);
Toast.makeText(getApplicationContext(), Constants.API_NOT_CONNECTED, Toast.LENGTH_SHORT).show();
Log.e(Constants.PlacesTag, Constants.API_NOT_CONNECTED);
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
}
mRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
item = mAutoCompleteAdapter.getItem(position);
placeId = String.valueOf(item.placeId);
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, placeId);
placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
@Override
public void onResult(PlaceBuffer places) {
if (places.getCount() == 1) {
mAutoCompleteAdapter.clear();
mAutocompleteView.setText("");
String country = "";
try {
List<Address> addresses = geocoder.getFromLocation(places.get(0).getLatLng().latitude,
places.get(0).getLatLng().longitude, 1);
sb = new StringBuilder();
if (addresses.size() > 0) {
android.location.Address address = addresses.get(0);
featureName = address.getFeatureName();
locality = address.getLocality();
countryName = address.getCountryName();
Log.d("featureName ", featureName + "||" +
locality +"||" + countryName);
if (featureName == null) {
mapAddress = address.getLocality() + " " + address.getCountryName();
} else if (locality == null) {
mapAddress = address.getFeatureName() + ", " + address.getCountryName();
} else if (countryName == null) {
mapAddress = address.getFeatureName() + ", " + address.getLocality();
} else {
mapAddress = address.getFeatureName() + ", " + address.getLocality() + " " + address.getCountryName();
country = address.getCountryName();
Log.d("counttryy", "sasa"+country);
}
}
Log.d("mpaddress", "kaka "+mapAddress + "||" + country);
} catch (IOException e) {
e.printStackTrace();
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(places.get(0).getLatLng()) // Sets the center of the map to Mountain View
.zoom(12) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(30) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
marker.remove(); // remove any marker from maponclick or maponlonclick
marker = mMap.addMarker(new MarkerOptions().position(places.get(0).getLatLng())
.title("My Location"));
mMap.setTrafficEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
if (countryName.toLowerCase().equals("kenya")){
availabilityCheck = true;
checkAvailability.setEnabled(true);
confirmPosition();
} else {
}
} else {
Toast.makeText(getApplicationContext(), Constants.SOMETHING_WENT_WRONG, Toast.LENGTH_SHORT).show();
}
}
});
}
})
);
imageView = (ImageView) findViewById(R.id.maps_close);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("close", "close");
if (mAutoCompleteAdapter.getItemCount() != 0){
mAutoCompleteAdapter.clear();
}
mAutocompleteView.setText("");
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//mMap.getUiSettings().setZoomControlsEnabled(true);
final Double lat = location.getLatitude();
final Double lng = location.getLongitude();
Log.d("LATLANGz", lat + "|" + lng);
latLng = new LatLng(lat, lng);
markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Positionn");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
marker = mMap.addMarker(markerOptions);
//move map camera_main
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
sb = new StringBuilder();
if (addresses.size() > 0) {
android.location.Address address = addresses.get(0);
String featureName = address.getFeatureName();
String locality = address.getLocality();
String countryName = address.getCountryName();
System.out.println("featureName " + featureName + "||" + locality +"||" + countryName);
if (featureName == null) {
mapAddress = address.getLocality() + " " + address.getCountryName();
} else if (locality == null) {
mapAddress = address.getFeatureName() + ", " + address.getCountryName();
} else if (countryName == null) {
mapAddress = address.getFeatureName() + ", " + address.getLocality();
} else {
mapAddress = address.getFeatureName() + ", " + address.getLocality() + " " + address.getCountryName();
}
}
System.out.println("mpaddress " + mapAddress + "||" );
mAutocompleteView.setText(mapAddress);
} catch (IOException e) {
e.printStackTrace();
}
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener(){
@Override
public boolean onMyLocationButtonClick() {
// Toast.makeText(getApplicationContext(), "2> "+mapAddress + lat + lng, Toast.LENGTH_LONG).show();
return false;
}});
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnectionSuspended(int i) {
Log.v("Google API Callback", "Connection Suspended");
Log.v("Code", String.valueOf(i));
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.v("Google API Callback","Connection Failed");
Log.v("Error Code", String.valueOf(connectionResult.getErrorCode()));
Toast.makeText(this, Constants.API_NOT_CONNECTED, Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View v) {
if(v==delete){
mAutocompleteView.setText("");
}
}
@Override
public void onResume() {
super.onResume();
if (!mGoogleApiClient.isConnected() && !mGoogleApiClient.isConnecting()){
Log.v("Google API","Connecting");
mGoogleApiClient.connect();
}
}
@Override
public void onPause() {
super.onPause();
if(mGoogleApiClient.isConnected()){
Log.v("Google API","Dis-Connecting");
mGoogleApiClient.disconnect();
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Log.d("permission","permission");
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
Log.d("permission2","permission2");
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (mGoogleApiClient.isConnected()){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
// mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
@Override
public void onStart(){
super.onStart();
buildGoogleApiClient();
if (isNetworkAvailable() == true){
if (isLocationEnabled(getApplicationContext())){
// Toast.makeText(getApplicationContext(), "enabled", Toast.LENGTH_LONG).show();
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
} else{
Display.displaySnackbar(getApplicationContext(), linearLayout, "YOUR GPS IS CURRENTLY DISABLED");
showLocationDialog();
}
} else {
Display.displaySnackbar(getApplicationContext(), linearLayout, "YOU ARE CURRENTLY OFFLINE");
showInternetDialog();
}
}
public void showInternetDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Please turn on mobile network or Wi-Fi in Settings.")
.setTitle("WIFI Disabled")
.setCancelable(false)
.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(i);
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
PlacesAutoCompleteActivity.this.finish();
}
}
);
AlertDialog alert = builder.create();
alert.show();
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public static boolean isLocationEnabled(Context context) {
int locationMode = 0;
String locationProviders;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return false;
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
}else{
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locationProviders);
}
}
public void showLocationDialog(){
executeOnStart = true;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.gps_not_found_message)
.setTitle(R.string.gps_not_found_title)
.setCancelable(false)
.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(i);
}
}
)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dg, int id) {
// dialog.dismiss();
// SignIn.dialog.dismiss();
PlacesAutoCompleteActivity.this.finish();
}
}
);
AlertDialog alert = builder.create();
alert.show();
}
}
公共类PlacesAutoCompleteActivity扩展了AppCompatiaActivity实现
GoogleAppClient.ConnectionCallbacks,
GoogleAppClient.OnConnectionFailedListener,
View.OnClickListener,OnMapReadyCallback,
位置侦听器{
受保护的GoogleapClient MGoogleapClient;
私有布尔值executeOnStart=false;
位置请求mLocationRequest;
私有静态最终LatLngBounds BOUNDS_INDIA=新LatLngBounds(
新LatLng(-0,0),新LatLng(0,0));
公共谷歌地图;
位置mLastLocation;
标记器mCurrLocationMarker;
私有字符串mapAddress=null;
私人影像视图;
私人按钮检查可用性;
私有StringBuilder sb=null;
私有EditText mAutocompleteView;
私人地理编码器;
私有标记选项标记选项;
私人车床;
private boolean availabilityCheck=false;
专用标记;
私人回收视图mRecyclerView;
私人线路布局经理;
私人配售完成适配器mAutoCompleteAdapter;
PlacesAutoCompleteAdapter.PlaceAutocomplete项;
字符串特征名称、位置、国家名称;
字符串placeId;
图像视图删除;
SupportMapFragment-mapFragment;
private boolean alloweditttextchangelister=true;//当用户单击地图时禁用google地图自动完成,以避免获取所选位置
私人停车位;
静态布尔值invalidLocation=false;//此值确认我们是否能够传递到用户位置
私人线性布局线性布局;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
buildGoogleAppClient();
setContentView(R.layout.activity\u search);
mAutocompleteView=(EditText)findViewById(R.id.autocomplete_位置);
mapFragment=(SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map);
getMapAsync(PlacesAutoCompleteActivity.this);
linearLayout=(linearLayout)findViewById(R.id.linear\U布局);
geocoder=新的geocoder(这个,Locale.getDefault());
markerOptions=新的markerOptions();
buildGoogleAppClient();
delete=(ImageView)findviewbyd(R.id.cross);
mAutoCompleteAdapter=新位置SautoCompleteAdapter(此,R.layout.searchview\u适配器,
mGoogleApiClient,印度边界,空);
mRecyclerView=(RecyclerView)findViewById(R.id.RecyclerView);
mLinearLayoutManager=新的LinearLayoutManager(此);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mRecyclerView.setAdapter(mAutoCompleteAdapter);
//mRecyclerView.setLayoutFrozed(true);
delete.setOnClickListener(此);
如果(AllowEdittXtChangeListener){
Log.d(“AllowEdittXtChangZ1”,AllowEdittXtChangeListener+”);
mAutocompleteView.addTextChangedListener(新的TextWatcher(){
public void onTextChanged(字符序列,int start,int before,
整数计数){
Log.d(“允许的”第Z1条“,”第jo条”);
如果(!s.toString().equals(“”&&mGoogleApiClient.isConnected()){
Log.d(“alloweditttextchangzq”,s.toString());
mAutoCompleteAdapter.getFilter().filter(s.toString());
}如果(!mgoogleapClient.isConnected()),则为else{
checkAvailability.setEnabled(false);
检查可用性。setAlpha(0.3f);
Toast.makeText(getApplicationContext(),Constants.API_未连接,Toast.LENGTH_SHORT).show();
Log.e(Constants.PlacesTag,Constants.API\u未连接);
}
}
更改前的公共无效(字符序列、整数开始、整数计数、,
整数后){
}
公共无效后文本已更改(可编辑){
}
});
}
mRecyclerView.addonimtouchlistener(
新的RecyclerItemClickListener(这个,新的RecyclerItemClickListener.OnItemClickListener(){
@凌驾
公共虚线单击(视图,int位置){
item=mAutoCompleteAdapter.getItem(位置);
placeId=String.valueOf(item.placeId);
Pendingreult placeResult=Places.GeoDataApi
.getPlaceById(mGoogleApiClient,placeId);
setResultCallback(新的ResultCallback(){
@凌驾
公共void onResult(PlaceBuffer places){
if(places.getCount()==1){
mAutoCompleteAdapter.clear();
mAutocompleteView.setText(“”);
字符串country=“”;
试一试{
列表地址=geocoder.getFromLocation(places.get(0).getLatLng().latitude,
places.get(0.getLatLng().longitude,1);
sb=新的StringBuilder();
如果(地址.size()>0){