如何从Android应用程序发送和接收短信?

kai*_*uki 35 sms android android-contacts

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

谢谢

Sha*_*nak 45

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

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

希望Androider和我的回答完善你的答案!

更新:由于上面的链接已经死了:

免责声明: 我没有写过原始文章.我只是在这里复制它.根据文章的原始作者是weimenglee.我在这里复制文章是因为在几年前发布原始链接后,链接现在已经死了.

如何发送短信

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

图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>
Run Code Online (Sandbox Code Playgroud)

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

<?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>
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

接下来,在SMS活动中,我们连接Button视图,以便当用户点击它时,我们将检查在我们使用sendSMS()函数发送消息之前输入收件人的电话号码和消息,我们将很快定义:

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();
            }
        });        
    }    
}
Run Code Online (Sandbox Code Playgroud)

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);        
    }    
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

// ---向另一台设备发送短信--- 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);        
Run Code Online (Sandbox Code Playgroud)

}

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

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

在此输入图像描述

图3显示了如何从一个模拟器向另一个模拟器发送SMS消息; 只需使用目标模拟器的端口号(显示在窗口的左上角)作为其电话号码.成功发送短信后,将显示"短信已发送"消息.成功交付后,将显示"已发送短信"消息.请注意,对于使用模拟器进行测试,当成功传送SMS时,不会出现"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);
Run Code Online (Sandbox Code Playgroud)

图5显示了调用以发送SMS消息的内置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>
Run Code Online (Sandbox Code Playgroud)

将新类文件添加到项目中,并将其命名为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) 
       {    
    }
}
Run Code Online (Sandbox Code Playgroud)

收到SMS消息时,onCreate()将调用该方法.SMS消息包含并通过对象附加到Intent对象(intent - 方法中的第二个参数onReceive())Bundle.消息以PDU格式存储在Object数组中.要提取每条消息,请使用类中的静态createFromPdu()方法SmsMessage.然后使用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();
        }                         
    }
}
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

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

在此输入图像描述


小智 13

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

希望这是你正在寻找的.


Ish*_*era 7

尝试本教程发送短信.希望这可以帮助.

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

在活动文件中添加以下方法,您需要在其中实现"发送SMS"功能.

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

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

在活动的xml布局中添加一个按钮,并在Button click事件上调用sendSMSMessage方法.

Button.setOnClickListener(new View.OnClickListener() {
  public void onClick(View view) {
    sendSMSMessage();
   }
 });
Run Code Online (Sandbox Code Playgroud)

在Manifest.xml中添加以下权限.

<uses-permission android:name="android.permission.SEND_SMS"/>
Run Code Online (Sandbox Code Playgroud)