Search code examples
androidandroid-activityandroid-contentresolver

Android: how to use ContentResolver in background


I have class that extends BroadcastReceiver and gets all new sms.

When I get new sms I want to search the phonebook to check if phone numbers inside this message are in phone book, and if they are, send sms with result to another phone.

I use ContentResolver to check the phone numbers, but to use it I need to use it inside Activity or have pointer to activity, but my sms listener works in background.

Is there a way to search phone book without activity or to get valid activity from context or intent that I get when recieving new sms?

I tried to use something like that:

                    Activity act = new Activity();
                    DBManager dbm = new DBManager(act);
                    ArrayList<MyContact> res = dbm.phoneSearch(sms_ar[1]);
                    SmsSender sms = new SmsSender(act);
                    if(res.size() > 0){                     
                        String answer = res.get(0).getName()+CSStatic.SMS_SEPARATOR+res.get(0).getPhone();
                        for(int z = 1; z < res.size(); z++){
                            answer = answer+CSStatic.SMS_SEPARATOR+res.get(z).getName()+CSStatic.SMS_SEPARATOR+res.get(z).getPhone();
                        }
                        Log.d("sms", "Answer: "+answer);
                        sms.smsAnswer(answer, sms_ar[2]);
                    } else {
                        String phone = dbm.getPhoneToQuery(sms_txt);
                        sms.smsQueryNext(sms_txt, phone);
                    }
                    act.finish();

but it don't work :P In DBManager I search for phones and in SmsSender I send new sms.


Solution

  • You need a valid Context object (an activity or service for example, these are subclasses of Context). These are created by android, do not use the constructor to create these objects!

    To get the needed context in a BroadcastReceiver is explained here: https://stackoverflow.com/a/6074829/1127492, its the first parameter of onReceive().