Android卸载重装后,开关触发位置获取及Google Places API列餐厅失效问题
Hey there, let's figure out why your location + nearby restaurants feature stopped working after reinstalling the app. Since it ran fine before, the issue is almost certainly tied to permission resets, API key configuration, or missing error handling post-reinstall. Let's break down the fixes step by step:
When you uninstall and reinstall an app, all previously granted permissions get wiped. Your current switch listener might be trying to fetch location immediately without checking if permissions are still granted first. Here's how to fix that:
// First, register an ActivityResultLauncher in your Activity/Fragment private ActivityResultLauncher<String[]> permissionLauncher; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // ... other setup code permissionLauncher = registerForActivityResult( new ActivityResultContracts.RequestMultiplePermissions(), permissions -> { boolean fineLocationGranted = permissions.getOrDefault(Manifest.permission.ACCESS_FINE_LOCATION, false); boolean coarseLocationGranted = permissions.getOrDefault(Manifest.permission.ACCESS_COARSE_LOCATION, false); if (fineLocationGranted || coarseLocationGranted) { // Permissions granted, start location updates MyLocationManager.startLocationUpdates(); } else { // Permissions denied, uncheck the switch and notify user switchCompat.setChecked(false); Toast.makeText(this, "Location permissions are required to find nearby restaurants", Toast.LENGTH_LONG).show(); } } ); // Now update your switch listener switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { // Check permissions before proceeding if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Request permissions permissionLauncher.launch(new String[]{ Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION }); return; } // Permissions already granted, start location fetch MyLocationManager.startLocationUpdates(); } else { // Stop location updates when switch is turned off MyLocationManager.stopLocationUpdates(); } } }); }
Reinstalls don't usually break API keys, but it's worth double-checking if your key has strict restrictions (like package name/SHA-1 binding):
- Head to Google Cloud Console and confirm the Places API is still enabled for your project.
- Check your API key's restrictions: Ensure it's tied to your app's exact package name and includes both debug and release SHA-1 fingerprints (if you're testing with a debug build).
- Make sure your
AndroidManifest.xmlhas the correct meta-data entry:
<meta-data android:name="com.google.android.geo.API_KEY" android:value="YOUR_ACTUAL_API_KEY"/>
Users might have disabled location services since your last install. Add a check to prompt them to turn it on:
private boolean isLocationServiceEnabled() { LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } // Call this before starting location updates if (!isLocationServiceEnabled()) { switchCompat.setChecked(false); Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); Toast.makeText(this, "Please enable location services to use this feature", Toast.LENGTH_LONG).show(); return; }
gotLocation() Your gotLocation() method might be missing error handling for null locations or Places API failures. Here's a robust version:
private void gotLocation(Location location) { if (location == null) { switchCompat.setChecked(false); Toast.makeText(this, "Failed to retrieve your current location", Toast.LENGTH_SHORT).show(); return; } // Initialize Places API and fetch nearby restaurants Places.initialize(getApplicationContext(), "YOUR_API_KEY"); PlacesClient placesClient = Places.createClient(this); // Request only the fields we need to reduce data usage List<Place.Field> placeFields = Arrays.asList( Place.Field.NAME, Place.Field.ADDRESS, Place.Field.RATING ); FindCurrentPlaceRequest request = FindCurrentPlaceRequest.newInstance(placeFields); placesClient.findCurrentPlace(request) .addOnSuccessListener(response -> { // Process the restaurant list List<PlaceLikelihood> placeLikelihoods = response.getPlaceLikelihoods(); if (placeLikelihoods.isEmpty()) { Toast.makeText(this, "No nearby restaurants found", Toast.LENGTH_SHORT).show(); return; } // Update your UI with the results here for (PlaceLikelihood likelihood : placeLikelihoods) { Place place = likelihood.getPlace(); Log.d("NearbyPlaces", "Restaurant: " + place.getName() + " | " + place.getAddress()); } }) .addOnFailureListener(e -> { switchCompat.setChecked(false); Log.e("PlacesError", "Failed to fetch restaurants: " + e.getMessage()); Toast.makeText(this, "Error loading nearby restaurants", Toast.LENGTH_SHORT).show(); }); }
Sometimes residual cache from previous installs can cause odd behavior. Go to your device's Settings > Apps > [Your App] > Storage and tap "Clear Cache", then restart the app.
内容的提问来源于stack exchange,提问作者Houda Laabidi

