我正在尝试收听传出的短信。我遵循了接受的答案here,但它无效。我不确定我哪里出错了。我对内容观察者并不熟悉,所以请原谅我的无知。
我想在服务中创建它,以便它一直在运行。这是我在该服务中的代码:
import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
public class SmsOutgoingObserver extends Service {
public SmsOutgoingObserver() {
}
/* this method handles a single incoming request */
@Override
public int onStartCommand(Intent intent, int flags, int id) {
Log.d("OUTGOING", "RUNNING SERVICE");
return START_STICKY; // stay running
}
@Override
public IBinder onBind(Intent intent) {
return null; // disable binding
}
public class SmsObserver extends ContentObserver {
public SmsObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Uri uriSMSURI = Uri.parse("content://sms/out");
Cursor cr = SmsOutgoingObserver.this.getContentResolver().query(uriSMSURI, null, null, null, null);
cr.moveToNext();
String address = cur.getString(cr.getColumnIndex("body"));
Log.d("OUTGOING", address);
cr.close();
//Database.messageReceived(SmsOutgoingObserver.this, address);
}
}
}
我做错了什么?
答案 0 :(得分:2)
除了@CommonsWare指出的愚蠢的错误,我错过了
@Override
public void onCreate() {
super.onCreate();
ContentResolver contentResolver = this.getContentResolver();
contentResolver.registerContentObserver(Uri.parse("content://sms/out"),true, new SmsObserver(new Handler()));
}
另一个问题实际上是在这两行中
contentResolver.registerContentObserver(Uri.parse("content://sms/out"),true, new SmsObserver(new Handler()));
和
Uri uriSMSURI = Uri.parse("content://sms/out");
我将content://sms/out
更改为content://sms
,然后继续检查类型,以确保我获得的更改实际上是传出消息。我还必须确保像这样检查多个电话:
if (cr.getInt(cr.getColumnIndex("type")) == 2) {
if(id != cr.getInt(cr.getColumnIndex(cr.getColumnName(0)))) {
id = cr.getInt(cr.getColumnIndex(cr.getColumnName(0)));
String address = cr.getString(cr.getColumnIndex("address"));
Database.messageSent(SmsOutgoingObserver.this, address);
Log.d("OUTGOING", address);
} else {
Log.d("OUTGOING", "MESSAGE ALREADY LOGGED");
}
};
}
并简单地将private int id = 0;
定义为全局变量
答案 1 :(得分:1)
您的SmsOutgoingObserver
除了将消息记录到LogCat之外什么都不做。如果您要使用SmsObserver
,则需要添加一些代码,例如调用registerContentObserver()
。关于您链接的问题,the accepted answer显示了这一点。