您的位置:首页 > 移动开发 > Android开发

android发送短信并监听插入收件箱的方法

2015-09-15 18:29 405 查看
package com.sms.service;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.*;
import android.net.Uri;
import android.telephony.SmsManager;
import org.apache.commons.lang3.RandomUtils;

import java.util.List;

/**
* Created by Administrator on 2015/8/18.
*/
public class SmsService {
//移动,每小时70,一天500
//
//电信 每小时200,一天1000
private static final SmsService instance = new SmsService();
public static final SmsService getInstance() {
return instance;
}
public int send(final String phone, String message, final Context context) {
if (message != null && phone != null) {
SmsManager sms = SmsManager.getDefault();
final List<String> texts = sms.divideMessage(message);

PendingIntent sendIntent = null;
PendingIntent backIntent = null;
//处理返回的发送状态
String SENT_SMS_ACTION = "SENT_SMS_ACTION";
Intent sentIntent = new Intent(SENT_SMS_ACTION);
for(int i=1;i<texts.size()+1;i++) {
try {
sentIntent.putExtra(i + "", texts.get(i - 1));
}catch (Exception e){
e.printStackTrace();
}
}
sendIntent = PendingIntent.getBroadcast(context, phone.hashCode(), sentIntent, 0);
//下标
final StringBuffer index = new StringBuffer("0");
context.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context _context, Intent intent) {
index.append(Integer.parseInt(index.substring(index.length() - 1))+1);
switch (getResultCode()) {
case Activity.RESULT_OK:
String text = intent.getStringExtra(index.substring(index.length() - 1));
if (text == null){
break;
}
ContentValues values = new ContentValues();
values.put("date", System.currentTimeMillis());
values.put("read", 0);
values.put("type", 2);
values.put("address", phone);
values.put("body", text);
System.out.println("text:"+text);
context.getContentResolver().insert(Uri.parse("content://sms/sent"), values);
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
break;
}
if (Integer.parseInt(index.substring(index.length() - 1)) == texts.size()){
context.unregisterReceiver(this);
}
}
}, new IntentFilter(SENT_SMS_ACTION));

for(int i=0;i<texts.size();i++) {
try {
//发送短信
sms.sendTextMessage(phone, null, texts.get(i), sendIntent, backIntent);
Thread.sleep(RandomUtils.nextLong(100, 600));
} catch (Exception e) {
e.printStackTrace();
}
}
return texts.size();
}
return 0;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: