Android SmsManager 发送短信
SmsManager可以在后台发送短信,无需用户操作,开发者就用这个SmsManager功能在后台偷偷给SP发短信,导致用户话费被扣。必须添加android.permission.SEND_SMS权限。
<uses-permission android:name="android.permission.SEND_SMS" />
如果短信内容过长,可以使用SmsManager.divideMessage(String text)方法自动拆分成一个ArrayList数组,再根据数组长度循环发送。
用sendMultipartTextMessage(String destinationAddress, string scAddress, ArrayList<String> parts, ArrayList<PendingIntent> sentIntents, ArrayList<PendingIntent> deliveryIntents)方法发送。
参数分别为号码,短信服务中心号码(null 即可),短信内容,短信发送结果广播PendingIntent,短信到达广播。
下面写一个demo查移动话费余额,贴上代码:
package com.dimos.sendmessage; import java.util.ArrayList; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.telephony.SmsManager; public class SendMessageActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); SendReceiver receiver=new SendReceiver(); IntentFilter filter=new IntentFilter(); filter.addAction(SendReceiver.ACTION); registerReceiver(receiver,filter); //必须先注册广播接收器,否则接收不到发送结果 SmsManager smsManager = SmsManager.getDefault(); Intent intent = new Intent(); intent.setAction(SendReceiver.ACTION); ArrayList<String> divideMessage = smsManager.divideMessage("ye"); PendingIntent sentIntent = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT); ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>(); sentIntents.add(sentIntent); try { smsManager.sendMultipartTextMessage("10086", null, divideMessage, sentIntents, null); } catch (Exception e) { e.printStackTrace(); } } }
接收器:
package com.dimos.sendmessage; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class SendReceiver extends BroadcastReceiver { public static final String ACTION = "action.send.sms"; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION.equals(action)) { int resultCode = getResultCode(); if (resultCode == Activity.RESULT_OK) { // 发送成功 System.out.println("发送成功!"); } else { // 发送失败 System.out.println("发送失败!"); } } } }