如何从Android应用发送和接收短信? [英] How to send and receive SMS from android app?

查看:152
本文介绍了如何从Android应用发送和接收短信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用程序中添加短信发送功能,并且还希望用户可以直接从应用程序中从联系人列表中选择联系人的选项.联系人列表可以与我的应用程序集成吗?

I want to add sms sending feature in my app and also want option in which user can select the contacts from the contact list directly from the application. Is there way that contact list can be integrated with my application.

谢谢

推荐答案

这是逐步显示如何从Android应用发送短信的教程.

And here is a Tutorial Showing step by step how to send SMS from an Android App.

http://mobiforge.com/developing/story/sms-messaging-android

希望Androider和我的答案会完善您的答案!

Hope Androider's and my answer complets your answer!

更新:由于上面的链接现已失效:

免责声明: 我没有写原始文章.我只是在这里复制.根据这篇文章的原始作者是 weimenglee .我将其复制到此处是因为几年前发布了原始链接后,该链接现在已失效.

Disclaimer: I have not written the original article. I am just copying it here. The orignal author according to the article was weimenglee. I am copying the article here because after posting the original link few years back, the link is now dead.

首先,请启动Eclipse并创建一个新的Android项目.为项目命名,如图1所示.

To get started, first launch Eclipse and create a new Android project. Name the project as shown in Figure 1.

Android使用基于权限的策略,其中需要在AndroidManifest.xml文件中指定应用程序所需的所有权限.这样,在安装应用程序时,用户将清楚应用程序需要哪些特定的访问权限.例如,由于发送SMS消息可能会在用户端产生额外的费用,因此AndroidManifest.xml文件中的SMS权限表明用户可以决定是否允许安装该应用程序.

Android uses a permission-based policy where all the permissions needed by an application need to be specified in the AndroidManifest.xml file. By doing so, when the application is installed it will be clear to the user what specific access permissions are required by the application. For example, as sending SMS messages will potentially incur additional cost on the user’s end, indicating the SMS permissions in the AndroidManifest.xml file will let the user decide whether to allow the application to install or not.

AndroidManifest.xml文件中,添加两个权限– SEND_SMSRECEIVE_SMS:

In the AndroidManifest.xml file, add the two permissions – SEND_SMS and RECEIVE_SMS:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="net.learn2develop.SMSMessaging"
      android:versionCode="1"
      android:versionName="1.0.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SMS"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.SEND_SMS">
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>
</manifest>

res/layout文件夹中的main.xml文件中,添加以下代码,以便用户可以输入电话号码以及要发送的消息:

In the main.xml file located in the res/layout folder, add the following code so that the user can enter a phone number as well as a message to send:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="Enter the phone number of recipient"
        />     
    <EditText 
        android:id="@+id/txtPhoneNo"  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"        
        />
    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"         
        android:text="Message"
        />     
    <EditText 
        android:id="@+id/txtMessage"  
        android:layout_width="fill_parent" 
        android:layout_height="150px"
        android:gravity="top"         
        />          
    <Button 
        android:id="@+id/btnSendSMS"  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:text="Send SMS"
        />    
</LinearLayout>

上面的代码创建如图2所示的UI.

The above code creates the UI shown in Figure 2.

接下来,在SMS活动中,我们连接了Button视图,以便当用户单击它时,在使用sendSMS()函数,我们将在稍后对其进行定义:

Next, in the SMS activity, we wire up the Button view so that when the user clicks on it, we will check to see that the phone number of the recipient and the message is entered before we send the message using the sendSMS() function, which we will define shortly:

package net.learn2develop.SMSMessaging;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SMS extends Activity 
{
    Button btnSendSMS;
    EditText txtPhoneNo;
    EditText txtMessage;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        

        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
        txtMessage = (EditText) findViewById(R.id.txtMessage);
                
        btnSendSMS.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {                
                String phoneNo = txtPhoneNo.getText().toString();
                String message = txtMessage.getText().toString();                 
                if (phoneNo.length()>0 && message.length()>0)                
                    sendSMS(phoneNo, message);                
                else
                    Toast.makeText(getBaseContext(), 
                        "Please enter both phone number and message.", 
                        Toast.LENGTH_SHORT).show();
            }
        });        
    }    
}

sendSMS()函数的定义如下:

