如何将LatLng发送至ProximityIntentReceiver?修改代码支持经纬度输入
Got it, let's break down your two Android proximity alert needs step by step:
1. Sending LatLng Data to ProximityIntentReceiver
To pass a LatLng to your ProximityIntentReceiver, bundle the latitude and longitude as extras in the broadcast Intent you use to create the PendingIntent. Here's how to do it:
Step 1: Attach LatLng to the Intent
When setting up your proximity alert intent, add the LatLng coordinates as extra values:
// Create the base intent for your receiver Intent intent = new Intent("com.example.a57050358.testboat.util.proximityintentreceiver"); // Add LatLng data as extras intent.putExtra("TARGET_LAT", latLng.latitude); intent.putExtra("TARGET_LNG", latLng.longitude); // Use FLAG_UPDATE_CURRENT to ensure updated extras are passed to existing PendingIntents PendingIntent proximityIntent = PendingIntent.getBroadcast(getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Step 2: Retrieve LatLng in the Receiver
In your ProximityIntentReceiver class, extract the extras from the incoming intent to get the LatLng:
public class ProximityIntentReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // Pull the coordinates from extras double lat = intent.getDoubleExtra("TARGET_LAT", 0.0); double lng = intent.getDoubleExtra("TARGET_LNG", 0.0); LatLng receivedLatLng = new LatLng(lat, lng); // Use the received LatLng (e.g., show a notification or trigger an action) Toast.makeText(context, "Entered zone near: " + receivedLatLng, Toast.LENGTH_SHORT).show(); } }
2. Modify GeocoderTask to Accept Direct LatLng Input
Your original task uses a location name to fetch coordinates—let's rework it to take a LatLng directly, skip name-based geocoding, and set up the proximity alert using the provided coordinates. Here's the revised code:
private class GeocoderTask extends AsyncTask<LatLng, Void, Address> { @Override protected Address doInBackground(LatLng... latLngs) { // Get the input LatLng from parameters LatLng targetLatLng = latLngs[0]; Geocoder geocoder = new Geocoder(getContext()); Address address = null; try { // Fetch address details from the provided coordinates (limit to 1 result) List<Address> addresses = geocoder.getFromLocation( targetLatLng.latitude, targetLatLng.longitude, 1 ); if (addresses != null && !addresses.isEmpty()) { address = addresses.get(0); } } catch (IOException e) { e.printStackTrace(); // Optional: Handle geocoding failures (e.g., no network access) } return address; } @SuppressLint("MissingPermission") @Override protected void onPostExecute(Address address) { LatLng targetLatLng = null; // Get the target coordinates (either from the address or original input) if (address != null) { targetLatLng = new LatLng(address.getLatitude(), address.getLongitude()); } else { Toast.makeText(getContext(), "Failed to fetch address details", Toast.LENGTH_SHORT).show(); return; } // Set up marker and circle for the map String addressText = address != null ? String.format("%s, %s", address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "", address.getCountryName()) : "Custom Location"; MarkerOptions markerOptions = new MarkerOptions() .position(targetLatLng) .title(addressText); CircleOptions circleOptions = new CircleOptions() .center(targetLatLng) .radius(Rd); // Create proximity intent with LatLng extras (as we did in part 1) Intent intent = new Intent("com.example.a57050358.testboat.util.proximityintentreceiver"); intent.putExtra("TARGET_LAT", targetLatLng.latitude); intent.putExtra("TARGET_LNG", targetLatLng.longitude); PendingIntent proximityIntent = PendingIntent.getBroadcast( getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT ); // Add the proximity alert using direct coordinates locationManager.addProximityAlert( targetLatLng.latitude, targetLatLng.longitude, Rd, -1, proximityIntent ); // Register the receiver (note: consider registering this in onCreate() to avoid duplicate receivers) IntentFilter filter = new IntentFilter("com.example.a57050358.testboat.util.proximityintentreceiver"); getContext().registerReceiver(new ProximityIntentReceiver(), filter); Toast.makeText(getContext(), "Proximity alert set successfully", Toast.LENGTH_SHORT).show(); } }
Key Updates:
- Changed the AsyncTask generic type to
<LatLng, Void, Address>to accept a LatLng input and return a single address. - Replaced
getFromLocationName()withgetFromLocation()to fetch address details directly from coordinates. - Added logic to pass the target LatLng to the
ProximityIntentReceivervia intent extras. - Simplified the address handling since we're only fetching one result for the given coordinates.
How to Use the Revised Task:
Call it with a LatLng instead of a location name:
// Example: Set alert for the Eiffel Tower LatLng eiffelTower = new LatLng(48.8584, 2.2945); new GeocoderTask().execute(eiffelTower);
内容的提问来源于stack exchange,提问作者PPZ

