监听器类
package com.crazyit.ui.viewlistener;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
/**
* 作者:Gaao on 2016/6/5 20:56
* <p/>
* 邮箱:xjs250@163.com
*/
public class SendSmsListener implements View.OnLongClickListener {
private Activity act;
private EditText address;
private EditText content;
public SendSmsListener(Activity act,EditText address,EditText content) {
this.act = act;
this.address = address;
this.content = content;
}
@Override
public boolean onLongClick(View v) {
String addressStr = address.getText().toString().trim();
String contentStr = address.getText().toString();
//获取短信管理器
SmsManager smsManager = SmsManager.getDefault();
//创建发送短信的 PendingIntent
PendingIntent sentIntent = PendingIntent.getBroadcast(act,0,new Intent(),0);
//发送文本内容
smsManager.sendTextMessage(addressStr,null,contentStr,sentIntent,null);
Toast.makeText(act, "短信发送完成", Toast.LENGTH_SHORT).show();
return false;
}
}
Activity
package com.crazyit.ui.viewlistener;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
public class SendSmsActivity extends AppCompatActivity {
private EditText address;
private EditText content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_sms);
address = (EditText) findViewById(R.id.address);
content = (EditText) findViewById(R.id.content);
Button btn = (Button) findViewById(R.id.send);
btn.setOnLongClickListener(new SendSmsListener(this,address,content));
}
}
布局文件
<?xml version="1.0" encoding="utf-8"?>
<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="com.crazyit.ui.viewlistener.SendSmsActivity">
<EditText
android:id="@+id/address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入电话号码" />
<EditText
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入短信内容" />
<Button
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="发送" />
</LinearLayout>
发送短信时 要在清单文件中加上发送短信的权限
在 加入权限
发短信相关的权限
<!-- 发送消息-->
<uses-permission android:name="android.permission.SEND_SMS"/>
<!-- 阅读消息-->
<uses-permission android:name="android.permission.READ_SMS"/>
<!-- 写入消息-->
<uses-permission android:name="android.permission.WRITE_SMS" />
<!-- 接收消息 -->
<uses-permission android:name="android.permission.RECEIVE_SMS" />