1

我是 android 编程的初学者,我正在尝试创建将短信记录到文件的应用程序。我遇到“方法 getContentResolver() 对于 SMSObserver 类型未定义”的问题,我不知道为什么......

这是代码:

public class SMSObserver extends ContentObserver
{
SMSLogger smsLogger;

public SMSObserver(SMSLogger smsLogger) {
    super(new Handler());
    this.smsLogger = smsLogger;
}

@Override
public void onChange(boolean selfChange) {
    super.onChange(selfChange);
    querySMS();
}

protected void querySMS() {
    Uri uriSMS = Uri.parse("content://sms/");
    Cursor cur = getContentResolver().query(uriSMS, null, null, null, null);
    cur.moveToNext();
    String body = cur.getString(cur.getColumnIndex("body"));
    String add = cur.getString(cur.getColumnIndex("address"));
    String time = cur.getString(cur.getColumnIndex("date"));
    String protocol = cur.getString(cur.getColumnIndex("protocol"));
    String out = "";
    if (protocol == null)
        out = "Sending to "+add + ".Time:"+time +" - "+body;
    else out = "Receive from "+add + ".Time:"+time +" - "+body;
    /*logging action HERE...*/
}
}

和进口:

import android.database.ContentObserver;
import android.os.Handler;
import android.content.ContextWrapper;
import org.json.JSONException;
import org.json.JSONStringer;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.BroadcastReceiver;
import android.database.Cursor;
import android.net.Uri;
import android.content.Context;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.PhoneLookup;

请帮忙。

4

2 回答 2

5

您只能在 Context 对象上调用该方法。尝试这个:

public class SMSObserver extends ContentObserver
{
SMSLogger smsLogger;
Context context;

public SMSObserver(SMSLogger smsLogger, Context c) {
    super(new Handler());
    context = c;
    this.smsLogger = smsLogger;
}

protected void querySMS() {
    Uri uriSMS = Uri.parse("content://sms/");
    Cursor cur = context.getContentResolver().query(uriSMS, null, null, null, null);
}
}
于 2012-04-15T20:26:44.763 回答
0

扩展应用程序以保持上下文并静态访问它或者您可以将函数调用传递给 ContentResolver 中的每个库函数。目前您没有上下文引用,因此您不能在此处调用 getContentResolver()。

于 2012-04-15T20:40:38.333 回答