在Android应用程序中发送短信

时间:2015-01-07 14:09:01

标签: android eclipse sms smsmanager

我正在尝试构建一个项目,展示如何通过Android应用程序发送短信。 我根据这里的代码使用SmsManager对象构建了项目(在eclipse中):http://www.tutorialspoint.com/android/android_sending_sms.htm

该项目运行良好,但短信未发送给我。 我想我还需要添加一些东西才能真正发送短信 - 所以我错过了什么? 或者我可能没有正确插入号码?我该怎么写呢?我尝试了几种方法......

任何帮助都会受到很大的关注! 谢谢。

1 个答案:

答案 0 :(得分:0)

以下是点击按钮时从联系人列表中选择联系人的代码:

Button x;
String phn_no, msg,c;

    x.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(Intent.ACTION_PICK,
                        ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, PICK_CONTACT);
            }

        });


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
        case (1):
            if (resultCode == Activity.RESULT_OK) {
                Uri contactData = data.getData();
                Cursor c = getContentResolver().query(contactData, null, null,
                        null, null);
                if (c.moveToFirst()) {
                    String id = c
                            .getString(c
                                    .getColumnIndexOrThrow(ContactsContract.Contacts._ID));

                    String hasPhone = c
                            .getString(c
                                    .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

                    if (hasPhone.equalsIgnoreCase("1")) {
                        Cursor phones = getContentResolver()
                                .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                        null,
                                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                        + " = " + id, null, null);
                        phones.moveToFirst();
                        phn_no = phones.getString(phones
                                .getColumnIndex("data1"));

                        // Toast.makeText(getApplicationContext(), phn_no,
                        // Toast.LENGTH_LONG).show();
                        contact_num.setText(phn_no);

                        // String name =
                        // c.getString(c.getColumnIndex(StructuredPostal.DISPLAY_NAME));
                        // Toast.makeText(this, "contact info : "+
                        // phn_no+"\n"+name, Toast.LENGTH_LONG).show();
                    }

                }
            }
        }
    }

这是发送短信的代码:

    void send_sms(final String phn_no, final String msg) {
        final SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phn_no, null, msg, null, null);
    }
相关问题