Android Service中使用SMSManager发送短信时应用崩溃问题求助
Hey there! Let's figure out why your app crashes when trying to send location via SMSManager. Since you’ve already got location fetching working and added permissions, let’s walk through the most likely issues and fixes step by step:
1. Missing Dynamic Permission Request
Even if you’ve added <uses-permission android:name="android.permission.SEND_SMS"/> in your AndroidManifest.xml, SEND_SMS is a dangerous permission on Android 6.0 (API 23) and above. You can’t just declare it in the manifest—you need to ask the user for permission at runtime.
Here’s how to implement dynamic permission handling in your MainActivity:
private static final int REQUEST_SEND_SMS = 1; // Call this method before triggering SMS sending private void requestSmsPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, REQUEST_SEND_SMS); } else { // Permission already granted—proceed to send SMS sendLocationSms(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_SEND_SMS) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { sendLocationSms(); } else { Toast.makeText(this, "SMS permission is required to send location data", Toast.LENGTH_SHORT).show(); } } }
2. Incorrect SMSManager Usage
Common mistakes here include:
- Passing an invalid phone number (e.g., missing country code, empty string)
- Not handling
PendingIntentfor send/delivery status (some devices require these) - Null
SMSManagerinstance (rare, but possible on custom ROMs)
Here’s a safe way to use SMSManager (you can call this from your BroadcastService or MainActivity, just ensure you have a valid context):
private void sendLocationSms(String phoneNumber, String locationText) { SMSManager smsManager = SMSManager.getDefault(); if (smsManager == null) { Toast.makeText(getApplicationContext(), "Failed to access SMS service", Toast.LENGTH_SHORT).show(); return; } // Create PendingIntents to track send/delivery status (required on some devices) PendingIntent sentIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("SMS_SENT_ACTION"), PendingIntent.FLAG_IMMUTABLE); PendingIntent deliveryIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("SMS_DELIVERED_ACTION"), PendingIntent.FLAG_IMMUTABLE); try { smsManager.sendTextMessage(phoneNumber, null, locationText, sentIntent, deliveryIntent); Toast.makeText(getApplicationContext(), "Location sent successfully", Toast.LENGTH_SHORT).show(); } catch (IllegalArgumentException e) { Toast.makeText(getApplicationContext(), "Invalid phone number format", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } catch (SecurityException e) { Toast.makeText(getApplicationContext(), "SMS permission not granted", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } }
3. Check Your Crash Log for Exact Errors
The crash log will tell you exactly what’s wrong—look for keywords like:
SecurityException: Definitely a permission issue (you missed dynamic request)IllegalArgumentException: Invalid phone number or empty messageNullPointerException: A variable (like phone number or location data) is null when you try to use it
For example, if your log says java.lang.SecurityException: SEND_SMS permission denied, go back and verify your dynamic permission code is running before you call sendTextMessage.
4. Service Context & Background Restrictions
If you’re sending SMS from a Service, make sure:
- You’re using a valid context (use
getApplicationContext()instead of an activity context that might be destroyed) - On Android 8.0+ (API 26), background services have restrictions—if your service is running in the background, you might need to use a
ForegroundServiceto avoid being killed (though this is more likely to cause the service to stop than an immediate crash)
内容的提问来源于stack exchange,提问作者Prakaash M

