问题
I am trying to open System default Messaging activity when clicking on a button. Here is my code:
smsUri = Uri.parse("tel:" + teacherPhone2);
Intent intent = new Intent(Intent.ACTION_VIEW, smsUri);
intent.putExtra("address", teacherPhone);
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);
It works fine below MarshMallow. But in MarshMallow the app crashes when clicking that button. I have set the user-permission and also requested send sms permission. Can anyone tell me why this happens?
回答1:
Check runtime permission before sending sms:
if (Build.VERSION.SDK_INT >= 23) {
int checkCallPhonePermission = ContextCompat.checkSelfPermission(RegistrationActivity.this,Manifest.permission.SEND_SMS);
if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(RegistrationActivity.this,new String[]{Manifest.permission.SEND_SMS},SEND_SMS);
return;
}else{
sendSms(mobile);
}
} else {
sendSms(mobile);
}
回答2:
1. Add SEND_SMS
permission in manifest
<uses-permission android:name="android.permission.SEND_SMS"/>
2. Request permission if not granted, send sms otherwise
if (Build.VERSION.SDK_INT >= 23) {
int checkCallPhonePermission = ContextCompat.checkSelfPermission(RegistrationActivity.this,Manifest.permission.SEND_SMS);
if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(RegistrationActivity.this,new String[]{Manifest.permission.SEND_SMS},SEND_SMS);
return;
} else{
sendSms(mobile);
}
} else {
sendSms(mobile);
}
3. Override onActivityResult in order to send sms after permission is granted
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
int checkCallPhonePermission = ContextCompat.checkSelfPermission(RegistrationActivity.this,Manifest.permission.SEND_SMS);
if(checkCallPhonePermission == PackageManager.PERMISSION_GRANTED){
sendSms(mobile);
}
}
回答3:
The reason may be in MarshMallow we can turn off and on permissions for particular app. So check for permissions turned on or off before sending SMS.
回答4:
String[] PERMISSIONS = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_SMS, Manifest.permission.CAMERA};
if(!hasPermissions(this, PERMISSIONS)){
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}
public static boolean hasPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
try this code
来源:https://stackoverflow.com/questions/43782762/sms-does-not-send-in-marshmallow