如何从Android应用发送和接收短信? [关闭]

问题描述 投票:35回答:3

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

谢谢

android sms android-contacts
3个回答
45
投票

这是逐步显示如何从Android应用程序发送SMS的教程。

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

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

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

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

如何发送短信

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

Figure 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>

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>

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

enter image description here

[接下来,在SMS活动中,我们连接了Button视图,以便当用户单击它时,在使用[C0发送消息之前,我们将检查接收者的电话号码和消息是否已输入。 ]函数,稍后将对其进行定义:

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(); } }); } } 功能定义如下:

sendSMS()

要发送SMS消息,请使用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); } } 类。与其他类不同,您不直接实例化此类。相反,您将调用SmsManager静态方法来获取getDefault()对象。 SmsManager方法发送带有sendTextMessage()的SMS消息。

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

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

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); } 对象(sentPI)监视发送过程。发送SMS消息后,将触发第一个BroadcastReceiver的onReceive事件。您可以在此处检查发送过程的状态。第二个PendingIntent对象(deliveredPI)监视交付过程。成功发送SMS时,将触发第二个BroadcastReceiver的PendingIntent事件。

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

Emulator.exe

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

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

enter image description here

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

enter image description here

图5显示了为发送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);

接收短信]

除了以编程方式发送SMS消息之外,您还可以使用enter image description here对象来拦截传入的SMS消息。

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

SmsReceiver

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

<?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类中,扩展BroadcastReceiver类并覆盖onReceive()方法:

enter image description here

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

Toast

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

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

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

enter image description here

这里是有关如何将联系人加载到您的应用程序中的信息的链接:enter image description here

希望这是您想要的。

尝试使用本教程发送短信。希望这会有所帮助。

http://developer.android.com/guide/topics/providers/content-providers.html

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

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

您将需要导入android.telephony.SmsManager

来实现sendSMSMessage方法。

向活动的xml布局添加按钮,并在Button单击事件上调用sendSMSMessage方法。

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

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

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

13
投票

这里是有关如何将联系人加载到您的应用程序中的信息的链接:enter image description here


7
投票

尝试使用本教程发送短信。希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.