22.系統廣播-短信

一.簡介


二.案例(發送短信)(具體實現代碼如下)

注意:安裝到手機上的項目要給它的權限設置爲允許,不然發不了短信哦。

系統的廣播在有些手機上可能收不到

MySMS.java

package com.zking.android22_sms;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

/**
 * Created by Administrator on 2017/7/13 0013.
 */

public class MySMS extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if("android.provider.Telephony.SMS_RECEIVED".equals(intent.getAction())){
            Log.i("test","收到短信了");
            //拿到短信的內容
            Bundle bundle=intent.getExtras();
            Object object[]= (Object[]) bundle.get("pdus");//鍵pdus不能隨便寫
            //讀取短信的內容用SmsMessage  一個SmsMessage代表一條信息
            SmsMessage smsMessage[]=new SmsMessage[object.length];
            for (int i = 0; i < object.length; i++) {
                smsMessage[i]=SmsMessage.createFromPdu((byte[])object[i]);//強轉爲字節數組byte
            }
            //拿消息
            for (SmsMessage message : smsMessage) {
                String address=message.getOriginatingAddress();//誰發的
                String body=message.getDisplayMessageBody();//短信的內容
                Log.i("test",address+":"+body);//打印
            }
        }
    }
}
AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zking.android22_sms">

   <!-- 權限-->
    <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>

    <application android:allowBackup="true" android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true" android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!--配置-->
        <receiver android:name=".MySMS">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
            </intent-filter>
        </receiver>

    </application>

</manifest>

執行效果:



以下知識瞭解一下:






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章