SMS Logger: method getContentResolver() is undefined for the type

左心房为你撑大大i 提交于 2019-12-24 10:58:28

问题


I'am begginer in android programming and I'am trying to create app that is logging sms's to a file. Iam having a problem with "The method getContentResolver() is undefined for the type SMSObserver" and i dont know why...

Here is the code:

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...*/
}
}

and the imports:

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;

Please help.


回答1:


You can call that method only on Context object. Try this:

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);
}
}



回答2:


Extend Application to keep hold of a context and access it statically Or you can pass function call to each library function in ContentResolver. Currently you do not have Context reference so you can not call getContentResolver() here.



来源:https://stackoverflow.com/questions/10165609/sms-logger-method-getcontentresolver-is-undefined-for-the-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!