Android接收和傳送簡訊

來源:互聯網
上載者:User

標籤:

每一部手機都具有簡訊接收和發送功能,下面我們通過代碼來實現接收和傳送簡訊功能。

一、接收簡訊

1、建立內部廣播接收器類,接收系統發出的簡訊廣播
2、從獲得的內容中解析出簡訊寄件者和簡訊內容
3、在Activity中註冊廣播
4、添加接收簡訊許可權

下面放上具體的代碼

activity_main.xml檔案用於顯示簡訊寄件者號碼和顯示簡訊內容

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <TextView        android:id="@+id/sms_from"        android:layout_width="wrap_content"        android:layout_height="20dp"        android:text="From" />    <TextView        android:id="@+id/sms_from_txt"        android:layout_width="wrap_content"        android:layout_height="20dp"        android:layout_marginLeft="15dp"        android:layout_toRightOf="@id/sms_from"/>    <TextView        android:id="@+id/sms_content"        android:layout_width="wrap_content"        android:layout_height="20dp"        android:layout_below="@id/sms_from"        android:layout_marginTop="20dp"        android:text="Content" />    <TextView        android:id="@+id/sms_content_txt"        android:layout_width="wrap_content"        android:layout_height="20dp"        android:layout_marginLeft="15dp"        android:layout_marginTop="20dp"        android:layout_below="@id/sms_from_txt"        android:layout_toRightOf="@id/sms_content"/></RelativeLayout>

MainActivity.java檔案

public class MainActivity extends AppCompatActivity {    private TextView fromTv;    private TextView contentTv;    private IntentFilter intentFilter;    private MessageReceiver messageReceiver;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initView();        getSms();    }    private void getSms() {        intentFilter = new IntentFilter();                                 intentFilter.addAction("android.provider.Telephony.SMS_RECEIVER");        messageReceiver = new MessageReceiver();        //設定較高的優先順序        intentFilter.setPriority(100);        registerReceiver(messageReceiver, intentFilter);    }    private void initView() {        fromTv = (TextView) findViewById(R.id.sms_from_txt);        contentTv = (TextView) findViewById(R.id.sms_content_txt);    }    @Override    protected void onDestroy() {        super.onDestroy();        unregisterReceiver(messageReceiver);    }    class MessageReceiver extends BroadcastReceiver {        @Override        public void onReceive(Context context, Intent intent) {            Bundle bundle = intent.getExtras();            //提取簡訊訊息            Object[] pdus = (Object[]) bundle.get("pdus");            SmsMessage[] messages = new SmsMessage[pdus.length];            for (int i = 0; i < messages.length; i++) {                messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);            }            //擷取發送方號碼            String address = messages[0].getOriginatingAddress();            String fullMessage = "";            for (SmsMessage message : messages) {                //擷取簡訊內容                fullMessage += message.getMessageBody();            }            //截斷廣播,阻止其繼續被Android內建的簡訊程式接收到            abortBroadcast();            fromTv.setText(address);            contentTv.setText(fullMessage);        }    }}

註:註冊的廣播接收器,一定要在OnDestroy()方法中取消註冊。

由於簡訊廣播是有序廣播,如果我們不想讓Android內建的簡訊程式接收到簡訊,就可以設定我們自身接收器的優先順序,同時在我們接受完廣播後將廣播截斷,阻止其被Android內建的簡訊程式接收到。

二、傳送簡訊

1、擷取接收者的號碼和簡訊內容
2、獲得簡訊發送管理執行個體
3、構造PendingIntent啟動簡訊發送狀態監控廣播
4、調用傳送簡訊函數,傳入參數傳送簡訊
5、構造廣播接收器內部類監控簡訊是否發送成功
6、獲得廣播接收器執行個體和IntentFilter執行個體,註冊廣播接收器
7、在onDestroy()中取消註冊的廣播接收器
8、在AndroidManifest.xml檔案中加入簡訊發送許可權

下面放上具體的布局檔案和代碼

activity_send_msg.xml檔案

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <EditText        android:id="@+id/to_ed"        android:layout_width="match_parent"        android:layout_height="50dp"        android:hint="to"/>    <EditText        android:id="@+id/to_content"        android:layout_width="match_parent"        android:layout_height="50dp"        android:layout_below="@id/to_ed"        android:hint="content"/>    <Button        android:id="@+id/send_msg"        android:layout_width="match_parent"        android:layout_height="50dp"        android:layout_below="@id/to_content"        android:text="@string/send_message"/></RelativeLayout>

SendMsgActivity.java檔案

public class SendMsgActivity extends AppCompatActivity implements View.OnClickListener {    private Context context;    private EditText toEdit;    private EditText toContent;    private IntentFilter sendFilter;    private SendStatusReceiver sendStatusReceiver;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_send_msg);        context = this;        initView();    }    private void initView() {        toEdit = (EditText) findViewById(R.id.to_ed);        toContent = (EditText) findViewById(R.id.to_content);        //添加發送按鈕的點擊監聽事件        Button sendMsg = (Button) findViewById(R.id.send_msg);        sendMsg.setOnClickListener(this);    }    @Override    public void onClick(View view) {        switch (view.getId()){            case R.id.send_msg:                sendMessage();             break;            default:                break;        }    }    private void sendMessage() {        //擷取簡訊接收者號碼        String to = toEdit.getText().toString();        //擷取傳送簡訊內容        String content = toContent.getText().toString();        //獲得廣播接收器執行個體和IntentFilter執行個體        sendStatusReceiver = new SendStatusReceiver();        sendFilter = new IntentFilter();        sendFilter.addAction("SENT_SMS_ACTION");        //註冊廣播監聽        registerReceiver(sendStatusReceiver, sendFilter);        //構造PendingIntent啟動簡訊發送狀態監控廣播        Intent sendIntent = new Intent("SENT_SMS_ACTION");        PendingIntent pi = PendingIntent.getBroadcast(context, 0, sendIntent, 0);        //獲得簡訊管理執行個體        SmsManager smsManager = SmsManager.getDefault();        //調用傳送簡訊函數,傳入參數傳送簡訊(第一、三、四參數依次為接收者號碼,簡訊內容,簡訊發送狀態監控的PendingIntent)        smsManager.sendTextMessage(to, null, content, pi, null);    }    /**     * 構造廣播接收器內部類監控簡訊是否發送成功     */    class SendStatusReceiver extends BroadcastReceiver{        @Override        public void onReceive(Context context, Intent intent) {            if (getResultCode() == RESULT_OK){                Toast.makeText(context, "successful", Toast.LENGTH_SHORT).show();            }else{                Toast.makeText(context, "failed", Toast.LENGTH_SHORT).show();            }        }    }    @Override    protected void onDestroy() {        super.onDestroy();        //取消註冊的廣播        unregisterReceiver(sendStatusReceiver);    }}

在AndroidManifest.xml檔案中加入簡訊發送許可權

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

Android接收和傳送簡訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.