Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/181.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何将联系人信息输入sms广播接收器类?_Android_Sms_Broadcastreceiver_Android Contacts - Fatal编程技术网

Android 如何将联系人信息输入sms广播接收器类?

Android 如何将联系人信息输入sms广播接收器类?,android,sms,broadcastreceiver,android-contacts,Android,Sms,Broadcastreceiver,Android Contacts,我有一个应用程序,可以在手机接收短信时使用联系人信息,我需要将联系人信息放入我创建的SMS receiver类中,但问题是当SMS receiver fetch contacts出现空指针异常错误时,因为它无法获取联系人信息,我的想法是获取所有联系人信息,比较短信发送者的号码,以获取其ID,以便在我的应用程序中执行其他操作 这是我的密码: public class SMSBroadcastReceiver extends BroadcastReceiver { private stat

我有一个应用程序,可以在手机接收短信时使用联系人信息,我需要将联系人信息放入我创建的SMS receiver类中,但问题是当SMS receiver fetch contacts出现空指针异常错误时,因为它无法获取联系人信息,我的想法是获取所有联系人信息,比较短信发送者的号码,以获取其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;
    }

}

最后,我解决了我的问题,我创建了一个名为contacts的对象类,其中包含所有contacts参数,并创建了一个contacts的arrayList,并用contacts填充它,以获取要逐个比较的信息,从而获得我需要的信息

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

我会初始化一个服务,而不是在接收端这样做。 看到这种服务了吗