I send SMS using code below:
Intent intent开发者_JAVA百科 = new Intent(Intent.ACTION_VIEW, Uri.parse("smsto:" + phoneNumber));
intent.putExtra("address", phoneNumber);
intent.putExtra("sms_body", messageBody);
intent.setType("vnd.android-dir/mms-sms");
context.startActivity(intent);
I added both Uri with smsto: and address String extra to Intent. It works on most devices, but on some - it doesn't. One of the devices is SE XPERIA Mini. What else can be added when sending SMS to make sure recipient is set in SMS App?
I looked into Intent source and it seems that setting intent type removes data and setting data removes type. This is what I've found:
public Intent setData(Uri data) {
mData = data;
mType = null;
return this;
}
public Intent setType(String type) {
mData = null;
mType = type;
return this;
}
public Intent setDataAndType(Uri data, String type) {
mData = data;
mType = type;
return this;
}
So setting type overrides my data provided in Uri.parse("smsto:" + phoneNumber). I also tried using setDataAndType, but then android just can't find the right Intent to start for such combination... So this is the final solution:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra("address", phoneNumber);
intent.putExtra("sms_body", messageBody);
intent.setData(Uri.parse("smsto:" + phoneNumber));
context.startActivity(intent);
It seems to work on different devices what I can test on. I hope this will be helpful for anyone who faces the same problem.
Cheers!
精彩评论