public class SMS extends Activity 
{
    //...
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        //...
    }
    
    //---sends an SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {        
        PendingIntent pi = PendingIntent.getActivity(this, 0,
            new Intent(this, SMS.class), 0);                
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, pi, null);        
    }    
}

要发送SMS消息,请使用SmsManager类.与其他类不同,您不直接实例化该类.相反,您将调用getDefault()静态方法来获取SmsManager对象. sendTextMessage()方法发送带有PendingIntent的SMS消息.

To send an SMS message, you use the SmsManager class. Unlike other classes, you do not directly instantiate this class; instead you will call the getDefault() static method to obtain an SmsManager object. The sendTextMessage() method sends the SMS message with a PendingIntent.

PendingIntent对象用于标识稍后要调用的目标.例如,发送消息后,可以使用PendingIntent对象显示另一个活动.在这种情况下,PendingIntent对象(pi)只是指向相同的活动(SMS.java),因此,发送SMS时,什么也不会发生.

The PendingIntent object is used to identify a target to invoke at a later time. For example, after sending the message, you can use a PendingIntent object to display another activity. In this case, the PendingIntent object (pi) is simply pointing to the same activity (SMS.java), so when the SMS is sent, nothing will happen.

如果需要监视SMS消息发送过程的状态,则实际上可以将两个PendingIntent对象与两个BroadcastReceiver对象一起使用,如下所示:

If you need to monitor the status of the SMS message sending process, you can actually use two PendingIntent objects together with two BroadcastReceiver objects, like this:

//---sends an SMS message to another device---
private void sendSMS(String phoneNumber, String message)
{        
    String SENT = "SMS_SENT";
    String DELIVERED = "SMS_DELIVERED";
    
    PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
        new Intent(SENT), 0);
    
    PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
        new Intent(DELIVERED), 0);
    
    //---when the SMS has been sent---
    registerReceiver(new BroadcastReceiver(){
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode())
            {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS sent", 
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    Toast.makeText(getBaseContext(), "Generic failure", 
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    Toast.makeText(getBaseContext(), "No service", 
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    Toast.makeText(getBaseContext(), "Null PDU", 
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    Toast.makeText(getBaseContext(), "Radio off", 
                            Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }, new IntentFilter(SENT));
    
    //---when the SMS has been delivered---
    registerReceiver(new BroadcastReceiver(){
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode())
            {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS delivered", 
                            Toast.LENGTH_SHORT).show();
                    break;
                case Activity.RESULT_CANCELED:
                    Toast.makeText(getBaseContext(), "SMS not delivered", 
                            Toast.LENGTH_SHORT).show();
                    break;                        
            }
        }
    }, new IntentFilter(DELIVERED));        
    
    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);        
}

上面的代码使用PendingIntent对象(sentPI)监视发送过程.发送SMS消息后,将触发第一个BroadcastReceiver的onReceive事件.您可以在此处检查发送过程的状态.第二个PendingIntent对象(deliveredPI)监视交付过程.成功发送SMS时,将触发第二个BroadcastReceiver的onReceive事件.

The above code uses a PendingIntent object (sentPI) to monitor the sending process. When an SMS message is sent, the first BroadcastReceiver‘s onReceive event will fire. This is where you check the status of the sending process. The second PendingIntent object (deliveredPI) monitors the delivery process. The second BroadcastReceiver‘s onReceive event will fire when an SMS is successfully delivered.

您现在可以通过在Eclipse中按F11来测试应用程序.要将SMS消息从一个仿真器实例发送到另一个仿真器实例,只需通过转到SDK的Tools文件夹并运行Emulator.exe来启动另一个Android仿真器实例.

You can now test the application by pressing F11 in Eclipse. To send an SMS message from one emulator instance to another, simply launch another instance of the Android emulator by going to the Tools folder of the SDK and running Emulator.exe.

图3显示了如何从一个仿真器向另一个仿真器发送SMS消息.只需使用目标仿真器的端口号(显示在窗口的左上角)作为其电话号码. SMS发送成功后,将显示"SMS已发送"消息.成功交付后,它将显示"SMS已交付"消息.请注意,使用模拟器进行测试时,如果成功发送了SMS,则不会出现"SMS delivery"消息.这仅适用于真实设备.

