我正在开发一个短信应用程序,用于隐藏从联系人列表中选择的某些特定联系人的短信。选择单击按钮后,联系人将添加到SQLite数据库,如下所示:
btn_select.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int len = selection.length;
int cnt = 0;
String selectIds = "";
for (int i = 0; i < len; i++) {
if (selection[i]) {
cnt++;
}
}
for (int i = 0; i < selection_val.size(); i++) {
selectedData[i]=selection_val.get(i);
selectIds = selectIds + " | " + selection_val.get(i);
}
addContacts(selectedData);
private void addContacts(String[] selectedItems) {
manager.Insert_phone_contact(selectedItems);
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
}
插入联系人的SQLite数据库方法如下:
public void Insert_phone_contact(String [] contact){
try{
SQLiteDatabase DB = this.getWritableDatabase();
ContentValues cv = new ContentValues();
for(int i=0;i<contact.length;i++){
// put all values in ContentValues
cv.put(CONTACT_NAME, contact[i]);
}
DB.insert(TABLE_CONTACTS, null, cv); // insert in db
DB.close(); // call close
}
catch(Exception ex){
Log.e("Error in phone contact insertion", ex.toString());
}
}
之后使用SMS接收器接收已保存在DB中的特定联系人的SMS,如下所示:
// get instance of SMS manager
final SmsManager sms = SmsManager.getDefault();
@Override
public void onReceive(Context context, Intent intent) {
try {
final Bundle bundle = intent.getExtras();
if (bundle != null) {
//—retrieve the SMS message received—
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
timestamp = smsMessage[n].getTimestampMillis();
number = smsMessage[n].getOriginatingAddress();
body += smsMessage[n].getDisplayMessageBody();
}
DBmanager = new DbManager(context);
cursor = DBmanager.Return_All_Contacts();
contactArr = showcontactsInfo(cursor);
for(int i= 0;i<=contactArr.length;i++)
{
for (int j=0; j<=contactObj.selectedData.length ;j++){
if(contactArr[i].equals(contactObj.selectedData[j]))
{
abortBroadcast();
blockMessage(context);
}
else{
Toast.makeText(context, "No contact selected", Toast.LENGTH_SHORT);
}
}
}
} // end for loop
} // bundle is null
catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
private String[] showcontactsInfo(Cursor cursor) {
String[] contact = new String [cursor.getCount()];
int i= 0;
while(cursor.moveToNext()){
contact[i] = cursor.getString(1);
i++;
}
return contact;
}
但无法根据保存的联系人过滤短信。任何有用的帮助将受到高度赞赏..