【问题标题】:How to send and receive SMS from android app? [closed]如何从安卓应用发送和接收短信? [关闭]
【发布时间】:2011-10-15 17:53:29
【问题描述】:

我想在我的应用程序中添加短信发送功能,并且还想要用户可以直接从应用程序从联系人列表中选择联系人的选项。有没有办法可以将联系人列表与我的应用程序集成。

谢谢

【问题讨论】:

  • Send SMS in android 的可能重复项
  • @BradLarson:这个问题是那个问题的 exact opposite (尽管除第一个答案之外的所有答案都是这个问题的真正答案)。

标签: android sms android-contacts


【解决方案1】:

这里有一个教程,逐步展示如何从 Android 应用发送短信。

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

希望 Androider 和我的回答能完善您的回答!

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

免责声明: 我没有写原始文章。我只是在这里复制它。文章原作者为weimenglee。我在这里复制这篇文章是因为几年前发布了原始链接后,该链接现在已经失效了。

如何发送短信

要开始使用,首先启动 Eclipse 并创建一个新的 Android 项目。为项目命名,如图 1 所示。

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

AndroidManifest.xml文件中,添加两个权限——SEND_SMSRECEIVE_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 文件中,添加以下代码,以便用户可以输入电话号码以及要发送的消息:

<?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。

接下来,在 SMS 活动中,我们连接 Button 视图,以便当用户单击它时,我们将在使用 @ 发送消息之前检查是否输入了收件人的电话号码和消息987654347@ 函数,我们稍后会定义:

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 消息。

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

如果需要监控短信发送过程的状态,其实可以使用两个PendingIntent对象和两个BroadcastReceiver对象,像这样:

//---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) 监控交付过程。第二个 BroadcastReceiver 的 onReceive 事件将在 SMS 成功发送时触发。

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

图 3 显示了如何将 SMS 消息从一个模拟器发送到另一个模拟器;只需使用目标模拟器的端口号(显示在窗口的左上角)作为其电话号码。短信发送成功后,会显示“短信已发送”信息。发送成功后,会显示“短信已发送”消息。请注意,使用模拟器进行测试时,当短信发送成功时,不会出现“短信已发送”消息;这仅适用于真实设备。

图 4 显示了接收方模拟器上收到的 SMS 消息。该消息首先出现在通知栏(屏幕顶部)中。向下拖动通知栏会显示收到的消息。要查看整条消息,请单击该消息。

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

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 应用程序。

接收短信

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

要查看如何从您的 Android 应用程序中接收 SMS 消息,请在 AndroidManifest.xml 文件中添加元素,以便 SmsReceiver 类可以拦截传入的 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>        

        <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)。

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

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) 
       {    
    }
}

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

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,显示了当前正在运行的仿真器。您需要做的就是选择每个模拟器并将应用程序部署到每个模拟器上。

图 8 显示,当您向另一个模拟器实例(端口号 5556)发送 SMS 消息时,该消息被目标模拟器接收并通过 Toast 类显示。

【讨论】:

  • 链接无效。这就是为什么 stackoverflow 要求添加原始答案而不是提供链接。
  • @MahendranSakkarai 感谢您引起我的注意,我已从此处的原始链接中复制了这篇文章。
  • 发送短信时注册的广播接收器什么时候取消注册?以及如何?
  • 链接再次工作。但奇怪的是,它说有 46 个 cmets,但它只显示了 20 个。
【解决方案2】:

这是一个链接,其中包含如何将联系人加载到您的应用中的信息: http://developer.android.com/guide/topics/providers/content-providers.html

希望这就是你要找的。​​p>

【讨论】:

  • Stack Overflow 不鼓励仅链接答案。
【解决方案3】:

试试这个教程发送短信。希望这会有所帮助。

http://www.tutorialspoint.com/android/android_sending_sms.htm

在您需要实现“发送短信”功能的活动文件中添加以下方法。

protected void sendSMSMessage() {

  String phoneNo = txtphoneNo.getText().toString();
  String message = txtMessage.getText().toString();

  try {
     SmsManager smsManager = SmsManager.getDefault();
     smsManager.sendTextMessage(phoneNo, null, message, null, null);
     Toast.makeText(getApplicationContext(), "SMS sent.",
     Toast.LENGTH_LONG).show();
  } catch (Exception e) {
     Toast.makeText(getApplicationContext(),
     "SMS faild, please try again.",
     Toast.LENGTH_LONG).show();
     e.printStackTrace();
  }
}

您需要导入 android.telephony.SmsManager 来实现 sendSMSMessage 方法。

将一个按钮添加到您的活动的 xml 布局中,并在按钮单击事件上调用 sendSMSMessage 方法。

Button.setOnClickListener(new View.OnClickListener() {
  public void onClick(View view) {
    sendSMSMessage();
   }
 });

在您的 Manifest.xml 中添加以下权限。

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

【讨论】:

  • 这对我不起作用。
  • 您收到的错误是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-26
  • 2011-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多