android发送短信样例

Android应用开发中我们经常须要发送手机短信。这对于android平台来说,是最简单只是的功能了,无需太多代码,也无需自己定义代码,仅仅须要调用android提供的消息管理类SmsManager就能够了。

【源代码下载】http://www.code4apk.com/android-code/202

核心就是使用SmsManager的sendTextMessage方法加上PendingIntent跳转。

核心代码例如以下:

SmsManager sms=SmsManager.getDefault();

PendingIntent  intent=PendingIntent.getBroadcast(MainActivtiy.this,0, new Intent(), 0);

sms.sendTextMessage(phone.getText().toString(), null, text.getText().toString(), intent, null);


以下一起来实现这个功能:

第1步:新建一个activity MainActivtiy

import android.app.Activity;

import android.app.PendingIntent;

import android.content.Intent;

import android.os.Bundle;

import android.telephony.SmsManager;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

public class MainActivtiy extends Activity {

EditText text;

EditText phone;

Button send;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

send=(Button)findViewById(R.id.send);

text=( EditText)findViewById(R.id.text);

phone=( EditText)findViewById(R.id.phone);

send.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

SmsManager sms=SmsManager.getDefault();

PendingIntent  intent=PendingIntent.getBroadcast(MainActivtiy.this,0, new Intent(), 0);

sms.sendTextMessage(phone.getText().toString(), null, text.getText().toString(), intent, null);

Toast.makeText( MainActivtiy.this, "发送成功.....", Toast.LENGTH_LONG).show();

}
});
}
}


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" > <EditText android:id="@+id/phone" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="请输入电话号码" android:inputType="phone" android:text="" > </EditText> <EditText android:id="@+id/text" android:inputType="text" android:hint="请输入消息" android:layout_width="fill_parent" android:layout_height="wrap_content" > </EditText> <Button android:id="@+id/send" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="发送消息" > </Button> </LinearLayout>



3步:在配置文件AndroidManifest.xml中加入发送短信支持

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


第4步调试执行:

android发送短信

【源代码下载】http://www.code4apk.com/android-code/202

posted @ 2017-04-19 14:17  jhcelue  阅读(158)  评论(0编辑  收藏  举报