Figure 3 shows how you can send an SMS message from one emulator to another; simply use the target emulator’s port number (shown in the top left corner of the window) as its phone number. When an SMS is sent successfully, it will display a "SMS sent" message. When it is successfully delivered, it will display a "SMS delivered" message. Note that for testing using the emulator, when an SMS is successfully delivered, the "SMS delivered" message does not appear; this only works for real devices.

图4显示了在收件人仿真器上收到的SMS消息.该消息首先出现在通知栏(屏幕顶部)中.向下拖动通知栏将显示收到的消息.要查看整个消息,请单击消息.

Figure 4 shows the SMS message received on the recipient emulator. The message first appeared in the notification bar (top of the screen). Dragging down the notification bar reveals the message received. To view the entire message, click on the message.

如果您不想自己发送短信的麻烦,可以使用Intent对象来帮助您发送短信.以下代码显示了如何调用内置的SMS应用程序来帮助您发送SMS消息:

If you do not want to go through all the trouble of sending the SMS message yourself, you can use an Intent object to help you send an SMS message. The following code shows how you can invoke the built-in SMS application to help you send an SMS message:

Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "Content of the SMS goes here..."); 
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);

图5显示了为发送SMS消息而调用的内置SMS应用程序.

Figure 5 shows the built-in SMS application invoked to send the SMS message.

除了以编程方式发送SMS消息外,您还可以使用BroadcastReceiver对象拦截传入的SMS消息.

Besides programmatically sending SMS messages, you can also intercept incoming SMS messages using a BroadcastReceiver object.

要查看如何从Android应用程序中接收SMS消息,请在AndroidManifest.xml文件中添加元素,以便SmsReceiver类可以拦截传入的SMS消息:

To see how to receive SMS messages from within your Android application, in the AndroidManifest.xml file add the element so that incoming SMS messages can be intercepted by the SmsReceiver class:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="net.learn2develop.SMSMessaging"
      android:versionCode="1"
      android:versionName="1.0.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SMS"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>        

        <receiver android:name=".SmsReceiver"> 
            <intent-filter> 
                <action android:name=
                    "android.provider.Telephony.SMS_RECEIVED" /> 
            </intent-filter> 
        </receiver>

    </application>
    <uses-permission android:name="android.permission.SEND_SMS">
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>
</manifest>

在您的项目中添加一个新的类文件,并将其命名为SmsReceiver.java(参见图6).

Add a new class file to your project and name it as SmsReceiver.java (see Figure 6).

在SmsReceiver类中,扩展BroadcastReceiver类并重写onReceive()方法:

In the SmsReceiver class, extend the BroadcastReceiver class and override the onReceive() method:

package net.learn2develop.SMSMessaging;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class SmsReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) 
       {    
    }
}

当收到SMS消息时,将调用onCreate()方法. SMS消息通过Bundle对象包含并附加到Intent对象(intent – onReceive()方法中的第二个参数).消息以PDU格式存储在对象数组中.要提取每条消息,请使用SmsMessage类中的静态createFromPdu()方法.然后使用Toast类显示SMS消息:

When SMS messages are received, the onCreate() method will be invoked. The SMS message is contained and attached to the Intent object (intent – the second parameter in the onReceive() method) via a Bundle object. The messages are stored in an Object array in the PDU format. To extract each message, you use the static createFromPdu() method from the SmsMessage class. The SMS message is then displayed using the Toast class:

package net.learn2develop.SMSMessaging;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;
        String str = "";            
        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]);                
                str += "SMS from " + msgs[i].getOriginatingAddress();                     
                str += " :";
                str += msgs[i].getMessageBody().toString();
                str += "n";        
            }
            //---display the new SMS message---
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        }                         
    }
}

就是这样!要测试该应用程序,请在Eclipse中按F11.将应用程序部署到每个Android模拟器.图7显示了Eclipse,其中显示了当前正在运行的仿真器.您需要做的就是选择每个仿真器,然后将应用程序部署到每个仿真器上.

That’s it! To test the application, press F11 in Eclipse. Deploy the application to each Android emulator. Figure 7 shows Eclipse showing the emulators currently running. All you need to do is to select each emulator and deploy the application onto each one.

图8显示,当您将SMS消息发送到另一个仿真器实例(端口号5556)时,目标仿真器接收到该消息,并通过Toast类显示该消息.

Figure 8 shows that when you send an SMS message to another emulator instance (port number 5556), the message is received by the target emulator and displayed via the Toast class.

这篇关于如何从Android应用发送和接收短信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