Android开发入门之发送短信

第一步:新建一个Android工程命名为03.Sms目录结构如下图:

Android开发入门之发送短信_第1张图片


第二步:修改activity_main.xml布局文件代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/sms_phone" />

    <EditText
        android:id="@+id/et_phone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="phone" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/sms_content" />

    <EditText
        android:id="@+id/et_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:lines="3" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="send"
        android:text="@string/send" />

</LinearLayout>


strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">03.Sms</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="sms_phone">手机号码</string>
    <string name="sms_content">短信内容</string>
    <string name="send">发送</string>

</resources>

第三步:编写MianActivity类:

package cn.leigo.sms;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	private EditText mPhoneEditText;
	private EditText mContentEditText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mPhoneEditText = (EditText) findViewById(R.id.et_phone);
		mContentEditText = (EditText) findViewById(R.id.et_content);
	}

	public void send(View v) {
		String phone = mPhoneEditText.getText().toString();
		String content = mContentEditText.getText().toString();
		SmsManager smsManager = SmsManager.getDefault();
		ArrayList<String> texts = smsManager.divideMessage(content);
		for (String text : texts) {
			smsManager.sendTextMessage(phone, null, text, null, null);
		}

		Toast.makeText(this, "发送成功!", Toast.LENGTH_SHORT).show();
	}

}

最后在AndroidManifest.xml文件中添加权限:

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

运行工程查看效果图:

Android开发入门之发送短信_第2张图片

Android开发入门之发送短信_第3张图片

Android开发入门之发送短信_第4张图片


你可能感兴趣的:(sms,发送短信)