2

我有一个应用程序可以在手机收到短信时处理联系人信息,我需要将联系人信息获取到我创建的短信接收器类中,但问题是当短信接收器获取联系人时出现我的空指针异常错误,因为它不要获取联系人信息,我的想法是获取所有联系人信息以比较 SMS 发件人的号码以获取他的 ID 以在我的应用程序中执行其他操作。

这是我的代码:

public class SMSBroadcastReceiver extends BroadcastReceiver {

    private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
    private static final String TAG = "SMSBroadcastReceiver";
    private static Activity mActivity;
    DBHelper mDBHelper;
    private Context mContext;
    private ArrayList<Contact> mContactsArrayList;
    public String str4;
    private ContactManager aContactManager;
    private ArrayList<Contact> ctnList;
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        //---get the SMS message passed in---
        Log.d("SMSBroadcastReceiver", "Yes it calls the onReceive");
        Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;
        String str = "";
        String str2 = "";
        if (bundle != null)
        {
            //---retrieve the SMS message received---
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];            
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
               str2=msgs[i].getOriginatingAddress();                     
                str = msgs[i].getMessageBody().toString();
                   str4 = str2;     
            }


            if(str.charAt(0)=='#'&&str.length()<=4){

                String ns = Context.NOTIFICATION_SERVICE;
                NotificationManager notManager = 
                    (NotificationManager) context.getSystemService(ns);

                //Configuramos la notificaci�n
                int icono = R.drawable.resultadosmnu;
                CharSequence textoEstado = "Ask-It notification";
                long hora = System.currentTimeMillis();

                Notification notif = 
                    new Notification(icono, textoEstado, hora);
                CharSequence titulo = "New set of response on Askit";
                CharSequence descripcion = "There's available a new set of response on your Survey_Name graph";

                Intent notIntent = new Intent(context, 
                        ProyectoAskitActivity.class);

                PendingIntent contIntent = PendingIntent.getActivity(
                        context, 0, notIntent, 0);

                notif.setLatestEventInfo(
                        context, titulo, descripcion, contIntent);
                notif.flags |= Notification.FLAG_AUTO_CANCEL;
                notManager.notify(icono, notif);
                Contact cnt = queryDetailsForContactNumber(str2);
                Toast toast1 =
                        Toast.makeText(context,
                                cnt.getPhoneNumber(), Toast.LENGTH_SHORT);

                toast1.show();
         }
        }

        }                         

    public Contact queryDetailsForContactNumber(String aContactId) {
        final String[] projection = new String[] {
                Phone._ID,                          // the contact id column
                Phone.DISPLAY_NAME,                 // the name of the contact
                Phone.NUMBER        // the id of the column in the data table for the image
        };

        final Cursor contact = mActivity.managedQuery(
                Phone.CONTENT_URI,
                projection,
                Phone.NUMBER+"="+aContactId,                        // filter entries on the basis of the contact id
                null,   // the parameter to which the contact id column is compared to
                null);

        if(contact.moveToFirst()) {
            final int contactId =  contact.getInt(
                        contact.getColumnIndex(Phone._ID));
            final String name = contact.getString(
                    contact.getColumnIndex(Phone.DISPLAY_NAME));
            final String number = contact.getString(
                    contact.getColumnIndex(Phone.NUMBER));
            final Contact aContact = new Contact(contactId, name,null,false,number);


            return aContact;
        }

        return null;
    }

}
4

2 回答 2

0

我会启动一项服务,而不是在接收方这样做。看到这种服务http://developer.android.com/reference/android/app/IntentService.html

于 2012-09-27T22:19:23.277 回答
0

最后我解决了我的问题,我使用所有联系人参数创建了一个名为联系人的对象类,并创建了一个联系人数组列表并用联系人填充它以获取信息以逐一比较以获得我需要的信息。

public class SMSBroadcastReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
    private static final String TAG = "SMSBroadcastReceiver";
    DBHelper mDBHelper;
    static Context mContext;
    private ArrayList<Contact> ctnList;

     @Override
    public void onReceive(Context context, Intent intent) 
    {
        //---get the SMS message passed in---
        Log.d("SMSBroadcastReceiver", "Yes it calls the onReceive");
        Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;
        String str = "";
        String str2 = "";
        if (bundle != null)
        {
            //---retrieve the SMS message received---
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];            
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
               str2=msgs[i].getOriginatingAddress();                     
                str = msgs[i].getMessageBody().toString();

            }


            if(str.charAt(0)=='#'&&str.length()<=4){

                String ns = Context.NOTIFICATION_SERVICE;

                ctnList=queryAllContactsWithPhone(context);
                Contact ctn = new Contact();
                int x = ctnList.size();
                int y = 0;
                while(x-1>=y){
                    ctn = ctnList.get(y);
                    if(ctn.getPhoneNumber().compareTo(str2)==0){
                        Toast toast1 =
                                Toast.makeText(context,
                                        ctn.getName(), Toast.LENGTH_LONG);

                        toast1.show();
                    }else{
                        Toast toast1 =
                                Toast.makeText(context,
                                        str2, Toast.LENGTH_LONG);

                        toast1.show();
                    }
                    y++;
                }

         }
        }

        }                         

    public ArrayList<Contact> queryAllContactsWithPhone(Context ct) {

        final String[] projection = new String[] {
                Phone.CONTACT_ID,                           // the contact id column
                Phone.DISPLAY_NAME,                 // the contact display name
                Phone.NUMBER
        };

        final String selection = Contacts.HAS_PHONE_NUMBER; // the contact has to have a phone number.
        final String sort = Contacts.DISPLAY_NAME+" ASC";   // the contact has to have a phone number.

        final Cursor contacts = ct.getContentResolver().query(
                Phone.CONTENT_URI,      // the uri for contact provider
                projection, 
                null,                   // if selection = null, retrieve all entries
                null,                       // not required because selection does not contain parameters
                sort);                      // do not order

        final int contactIdColumnIndex = contacts.getColumnIndex(Phone.CONTACT_ID);
        final int contactDisplayNameColumnIndex = contacts.getColumnIndex(Phone.DISPLAY_NAME);
        final int contactPhoneColumnIndex = contacts.getColumnIndex(Phone.NUMBER);

        final ArrayList<Contact> contactsArrayList = new ArrayList<Contact>();
        if(contacts.moveToFirst()) {                    // move the cursor to the first entry
            while(!contacts.isAfterLast()) {            // still a valid entry left?
                final int contactId =  contacts.getInt(contactIdColumnIndex);
                final String contactDisplayName=  contacts.getString(contactDisplayNameColumnIndex);
                final String Phones = contacts.getString(contactPhoneColumnIndex);
                final Contact aContact = new Contact();
                aContact.setPhoneNumber(Phones);
                aContact.setName(contactDisplayName);
                aContact.setId(contactId);
                contactsArrayList.add(aContact);
                contacts.moveToNext();              // move to the next entry
            }
        }

        contacts.close();
        return contactsArrayList;
    }       
}
于 2012-06-05T14:14:53.423 回答