现在的位置: 首页 > 综合 > 正文

Android 程式开发:(廿一)消息传递 —— 21.1 通过编码实现发送短信

2013年07月30日 ⁄ 综合 ⁄ 共 1915字 ⁄ 字号 评论关闭

1. 创建工程,SMS。

2. 修改main.xml中的代码。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<Button
    android:id="@+id/btnSendSMS"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Send SMS"
    android:onClick="onClick" />


</LinearLayout>

3. 在AndroidManifest.xml中添加权限。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.manoel.SMS"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".SMSActivity" 
            android:launchMode="singleTask" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />                
                <category android:name="android.intent.category.LAUNCHER" />
                        
                
            </intent-filter>
        </activity>

    </application>

</manifest>

4. 在SMSActivity.java中添加一些测试代码。

public class SMSActivity extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}

	public void onClick(View v) {
		sendSMS("130xxxxxxxx", "Hello my friends!");
	}


	//sends an SMS message to another device
	private void sendSMS(String phoneNumber, String message)
	{
		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
	}
}

5. 测试。

例子很简单,下面主要介绍发送短信的方法。

	private void sendSMS(String phoneNumber, String message)
	{
		SmsManager sms = SmsManager.getDefault();
		sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
	}

首先获得SmsManager的对象,然后调用sendTextMessage接口。

  • destinationAddress - 接收人的电话号码
  • scAddress - 服务中心的地址,传入null使用默认的SMSC
  • text - 短信的内容
  • sentIntent - 当短信被发送,调用这个PendingIntet对象
  • deliveryIntent - 当短信被送达,调用这个PendingIntent对象

抱歉!评论已关闭.