android发送短信,过滤短信,注册过滤信息
短信的发送
发送信息参数:1:号码 2:内容 3:条数 4:卡
1:判断短信号码是否合法,网络是否开通等操作
2:新建队列,将发送短信的任务填入队列,并统同时写入数据库(事务处理)
3:发送短信核心方法检测队列,如果队列不为空,则执行发短信的任务
4:每条短信发送指定的条数,成功则继续发送下一条,失败则再发送一次,失败次数超过三次放弃发送,无论短信发送成功与否,执行完则将其同步从数据库中删除,继续发送下一条,过程同上
5:若中途网络中断,断电或其他原因导致系统重启,系统开机后重新建立短信数据存放队列,将数据库中尚未完成的短信数据读出来,放入队列,继续执行4的操作
6:另有一个队列存放二次确认的回复短信信息,此队列不存数据库,系统重启将丢失数据,此队列大小不定,可增长,此队列的短信信息发送需在上一队列中的对应任务结束后执行,此队列优先级高于发短信的队列
短信的接收屏蔽
号码和内容屏蔽,符合条件则直接屏蔽
过滤信息数据直接从服务器获取,1:回复任意,匹配短信内容和相应的关键字,若匹配则直接回复任意2:回复指定(截取)直接截取指定字符串之间的内容回复(关键字由指定的规则或符号分割)3:答题,将短信内容发送至服务器,服务器将返回答案,将答案发送出去
注册
自己定义数据类型及存储规则,从服务器端接收数据,将相应数据放入手机终端服务器
实现:

