问题描述
我正在尝试向 ArrayList
中的所有联系号码发送短信。我的代码如下:
try{
SmsManager sms = SmsManager.getDefault();
if (customarray.size() != 0) {
Log.d("contact",String.valueOf(customarray)); //shows all the contact numbers
for (int i = 0; i < customarray.size(); i++) {
Log.d("contact",String.valueOf(customarray.get(i))); //shows each of the contact numbers
sms.sendTextMessage(customarray.get(i),null,string,null);
Toast.makeText(contacts.this,"Your sms has been sent to "+customarray.get(i),Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printstacktrace();
}
<uses-permission android:name="android.permission.SEND_SMS" />
此处,customarray
包含所有联系电话。即使 Toast 出现了,“您的短信已发送至...”,但短信从未发送。为什么?
解决方法
按照@Joachim Sauer 的建议,使用 PendingIntent
有效:
try{
SmsManager sms = SmsManager.getDefault();
Intent intent=new Intent(getApplicationContext(),contacts.class);
PendingIntent pi= PendingIntent.getActivity(getApplicationContext(),intent,0);
if (customarray.size() != 0) {
Log.d("contact",String.valueOf(customarray)); //shows all the contact numbers
for (int i = 0; i < customarray.size(); i++) {
Log.d("contact",String.valueOf(customarray.get(i))); //shows each of the contact numbers
sms.sendTextMessage(customarray.get(i),null,string,pi,null);
Toast.makeText(contacts.this,"Your sms has been sent to "+customarray.get(i),Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}