我已经成功监视了传入的SMS,并将其发送到数据库以供以后查看。我已经阅读了有关监视器传出短信的信息,但我不太了解它是如何工作的。有人可以指导我如何使用ContentObserver进行代码以监视传出的短信吗?我将在我应该开始的地方发布所有当前的传入sms.need指南代码。
smsReceiver.java
package terima.sms.inbox;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import java.net.*;
import java.io.*;
@SuppressWarnings("deprecation")
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage SMS[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
SMS[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
}
String member_id = "1";
inbox(SMS[0].getOriginatingAddress(), SMS[0].getMessageBody(), member_id);
}
public static Boolean inbox(String telefon, String message, String member_id){
String mesej = "";
for(int i = 0; i < message.length(); i++)
{
if(message.charAt(i) == ' ' || message.charAt(i) == '+')
{
if(message.charAt(i) == ' ')
mesej += "%20";
else
mesej += "%2B";
}
else
{
mesej += message.charAt(i);
}
}
try
{
URL oracle = new URL("http://192.168.1.111/inbox.php?message=" + mesej + "&telefon=" + telefon + "&member=" + member_id);
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));
String fetch, total = "";
while ((fetch = in.readLine()) != null)
total += fetch;
in.close();
if(total.equals("1"))
return true;
return false;
}
catch(Exception e)
{
return false;
}
}
}
提前致谢。
最佳答案
要捕获传出的SMS,您应该结合使用ContentObserver和ContentResolver。这是我在ContentObserver中使用的代码:
public class SmsObserver extends ContentObserver{
int smsCount;
public SmsObserver(Context context) {
super(new Handler());
smsCount = 0;
}
public void onChange(boolean selfChange){
super.onChange(selfChange);
readSms();
}
private void readSms(){
Uri uriSMS = Uri.parse("content://sms");
Cursor cur = context.getContentResolver().query(uriSMS, null, null, null, "_id");
cur.moveToLast();
int id = Integer.parseInt(cur.getString(cur.getColumnIndex("_id")));
if(cur != null && id != smsCount && id>0){
smsCount = id;
int type = Integer.parseInt(cur.getString(cur.getColumnIndex("type")));
if(type == 1){
// handle the received sms
}
else{
// handle the sent sms
}
}
cur.close();
}
}
之后,您应该创建一个SmsOberver实例,并将其注册在“ content:// sms”上。与您发送或接收新消息相比,它触发的频率更高,因此这就是为什么我有一个smsCount字段的原因。