Android发送短信并监测发送状态

Android发送短信功能,直接上代码

1、java类 Operation3GActivity.java
package com.jinlinbao.logisticsbox.ui.logisticsComm;

import android.app.Activity;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.jinlinbao.logisticsbox.R;
import com.jinlinbao.logisticsbox.ui.BaseActivity;
import com.jinlinbao.logisticsbox.utils.DialogUtil;

/**
 * Created by jsj on 15/9/9.
 * 3G操作测试类
 */
public class Operation3GActivity extends BaseActivity {

    private EditText et_phone;
    private EditText et_content;
    private TextView tv_count;
    private Button btn_send;

    private String phone;
    private String content;
    private Dialog dialog;

    private mServiceReceiver mReceiver01;

    //自定义action参数,作为广播的识别常数
    private static String SMS_SEND_ACTION = "SMS_SEND_AC" +
            "TION";
    //提示信息
    private String hintMsg = "提示信息";
    //是否发送成功
    private boolean isSendSuccess = false;

    @Override
    protected void initUI() {
        setContentView(R.layout.activity_operation_3g);

        et_phone = (EditText) findViewById(R.id.et_phone);
        et_content = (EditText) findViewById(R.id.et_content);
        tv_count = (TextView) findViewById(R.id.tv_count);
        btn_send = (Button) findViewById(R.id.btn_send);

        //电话号码改变事件
        et_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //如果第一个数字为0,将不允许记录
                String phone = et_phone.getText().toString().trim();
                if (phone.length() == 1 && (Integer.parseInt(phone) == 0 || Integer.parseInt(phone) != 1)) {
                    et_phone.setText("");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        //短信内容改变事件
        et_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //已经输入的短信内容计数
                String content = et_content.getText().toString();
                int length = content.length();
                tv_count.setText(length + "/70");
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        //发送按钮点击监听事件
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phone = et_phone.getText().toString().trim();
                content = et_content.getText().toString().trim();
                if (validate(phone, content)) {
                    SmsManager smsManager = SmsManager.getDefault();
                    try {
                        Intent itSend = new Intent(SMS_SEND_ACTION);

                        PendingIntent mSendPI = PendingIntent.getBroadcast(getApplicationContext(), 0, itSend, 0);
                        smsManager.sendTextMessage(phone, null, content, mSendPI, null);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    protected void initData() {
        title = getIntent().getStringExtra("title");
        setTitle(title);
    }

    //自定义mServiceReceiver重写BroadcastReceiver监听短信状态信息
    public class mServiceReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(SMS_SEND_ACTION)) {
                try {
                    switch (getResultCode()) {
                        case Activity.RESULT_OK:
                            hintMsg = "短信发送成功";
                            isSendSuccess = true;
                            break;
                        case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                            hintMsg = "短信发送失败";
                            isSendSuccess = false;
                            break;
                    }
                    dialog = new DialogUtil().createDialog(Operation3GActivity.this, "提示", hintMsg, false, new DialogUtil.OnButtonListener() {
                        @Override
                        public void enterButton() {
                            dialog.dismiss();
                            if (isSendSuccess) {
                                et_phone.setText("");
                                et_content.setText("");
                            }
                        }

                        @Override
                        public void cancelButton() {
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 验证号码和内容
     *
     * @param phone
     * @param content
     * @return
     */
    private boolean validate(String phone, String content) {
        boolean bool = true;
        if (validateSimCard()) {
            if (phone.length() == 0) {
                alert("电话号码不能为空!");
                bool = false;
            } else if (phone.length() < 11) {
                alert("电话号码输入错误,请重新输入!");
                bool = false;
            } else if (content.length() == 0) {
                alert("短信内容不能为空!");
                bool = false;
            }
        }
        return bool;
    }

    /**
     * 验证sim状态
     * @return
     */
    private boolean validateSimCard() {
        TelephonyManager manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        switch (manager.getSimState()) {
            case TelephonyManager.SIM_STATE_READY:
                return true;
            case TelephonyManager.SIM_STATE_ABSENT:
                alert("请插入sim卡");
                return false;
            default:
                alert("sim卡被锁定或未知状态");
                return false;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter mFilter = new IntentFilter(SMS_SEND_ACTION);
        mReceiver01 = new mServiceReceiver();
        registerReceiver(mReceiver01, mFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver01);
    }
}
 
2、布局文件 activity_operation_3g.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/header" />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="80dp">

        <TextView
            android:id="@+id/tv_phone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="204dp"
            android:text="手机号:"
            android:textColor="@color/color_7d7d7d"
            android:textSize="@dimen/text_size_16" />

        <EditText
            android:id="@+id/et_phone"
            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/ll_content"
            android:layout_toRightOf="@id/tv_phone"
            android:background="@drawable/border_black"
            android:hint="请输入11位手机号"
            android:inputType="number"
            android:maxLength="11"
            android:padding="10dp"
            android:textColor="@color/font_prompt"
            android:textSize="@dimen/text_size_14" />

        <TextView
            android:id="@+id/tv_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/tv_phone"
            android:layout_marginLeft="204dp"
            android:layout_marginTop="46dp"
            android:text="短信内容:"
            android:textColor="@color/color_7d7d7d"
            android:textSize="@dimen/text_size_16" />

        <RelativeLayout
            android:id="@+id/ll_content"
            android:layout_width="400dp"
            android:layout_height="170dp"
            android:layout_below="@id/tv_phone"
            android:layout_marginLeft="32dp"
            android:layout_marginTop="46dp"
            android:layout_toRightOf="@id/tv_content"
            android:background="@drawable/border_black">

            <EditText
                android:id="@+id/et_content"
                android:layout_width="342dp"
                android:layout_height="148dp"
                android:background="@null"
                android:gravity="top"
                android:hint="请输入短信内容,不要超过70个汉字"
                android:maxLength="70"
                android:padding="10dp"
                android:textColor="@color/font_prompt"
                android:textSize="@dimen/text_size_14" />

            <TextView
                android:id="@+id/tv_count"
                android:layout_width="50dp"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="20dp"
                android:paddingBottom="5dp"
                android:text="0/70"
                android:textColor="@color/font_prompt"
                android:textSize="@dimen/text_size_14" />
        </RelativeLayout>

    </RelativeLayout>

    <Button
        android:id="@+id/btn_send"
        android:layout_width="160dp"
        android:layout_height="40dp"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="432dp"
        android:layout_marginTop="84dp"
        android:background="@drawable/button_green_selector"
        android:text="发送"
        android:textColor="@color/color_fff"
        android:textSize="@dimen/text_size_18" />

</LinearLayout>

3、清单文件
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值