main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/txtPhoneNo"/> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/edtPhoneNo"/> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/txtContent"/> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:minLines="3" android:id="@+id/edtContent"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/btnText" android:id="@+id/btnSend"/> </LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello World, SMSMessageActivity!</string> <string name="txtPhoneNo">请输入号码</string> <string name="txtContent">请输入短信内容</string> <string name="btnText">发送</string> <string name="app_name">短信应用</string> <string name="str_sms_sending">message content</string> <string name="str_sms_sent_success">短信发送成功!</string> <string name="str_sms_rec_success">send rec success !</string> <string name="str_sms_sent_failed">发送失败(普通错误)!</string> <string name="str_sms_sent_no_service_failed">发送失败(服务不可用)!</string> <string name="str_sms_sent_null_pdu_failed">发送失败(没有提供pdu)!</string> <string name="str_sms_rec_status_on_icc_read">接收且已读!</string> <string name="str_sms_rec_status_on_icc_sent">存储且已发送!</string> <string name="str_sms_rec_failed">send rec failed !</string> <string name="str_sms_sent_radio_off_failed">无线广播被明确地关闭,短信发送失败!</string> </resources>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="test.sms" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="4" /> <uses-permission android:name="android.permission.SEND_SMS"></uses-permission> <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission> <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="test.sms" android:label="test junit "></instrumentation> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:label="@string/app_name" android:name=".SMSMessageActivity" > <intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".SMSBroadcastReceiver"> <intent-filter android:priority="800"> <action android:name="android.provider.Telephony.SMS_RECEIVED"/> </intent-filter> <intent-filter android:priority="800"> <action android:name="android.intent.action.SENT_SMS_ACTION"/> </intent-filter> </receiver> <uses-library android:name="android.test.runner"/> </application> </manifest>
DBOpenHelper.java
package test.sms; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBOpenHelper extends SQLiteOpenHelper { public DBOpenHelper(Context context) { super(context, "smsmessagedb.db", null, 1); // TODO Auto-generated constructor stub } /** * 数据库每一次创建时被调用 */ @Override public void onCreate(SQLiteDatabase db) { StringBuffer sql=new StringBuffer(); sql.append("create table sms (smsid integer primary key autoincrement,phonenum verchar(12),content varchar(200),"); sql.append("card varchar(12),times integer,seconds integer,failuretimes integer)"); db.execSQL(sql.toString()); StringBuffer sql1=new StringBuffer(); sql1.append("create table filterbean (filterid integer primary key autoincrement,type integer,value varchar(400))"); db.execSQL(sql1.toString()); } /** * 更改数据库版本时被执行 */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
FilterBean.java
package test.sms; public class FilterBean { private int filterid; //过滤类型非为五种:1:content(内容)2:number(号码)3:answerwhatever(回复任意) //4:answersomething(回复某内容,截取)5:answerquestion(回答问题) private int type; private String value; public FilterBean(int type, String value) { this.type = type; this.value = value; } public FilterBean(int filterid, int type, String value) { this.filterid = filterid; this.type = type; this.value = value; } public int getFilterid() { return filterid; } public void setFilterid(int filterid) { this.filterid = filterid; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String toString(){ return "filterid="+this.filterid+", type="+this.type+", value="+this.value; } }
FilterService.java
package test.sms; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; /** * 短信过滤信息操作类 * */ public class FilterService { private DBOpenHelper dbOpenHelper; public FilterService(Context context) { this.dbOpenHelper = new DBOpenHelper(context); } /** * 添加记录 * @param person */ public void save(FilterBean fliterBean){ SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); StringBuffer sql = new StringBuffer(); sql.append("insert into filterbean(type,value) values(?,?)"); db.execSQL(sql.toString(),new Object[]{fliterBean.getType(),fliterBean.getValue()}); db.close(); } /** * 添加记录并返回新插入数据的id * @param person */ public FilterBean saveAndReturnId(FilterBean filterBean){ SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); StringBuffer sql = new StringBuffer(); sql.append("insert into filterbean(type,value) values(?,?)"); db.execSQL(sql.toString(),new Object[]{filterBean.getType(),filterBean.getValue()}); SQLiteDatabase db1 = dbOpenHelper.getReadableDatabase(); Cursor cursor = db1.rawQuery("select last_insert_rowid() from filterbean",null); int strid = 0; if(cursor.moveToFirst()){ strid = cursor.getInt(0); } db.close(); return find(strid); } /** * 删除记录 * @param id */ public void delete(Integer id){ SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.execSQL("delete from filterbean where filterid=?",new Object[]{id}); db.close(); } /** * 更新记录 * @param person */ public void update(FilterBean filterBean){ SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); StringBuffer sql = new StringBuffer(); sql.append("update filterbean set type=?,value=? where filterid=?"); db.execSQL(sql.toString(),new Object[]{filterBean.getType(),filterBean.getValue(),filterBean.getFilterid()}); db.close(); } /** * 查找记录 * @param id * @return person */ public FilterBean find(Integer id){ FilterBean filterBean = null; SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select *from filterbean where filterid=?", new String[]{id.toString()}); if(cursor.moveToFirst()){ int filterid = cursor.getInt(cursor.getColumnIndex("filterid")); int type = cursor.getInt(cursor.getColumnIndex("type")); String value = cursor.getString(cursor.getColumnIndex("value")); filterBean = new FilterBean(filterid,type,value); } cursor.close(); db.close(); return filterBean; } /** * 查找top记录 * @param id * @return person */ public FilterBean findTop(){ FilterBean filterBean = null; SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from filterbean limit 0,1 ",null); if(cursor.moveToFirst()){ int filterid = cursor.getInt(cursor.getColumnIndex("filterid")); int type = cursor.getInt(cursor.getColumnIndex("type")); String value = cursor.getString(cursor.getColumnIndex("value")); filterBean = new FilterBean(filterid,type,value); } cursor.close(); db.close(); return filterBean; } /** * 查找bottom记录 * @param id * @return person */ public FilterBean findBottom(){ FilterBean filterBean = null; long count = getCount(); SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from filterbean limit ?,? ",new String[]{String.valueOf(count-1),String.valueOf(1)}); if(cursor.moveToFirst()){ int filterid = cursor.getInt(cursor.getColumnIndex("filterid")); int type = cursor.getInt(cursor.getColumnIndex("type")); String value = cursor.getString(cursor.getColumnIndex("value")); filterBean = new FilterBean(filterid,type,value); } cursor.close(); db.close(); return filterBean; } /** * 分页 * @param offset 跳过多少条记录 * @param maxResult 每页获取多少条记录 * @return */ public List<FilterBean> getScrollData(int offset,int maxResult){ List<FilterBean> filterBeans = new ArrayList<FilterBean>(); SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select *from filterbean order by filterid asc limit ?,?", new String[]{String.valueOf(offset),String.valueOf(maxResult)}); while(cursor.moveToNext()){ int filterid = cursor.getInt(cursor.getColumnIndex("filterid")); int type = cursor.getInt(cursor.getColumnIndex("type")); String value = cursor.getString(cursor.getColumnIndex("value")); filterBeans.add(new FilterBean(filterid,type,value)); } cursor.close(); db.close(); return filterBeans; } /** * 获取所有数据 * @return */ public List<FilterBean> getAllData(){ List<FilterBean> filterBeans = new ArrayList<FilterBean>(); SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select *from filterbean", null); while(cursor.moveToNext()){ int filterid = cursor.getInt(cursor.getColumnIndex("filterid")); int type = cursor.getInt(cursor.getColumnIndex("type")); String value = cursor.getString(cursor.getColumnIndex("value")); filterBeans.add(new FilterBean(filterid,type,value)); } cursor.close(); db.close(); return filterBeans; } /** * 获取指定type数据 * @param typeStr * @return */ public List<FilterBean> getAllTypeData(String typeStr){ List<FilterBean> filterBeans = new ArrayList<FilterBean>(); SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select *from filterbean where type=?", new String[]{typeStr}); while(cursor.moveToNext()){ int filterid = cursor.getInt(cursor.getColumnIndex("filterid")); int type = cursor.getInt(cursor.getColumnIndex("type")); String value = cursor.getString(cursor.getColumnIndex("value")); filterBeans.add(new FilterBean(filterid,type,value)); } cursor.close(); db.close(); return filterBeans; } /** * 获取记录总数 * @return */ public long getCount(){ SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select count(*) from filterbean",null); cursor.moveToFirst(); long result = cursor.getLong(0); cursor.close(); db.close(); return result; } /** * 清空表 */ public void emptyTable(){ SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.execSQL("delete from filterbean"); //清除自增 db.execSQL("UPDATE sqlite_sequence SET seq = 0 WHERE name = 'filterbean'"); db.close(); } }
Sms.java
package test.sms; public class Sms { private Integer smsid; private String phonenum; private String content; private String card = "222222222"; private int times = 1;//次数 private long seconds = 5*1000;//时间隔暂定为5秒 标记标记标记标记标记标记标记标记标记标记标记标记标记标记 private int failuretimes;//发送失败次数 public Sms(String phonenum, String content){ this.phonenum = phonenum; this.content = content; } public Sms(String phonenum, String content,String card){ this.phonenum = phonenum; this.content = content; this.card = card; } public Sms(int smsid, String phonenum, String content){ this.smsid = smsid; this.phonenum = phonenum; this.content = content; } public Sms(String phonenum, String content,String card,int times){ this.phonenum = phonenum; this.content = content; this.card = card; this.times = times; } public Sms(String phonenum, String content,String card,int times,int seconds){ this.phonenum = phonenum; this.content = content; this.card = card; this.times = times; this.seconds = seconds; } public Sms(String phonenum, String content,String card,int times,int seconds,int failuretimes) { this.phonenum = phonenum; this.content = content; this.card = card; this.times = times; this.seconds = seconds; this.failuretimes = failuretimes; } public Sms(int smsid,String phonenum, String content,String card,int times,int seconds,int failuretimes) { this.smsid = smsid; this.phonenum = phonenum; this.content = content; this.card = card; this.times = times; this.seconds = seconds; this.failuretimes = failuretimes; } public int getTimes() { return times; } public void setTimes(int times) { this.times = times; } public long getSeconds() { return seconds; } public void setSeconds(long seconds) { this.seconds = seconds; } public void setSmsid(Integer smsid) { this.smsid = smsid; } public int getSmsid() { return smsid; } public String getPhonenum() { return phonenum; } public void setPhonenum(String phonenum) { this.phonenum = phonenum; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getCard() { return card; } public void setCard(String card) { this.card = card; } public int getFailuretimes() { return failuretimes; } public void setFailuretimes(int failuretimes) { this.failuretimes = failuretimes; } public String toString(){ return "id="+this.smsid+",phonenum="+this.phonenum+"; content="+this.content+"; card=" +this.card+"; times="+this.times+"; seconds="+this.seconds+", failuretimes="+this.failuretimes; } public String toString1(){ return ",phonenum="+this.phonenum+"; content="+this.content; } }
SMSBroadcastReceiver.java
package test.sms; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.telephony.SmsMessage; public class SMSBroadcastReceiver extends BroadcastReceiver { /* 自定义ACTION常数,作为广播的Intent Filter识别常数 */ private static String SENT_SMS_ACTION = "android.intent.action.SENT_SMS_ACTION"; // private static String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION"; private static String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; // private final static String TAG = "SMSBroadcastReceiver"; //获取所有短信过滤数据; private FilterService filterService; private List<FilterBean> list; @Override public void onReceive(Context context, Intent intent) { //获取所有短信过滤数据 filterService = new FilterService(context); list = filterService.getAllData(); if (intent.getAction().equals(SENT_SMS_ACTION)) { System.out.println("短信发送监控!!!!!!!"); // LogCatcher.printLog(TAG,"短信发送监控!!!!!!!"); try { switch (getResultCode()) { case Activity.RESULT_OK: /* 发送短信成功 */ System.out.println("短信id:"+intent.getStringExtra("smsid")+"内容:"+intent.getStringExtra("content")+"发送成功!!!!!!!!!"); // LogCatcher.printLog(TAG, "短信id:"+intent.getStringExtra("smsid")+"内容:"+intent.getStringExtra("content")+"发送成功!!!!!!!!!"); System.out.println("成功回调函数开始。。。。。。。。"); // LogCatcher.printLog(TAG, "成功回调函数开始。。。。。。。。"); SMSTest.getSMSTest(context).sendSuccess(Integer.parseInt(intent.getStringExtra("smsid"))); break; default: System.out.println("短信id:"+intent.getStringExtra("smsid")+"发送失败!!!!!!!!!"); // LogCatcher.printLog(TAG, "短信id:"+intent.getStringExtra("smsid")+"发送失败!!!!!!!!!"); System.out.println("失败回调函数开始。。。。。。。。"); // LogCatcher.printLog(TAG, "失败回调函数开始。。。。。。。。"); SMSTest.getSMSTest(context).sendFailure(Integer.parseInt(intent.getStringExtra("smsid"))); } } catch (Exception e) { e.getStackTrace(); } } else if (intent.getAction().equals(SMS_RECEIVED)) { System.out.println("有短信进来!"); // LogCatcher.printLog(TAG, "有短信进来!"); SMSTest sMSTest = SMSTest.getSMSTest(context); Object[] pdus = (Object[]) intent.getExtras().get("pdus"); for (Object p : pdus) { byte[] pdu = (byte[]) p; SmsMessage message = SmsMessage.createFromPdu(pdu); String content = message.getMessageBody(); //以下注释的三行暂时无用 // Date date = new Date(message.getTimestampMillis()); // SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // String receiveTime = format.format(date); String senderNumber = message.getOriginatingAddress(); System.out.println("短信号码:"+senderNumber+",短信内容:"+content); // LogCatcher.printLog(TAG, "短信号码:"+senderNumber+",短信内容:"+content); //短信、内容过滤,直接屏蔽 if ((filterNumber(senderNumber)||filterContent(content)) == true) { System.out.println("号码或内容过滤,直接屏蔽!!!!!!"); // LogCatcher.printLog(TAG, "号码或内容过滤,直接屏蔽!!!!!!"); abortBroadcast();// 终止广播 } //屏蔽,并回复任意 if (filterAnswerWhatever(content) == true) { abortBroadcast();// 终止广播 System.out.println("回复任意"); // LogCatcher.printLog(TAG, "回复任意"); char c = createRandomChar(); sMSTest.sendReplySMS(senderNumber,String.valueOf(c)); } //屏蔽,并回复截取内容 if (subStrFromContent(content) != null) { abortBroadcast();// 终止广播 System.out.println("回复指定的值(截取)"); // LogCatcher.printLog(TAG, "回复指定的值(截取)"); sMSTest.sendReplySMS(senderNumber,subStrFromContent(content)); } //屏蔽,并回复题目答案 if (filterAnswerQuestion(content) == true) { abortBroadcast();// 终止广播 System.out.println("答题,暂未处理"); // LogCatcher.printLog(TAG, "答题,暂未处理"); // 将短信内容发送至服务器,将返回的答案发送 // String result = getAnswer(content); // Sms sm = new Sms(senderNumber,result)); // sendReplySMS(senderNumber,result); } } } } //号码过滤 private boolean filterNumber(String senderNumber) { boolean flag = false; List<FilterBean> numberList = getFilterBransByType(1);//获取type=1的数据(号码过滤) if(numberList.size()>0){ for(FilterBean filterBean : numberList){ if(senderNumber.contains(filterBean.getValue())){ flag = true; } } } return flag; } //内容过滤 private boolean filterContent(String content) { boolean flag = false; List<FilterBean> contentList = getFilterBransByType(2);//获取type=2的数据(内容过滤) if(contentList.size()>0){ for(FilterBean filterBean : contentList){ if(content.contains(filterBean.getValue())){ flag = true; } } } return flag; } //回复任意 private boolean filterAnswerWhatever(String content) { boolean flag = false; List<FilterBean> answerWhateverList = getFilterBransByType(3);//获取type=3的数据(回复任意过滤) if(answerWhateverList.size()>0){ for(FilterBean filterBean : answerWhateverList){ if(content.contains(filterBean.getValue())){ flag = true; } } } return flag; } //截取回复的内容 private String subStrFromContent(String content){ String str = null; String dividemark = SMSTest.getDividemark(); String str1,str2;// int str1index,str2index; List<FilterBean> subStrList = getFilterBransByType(4);//获取type=4的数据(回复指定内容过滤) if(subStrList.size()>0){ for(FilterBean filterBean : subStrList){ int index = filterBean.getValue().indexOf(dividemark); str1 = filterBean.getValue().substring(0, index); str2 = filterBean.getValue().substring(index+1); str1index = filterBean.getValue().indexOf(str1); str2index = filterBean.getValue().indexOf(str2); if((content.contains(str1)&&content.contains(str2))&&(str1index < str2index)&&(str2index-str1index-str1.length() > 0)){ int beginindex = content.indexOf(str1)+str1.length(); int endindex = content.indexOf(str2); str = content.substring(beginindex,endindex); } } } return str; } //答题 private boolean filterAnswerQuestion(String content) { boolean flag = false; List<FilterBean> answerQuestionList = getFilterBransByType(5);//获取type=5的数据(答题过滤) if(answerQuestionList.size()>0){ for(FilterBean filterBean : list){ //暂未处理 if(content.contains(filterBean.getValue())){ flag = true; System.out.println("答题"); // LogCatcher.printLog(TAG, "答题"); System.out.println(filterBean.getValue()); // LogCatcher.printLog(TAG, filterBean.getValue()); } } } return flag; } //生成任意字符 private char createRandomChar(){ char c='a'; c=(char)(c+(int)(Math.random()*26)); return c; } //获取短信过滤信息中指定type的数据 private List<FilterBean> getFilterBransByType(int type){ List<FilterBean> typeList = new ArrayList<FilterBean>(); for(FilterBean filterBean : list){ if(filterBean.getType()==type){ typeList.add(filterBean); } } return typeList; } }
SMSMessageActivity.java
package test.sms; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class SMSMessageActivity extends Activity { private Button btnSend; private EditText edtPhoneNo; private EditText edtContent; private SMSTest smsTest; private Sms sms; private int i=1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); smsTest = SMSTest.getSMSTest(getApplicationContext()); btnSend = (Button) findViewById(R.id.btnSend); edtPhoneNo = (EditText) findViewById(R.id.edtPhoneNo); edtContent = (EditText) findViewById(R.id.edtContent); edtPhoneNo.setText("5556"); edtContent.setText("message"+i); btnSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String phoneNo = edtPhoneNo.getText().toString(); String message = edtContent.getText().toString(); sms = new Sms(phoneNo, message); if (phoneNo.length() > 0 && message.length() > 0) { //添加短信 smsTest.send(sms); i++; edtContent.setText("message"+i); } else { Toast.makeText(getBaseContext(), "请输入完整",Toast.LENGTH_SHORT).show(); } } }); } }
SmsService.java
package test.sms; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class SmsService { private DBOpenHelper dbOpenHelper; public SmsService(Context context) { this.dbOpenHelper = new DBOpenHelper(context); } /** * 添加记录 * * @param person */ public void save(Sms sms) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); StringBuffer sql = new StringBuffer(); sql.append("insert into sms(phonenum,content,card,times,seconds,failuretimes) values(?,?,?,?,?,?)"); db.execSQL(sql.toString(),new Object[] { sms.getPhonenum(), sms.getContent(),sms.getCard(), sms.getTimes(), sms.getSeconds(), sms.getFailuretimes()}); db.close(); } /** * 根据id删除记录 * * @param id */ public void delete(Integer id) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.execSQL("delete from sms where smsid=?", new Object[] { id }); db.close(); } /** * 删除top * * @param id */ public void deleteTop() { Sms sms = getTop(); SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.execSQL("delete from sms where smsid=?",new Object[] { sms.getSmsid() }); db.close(); } /** * 删除bottom */ public void deleteBottom() { Sms sms = getBottom(); SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.execSQL("delete from sms where smsid=?",new Object[] { sms.getSmsid() }); db.close(); } /** * 更新记录 * * @param person */ public void updateTop(Sms sms) { int id = getFirstSmsidFromDB();// 数据库中第一条短信的id SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); StringBuffer sql = new StringBuffer(); sql.append("update sms set phonenum=?,content=?,card=?,times=?,seconds=?,failuretimes=? where smsid=?"); db.execSQL(sql.toString(),new Object[] { sms.getPhonenum(), sms.getContent(), sms.getCard(), sms.getTimes(), sms.getSeconds(), sms.getFailuretimes(), id }); db.close(); } /** * 查找记录 * * @param id * @return person */ public Sms find(Integer id) { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select *from sms where smsid=?",new String[] { id.toString()}); if (cursor.moveToFirst()) { int smsid = cursor.getInt(cursor.getColumnIndex("smsid")); String phonenum = cursor.getString(cursor.getColumnIndex("phonenum")); String content = cursor.getString(cursor.getColumnIndex("content")); String card = cursor.getString(cursor.getColumnIndex("card")); int times = cursor.getInt(cursor.getColumnIndex("times")); int seconds = cursor.getInt(cursor.getColumnIndex("seconds")); int failuretimes = cursor.getInt(cursor.getColumnIndex("failuretimes")); return new Sms(smsid, phonenum, content, card, times, seconds,failuretimes); } cursor.close(); db.close(); return null; } /** * 获取数据库中第一条短信的id * * @return */ public int getFirstSmsidFromDB() { int smsid = 0; SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from sms", null); if (cursor.moveToFirst()) { smsid = cursor.getInt(cursor.getColumnIndex("smsid")); } cursor.close(); db.close(); return smsid; } /** * 分页 * * @param offset * 跳过多少条记录 * @param maxResult * 每页获取多少条记录 * @return */ public List<Sms> getScrollData(int offset, int maxResult) { List<Sms> smss = new ArrayList<Sms>(); SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery( "select *from sms order by smsid asc limit ?,?", new String[] { String.valueOf(offset), String.valueOf(maxResult) }); while (cursor.moveToNext()) { int smsid = cursor.getInt(cursor.getColumnIndex("smsid")); String phonenum = cursor.getString(cursor .getColumnIndex("phonenum")); String content = cursor.getString(cursor.getColumnIndex("content")); String card = cursor.getString(cursor.getColumnIndex("card")); int times = cursor.getInt(cursor.getColumnIndex("times")); int seconds = cursor.getInt(cursor.getColumnIndex("seconds")); int failuretimes = cursor.getInt(cursor .getColumnIndex("failuretimes")); smss.add(new Sms(smsid, phonenum, content, card, times, seconds, failuretimes)); } cursor.close(); db.close(); return smss; } /** * 获取所有记录 * * @return */ public List<Sms> getAllData(){ List<Sms> smss = new ArrayList<Sms>(); SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select *from sms", null); if(cursor!=null){ if(cursor.moveToFirst()){ do{ int smsid = cursor.getInt(cursor.getColumnIndex("smsid")); String phonenum = cursor.getString(cursor.getColumnIndex("phonenum")); String content = cursor.getString(cursor.getColumnIndex("content")); String card = cursor.getString(cursor.getColumnIndex("card")); int times = cursor.getInt(cursor.getColumnIndex("times")); int seconds = cursor.getInt(cursor.getColumnIndex("seconds")); int failuretimes = cursor.getInt(cursor.getColumnIndex("failuretimes")); smss.add(new Sms(smsid,phonenum,content,card,times,seconds,failuretimes)); }while(cursor.moveToNext()); } } cursor.close(); db.close(); return smss; } /** * 获取记录总数 * * @return */ public long getCount() { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select count(*) from sms", null); cursor.moveToFirst(); long result = cursor.getLong(0); cursor.close(); db.close(); return result; } /** * 获取最新记录 * * @return */ public Sms getTop() { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from sms", null); Sms sms = null; if (cursor.moveToFirst()) { int smsid = cursor.getInt(cursor.getColumnIndex("smsid")); // 暂时不用id String phonenum = cursor.getString(cursor.getColumnIndex("phonenum")); String content = cursor.getString(cursor.getColumnIndex("content")); String card = cursor.getString(cursor.getColumnIndex("card")); int times = cursor.getInt(cursor.getColumnIndex("times")); int seconds = cursor.getInt(cursor.getColumnIndex("seconds")); int failuretimes = cursor.getInt(cursor.getColumnIndex("failuretimes")); sms = new Sms(smsid, phonenum, content, card, times, seconds,failuretimes); } cursor.close(); db.close(); return sms; } /** * 查找bottom记录 * * @param id * @return person */ public Sms getBottom() { SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from sms", null); Sms sms = null; if (cursor.moveToLast()) { int smsid = cursor.getInt(cursor.getColumnIndex("smsid")); // 暂时不用id String phonenum = cursor.getString(cursor.getColumnIndex("phonenum")); String content = cursor.getString(cursor.getColumnIndex("content")); String card = cursor.getString(cursor.getColumnIndex("card")); int times = cursor.getInt(cursor.getColumnIndex("times")); int seconds = cursor.getInt(cursor.getColumnIndex("seconds")); int failuretimes = cursor.getInt(cursor.getColumnIndex("failuretimes")); sms = new Sms(smsid, phonenum, content, card, times, seconds,failuretimes); } cursor.close(); db.close(); return sms; } /** * 清空表 * * @return */ public void emptyTable() { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.execSQL("delete from sms"); // 清除自增 db.execSQL("UPDATE sqlite_sequence SET seq = 0 WHERE name = 'sms'"); db.close(); } }
SMSTest.java
package test.sms; import java.util.ArrayList; import java.util.List; import java.util.Timer; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.telephony.SmsManager; public class SMSTest { //单例 private static SMSTest smsTest = null; //是否在发短信 private boolean isSMSSending = false; //定义短信截取分隔符 private final static String dividemark = "\n"; //定义smsList的大小 private final static int smsListSize = 5; //时间间隔 private static final long SENDTIMERTIMESPAN = 60*1000;//一分钟 //二次确认回复短信的时间间隔 private long sendReplySMSTimespan = 60*1000;//一分钟 //设置失败时间间隔 // private long failuretimespan = 10*60*1000; private long failuretimespan = 10*1000; //10S测试用标记标记标记标记标记标记标记标记标记标记标记标记标记标记标记标记标记标记标记 //定时器 private Timer timer; //smsid private static int smsid = 0; private SMSList smsList = SMSList.getSMSList();//发短信存放list private ReplySMSList replySMSList = ReplySMSList.getReplySMSList();//二次确认短信存放list private SmsService smsService;//发送短信操作service private FilterService filterService;//注册短信过滤信息service private Context context; /* 自定义ACTION常数,作为广播的Intent Filter识别常数 */ private static String SENT_SMS_ACTION = "android.intent.action.SENT_SMS_ACTION"; // private static String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION"; private static String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; public static SMSTest getSMSTest(Context context) { if (smsTest == null) { smsTest = new SMSTest(context); } return smsTest; } public static String getDividemark(){ return dividemark; } public SMSTest(Context context){ this.context = context; smsService = new SmsService(context);// 必须放这里 //如果数据库中有数据则优先加入list中 if(smsService.getCount()>0){ List<Sms> smss = smsService.getAllData(); for(Sms sms : smss){ sms.setSmsid(smsid); smsList.addSms(sms); smsid++; } // LogCatcher.printLog(TAG, "数据库中数据加入list,共"+smss.size()+"条数据!!!!!!!"); System.out.println("数据库中数据加入list,共"+smss.size()+"条数据!!!!!!!"); if(isSMSSending==false){ innerSend(); } }else{ // LogCatcher.printLog(TAG,"数据库中暂无数据!!!!!!!!!" ); System.out.println("数据库中暂无数据!!!!!!!!!"); } } //send public void send(Sms sms){ sms.setSmsid(smsid); smsid++; sms.setSmsid(smsid); addSms(sms); if(isSMSSending==false){ innerSend(); } } //发短信 private void innerSend(){ if(replySMSList.getSize()>0){ System.out.println("replySMSList大小为:"+replySMSList.getSize()+"继续发送!!!!!"); // isReplySMSSending = true; isSMSSending = true; timer = new Timer(); Sms replySms = replySMSList.getSms(replySMSList.getSize()-1);//获取最新短信 System.out.println("发送一条回复短信。。。。。。。。。"); sendSMS(replySms); timer.schedule(new sendReplySMSTask(),sendReplySMSTimespan);//固定值一分钟 }else{ // LogCatcher.printLog(TAG,"二次确认replySMSList中无短信!!!!!!!!!" ); System.out.println("二次确认replySMSList中无短信!!!!!!!!!"); // isReplySMSSending = false; if(smsList.getSize()>0){ // LogCatcher.printLog(TAG, "发送短信的list中有"+smsList.getSize()+"条短信"); System.out.println("发送短信的list中有"+smsList.getSize()+"条短信"); isSMSSending = true; timer = new Timer(); Sms sms = smsList.getSms(smsList.getSize()-1);//获取最新短信 // LogCatcher.printLog(TAG, "短信的失败次数:"+sms.getFailuretimes()); System.out.println("短信的失败次数:"+sms.getFailuretimes()); if(sms.getFailuretimes()<3){ // LogCatcher.printLog(TAG, "短信的失败次数小于3"); System.out.println("短信的失败次数小于3"); // LogCatcher.printLog(TAG, "发送。。。。。。。短信id:"+sms.getSmsid()); System.out.println("发送。。。。。。。短信id:"+sms.getSmsid()); sendSMS(sms); // LogCatcher.printLog(TAG, "定时器开始跑。。。。。。。。跑"+getTimespan()/1000+"秒,中途有发送结果到来则停掉"); System.out.println("定时器开始跑。。。。。。。。跑"+SENDTIMERTIMESPAN/1000+"秒,中途有发送结果到来则停掉"); timer.schedule(new sendSMSTask(),SENDTIMERTIMESPAN); }else{ // LogCatcher.printLog(TAG, "失败次数到3,直接删除。。。。。。"); System.out.println("失败次数到3,直接删除。。。。。。"); smsList.removeSms(smsList.getSize()-1);//队列删除 smsService.deleteTop();//数据库删除 if(smsList.getSize()>0){ sendSMS(smsList.getSms(smsList.getSize()-1)); // LogCatcher.printLog(TAG, "定时器开始跑。。。。。。。。跑"+getTimespan()/1000+"秒,中途有发送结果到来则停掉"); System.out.println("定时器开始跑。。。。。。。。跑"+SENDTIMERTIMESPAN/1000+"秒,中途有发送结果到来则停掉"); timer.schedule(new sendSMSTask(),SENDTIMERTIMESPAN); }else{ // LogCatcher.printLog(TAG, "list中已无短信!!!!!!!!!"); System.out.println("list中已无短信!!!!!!!!!"); isSMSSending = false; } } }else{ // LogCatcher.printLog(TAG, "list中已无短信!!!!!!!!!"); System.out.println("list中已无短信!!!!!!!!!"); // LogCatcher.printLog(TAG, "数据库中短信还有"+smsService.getCount()+"条"); System.out.println("数据库中短信还有"+smsService.getCount()+"条"); isSMSSending = false; timer.cancel(); } } } //发送短信的task class sendSMSTask extends java.util.TimerTask { public void run() { // LogCatcher.printLog(TAG, "运行发送短信定时器中方法"); System.out.println("运行发送短信定时器中方法"); if(smsList.getSize()>0){ Sms sms = replySMSList.getSms(smsList.getSize()-1);//获取最新短信 if(sms.getFailuretimes()<3){ sms.setFailuretimes(sms.getFailuretimes()+1);//错误次数加一 smsService.updateTop(sms);//数据库同步更新top }else{ smsList.removeSms(smsList.getSize()-1);//队列删除 smsService.deleteTop();//数据库删除最新短信top } } System.out.println("定时器执行结束!"); // LogCatcher.printLog(TAG, "定时器执行结束!"); System.out.println("发送失败,短信发送时间间隔变为10分钟"); // LogCatcher.printLog(TAG, "发送失败,短信发送时间间隔变为10分钟"); timer.schedule(new sendSMSTimespanTask(),failuretimespan);//短信发送时间间隔 } } //二次确认的task class sendReplySMSTask extends java.util.TimerTask { public void run() { // LogCatcher.printLog(TAG, "运行二次确认定时器中方法"); System.out.println("一条回复短信结果返回超时,进入定时器中的方法,删除一条最新短信。。。。。。。。。。。"); replySMSList.removeSms(replySMSList.getSize()-1);//队列删除 // LogCatcher.printLog(TAG, "定时器执行结束!"); System.out.println("定时器执行结束!"); timer.cancel(); System.out.println("继续执行innerSend方法"); innerSend(); } } //二次确认的task class sendSMSTimespanTask extends java.util.TimerTask { public void run() { // LogCatcher.printLog(TAG, "短信发送时间间隔timer运行完"); System.out.println("短信发送时间间隔timer运行完"); innerSend(); } } //将短信插入数据库中,并加入到list中 private void addSms(Sms sms) { if (smsList.getSize() < smsListSize) { smsList.addSms(sms); smsService.save(sms);//插入数据库 } else { // list饱和则删除最老的,并删除数据库中相应选项 smsList.removeSms(0); smsList.addSms(sms); smsService.deleteBottom(); smsService.save(sms); } } //发短信 private void sendSMS(Sms sendSms){ /* 建立SmsManager对象 */ SmsManager smsManager = SmsManager.getDefault(); /* 建立自定义Action常数的Intent(给PendingIntent参数之用) */ Intent itSend = new Intent(SENT_SMS_ACTION); Intent itDeliver = new Intent(SMS_RECEIVED); itSend.putExtra("smsid", String.valueOf(sendSms.getSmsid())); itSend.putExtra("phonenum", sendSms.getPhonenum()); itSend.putExtra("content", sendSms.getContent()); itSend.putExtra("card", sendSms.getCard()); itSend.putExtra("seconds", String.valueOf(sendSms.getSeconds())); itSend.putExtra("times", String.valueOf(sendSms.getTimes())); itSend.putExtra("failuretimes", String.valueOf(sendSms.getFailuretimes())); PendingIntent mSendPI = PendingIntent.getBroadcast(context, 0, itSend, Intent.FLAG_ACTIVITY_NO_HISTORY); PendingIntent mDeliverPI = PendingIntent.getBroadcast(context, 0, itDeliver, 0); smsManager.sendTextMessage(sendSms.getPhonenum(), null,sendSms.getContent(), mSendPI, mDeliverPI); } //发送成功处理 public void sendSuccess(int smsid) { if(isReplySmsSendResult(smsid)==true){ // LogCatcher.printLog(TAG, "二次确认的结果返回"); System.out.println("一条回复短信发送成功,结果返回且回复短信list中含有此短信,删除。。。回复短信的list中还有信息条数为:"+replySMSList.getSize()); // LogCatcher.printLog(TAG, "二次确认list中含有该短信"); replySMSList.removeSms(replySMSList.getSize()-1);//队列删除 System.out.println("此短信已删除、、、、、、、、、、、、、"); System.out.println("退出timer"); timer.cancel(); System.out.println("二次确认发送成功结果已返回,如果还有则继续发送0000,再次进入innerSend方法。。。。。。。"); innerSend(); }else if(isSmsSendResult(smsid)==true){ // LogCatcher.printLog(TAG, "发送短信的结果返回"); System.out.println("发送短信的结果返回"); // LogCatcher.printLog(TAG, "发送短信list中含有该id的短信"); System.out.println("发送短信list中含有该id的短信"); Sms sms = smsList.getSmsFromListById(smsid);//获取相应短信 if(sms.getTimes()>1){ sms.setTimes(sms.getTimes()-1);//队列中相应短信发送次数字段减一 smsService.updateTop(sms);//数据库同步更新top // LogCatcher.printLog(TAG, "该短信发送次数大于1,将其减一"); System.out.println("该短信发送次数大于1,将其减一"); }else{ smsList.removeSms(smsList.getSize()-1);//队列删除 smsService.deleteTop();//数据库删除最新短信top // LogCatcher.printLog(TAG, "该短信发送次数不大于一,将其删除"); System.out.println("该短信发送次数不大于一,将其删除"); } // LogCatcher.printLog(TAG, "要退出timer啦啊啊 啊 啊啊啊 啊啊 啊 "); System.out.println("要退出timer啦啊啊 啊 啊啊啊 啊啊 啊 "); timer.cancel(); timer = new Timer(); // LogCatcher.printLog(TAG, "发送成功,短信发送时间间隔变为传递参数的值"); System.out.println("发送成功,短信发送时间间隔变为传递参数的值"); timer.schedule(new sendSMSTimespanTask(),sms.getSeconds());//短信发送时间间隔 } } //发送失败处理 public void sendFailure(int smsid) { if(isReplySmsSendResult(smsid)==true){ System.out.println("一条回复短信发送成功,结果返回且回复短信list中含有此短信,则将此短信删除。。。。。。。。"); replySMSList.removeSms(replySMSList.getSize()-1);//队列删除 System.out.println("此短信已删除、、、、、、、、、、、、、"); System.out.println("退出timer"); timer.cancel(); System.out.println("二次确认发送失败结果已返回,如果还有则继续发送0000,再次进入innerSend方法。。。。。。。"); innerSend(); }else if(isSmsSendResult(smsid)==true){ Sms sms = smsList.getSmsFromListById(smsid);//获取相应短信 if(sms.getFailuretimes()<3){ sms.setFailuretimes(sms.getFailuretimes()+1); smsService.updateTop(sms);//数据库同步更新 }else{ smsList.removeSms(smsList.getSize()-1);//队列删除 smsService.deleteTop();//数据库删除 } timer.cancel(); timer = new Timer(); // LogCatcher.printLog(TAG, "发送失败,短信发送时间间隔变为10分钟"); System.out.println("发送失败,短信发送时间间隔变为10分钟"); timer.schedule(new sendSMSTimespanTask(),failuretimespan);//短信发送时间间隔 } } //判断smsList中是否还含有指定smsid的短信 private boolean smsIsExist(int smsid){ boolean flag = false; for(int i=0;i<smsList.getSize();i++){ if(smsList.getSms(i).getSmsid()==smsid){ flag = true; } } return flag; } //判断replySmsList中是否还含有指定smsid的短信 private boolean replySmsIsExist(int smsid){ boolean flag = false; for(int i=0;i<replySMSList.getSize();i++){ if(replySMSList.getSms(i).getSmsid()==smsid){ flag = true; } } return flag; } //二次确认的短信加入replySMSList public void addReplySMS(String senderNumber, String content){ ReplySMSList list = ReplySMSList.getReplySMSList(); Sms sms = new Sms(smsid,senderNumber,content); list.addSms(sms); // LogCatcher.printLog(TAG, "加入ReplySMSList的短信是:"+sms.toString1()+",ReplySMSList大小为:"+list.getSize()); System.out.println("加入ReplySMSList的短信是:"+sms.toString1()+",ReplySMSList大小为:"+list.getSize()); smsid++; } //发送二次确认短信 public void sendReplySMS(String senderNumber, String content) { // LogCatcher.printLog(TAG, "先加入list,number="+senderNumber+",content="+content); System.out.println("先加入list,number="+senderNumber+",content="+content); addReplySMS(senderNumber,content);//将短信加入list System.out.println(isSMSSending); if(isSMSSending==false){ System.out.println("进来啦00000000000000000000000000000"); // LogCatcher.printLog(TAG, "运行innerSendReplySMS.........."); System.out.println("运行innerSendReplySMS.........."); innerSend(); } } // //发送二次确认短信 // private void innerSendReplySMS() { //// LogCatcher.printLog(TAG, "到了inner"); // System.out.println("到了inner"); //// LogCatcher.printLog(TAG, "replySMSList的大小:"+replySMSList.getSize()); // System.out.println("replySMSList的大小:"+replySMSList.getSize()); // if(replySMSList.getSize()>0){ // isSMSSending = true; // timer = new Timer(); // Sms sms = replySMSList.getSms(replySMSList.getSize()-1); // sendSMS(sms); //// LogCatcher.printLog(TAG, "发送一条回复短信"); // System.out.println("发送一条回复短信"); //// LogCatcher.printLog(TAG, "定时器开始跑。。。。。。。。跑"+sendReplySMSTimespan/1000+"秒"); // System.out.println("定时器开始跑。。。。。。。。跑"+sendReplySMSTimespan/1000+"秒"); // timer.schedule(new sendSMSTimespanTask(),sendReplySMSTimespan);//二次确认短信回复broadcast只是一分钟 // }else{ // isSMSSending = false; // } // } //判断短信是发送短信还是二次确认短信 private boolean isSmsSendResult(int smsid){ boolean result = false; for(int i=0;i<smsList.getSize();i++){ if(smsList.getSms(i).getSmsid()==smsid){ result = true; } } return result; } private boolean isReplySmsSendResult(int smsid){ boolean result = false; for(int i=0;i<replySMSList.getSize();i++){ if(replySMSList.getSms(i).getSmsid()==smsid){ result = true; } } return result; } /** *注册短信过滤信息 */ public void regist(int type,String value){ FilterBean fliterBean = new FilterBean(type, value); filterService.save(fliterBean); } /** *注册短信过滤信息 (截取) */ public void regist(String value1,String value2){ String value = value1+dividemark+value2;//拼接 FilterBean fliterBean = new FilterBean(4, value); filterService.save(fliterBean); } //发短信list类 static class SMSList { private static SMSList smsList = null; private SMSList() { } private List<Sms> list = new ArrayList<Sms>(); public static SMSList getSMSList() { if (smsList == null) { smsList = new SMSList(); } return smsList; } //添加短信信息 public void addSms(Sms sms){ list.add(sms); } //移除短信信息 public Sms removeSms(int index){ return list.remove(index); } //获取list大小 public int getSize(){ return list.size(); } public boolean isEmpty(){ return list.isEmpty(); } //获取指定短信 public Sms getSms(int i){ return list.get(i); } //获取指id定短信 public Sms getSmsFromListById(int smsid){ Sms sms = null; for(int i=0;i<list.size();i++){ if(list.get(i).getSmsid()==smsid){ sms = list.get(i); } } return sms; } } //回复短信list static class ReplySMSList { private static ReplySMSList replySMSList = null; private ReplySMSList() {} public static ReplySMSList getReplySMSList() { if (replySMSList == null) { replySMSList = new ReplySMSList(); } return replySMSList; } private List<Sms> list = new ArrayList<Sms>(); //添加短信信息 public void addSms(Sms sms){ list.add(sms); } //移除短信信息 public Sms removeSms(int index){ return list.remove(index); } //获取list大小 public int getSize(){ return list.size(); } public boolean isEmpty(){ return list.isEmpty(); } //获取指定短信 public Sms getSms(int i){ return list.get(i); } //获取指id定短信 public Sms getSmsFromListById(int smsid){ Sms sms = null; for(int i=0;i<list.size();i++){ if(list.get(i).getSmsid()==smsid){ sms = list.get(i); } } return sms; } } }
浙公网安备 33010602011771号