andriod-四大組件之廣播Broadcast-短信的收發(fā)

我想幾乎所有的安卓開發(fā)者,第一個接觸到的四大組件之一就是activity,而我在之前的文章中也寫過,

在activity里面getContext是大佬級別的存在(可以看前幾章),

那么四大組件中的廣播Broadcast對應著的靈外一個大佬級別的存在就是intent(意圖)。

當然一般這個intent可能會經過一些包裝,比如PendingIntent(這個是包裝過后的intent)


簡單的理解就是PendingIntent是延遲后的intent。

先不扯這些了,講正事!

Android中的廣播主要可以分為兩種類型:標準廣播和有序廣播

標準廣播

一種完全異步執(zhí)行的廣播,在廣播發(fā)出之后,所有的廣播接收器幾乎都會在同一時間接收到這條廣播,因此他們之間沒有任何的先后順序。

特點:效率高;缺點:無法攔截。

有序廣播

一種同步執(zhí)行的廣播,在廣播發(fā)出之后,同一時刻只會有一個廣播接收器能夠接收到這條廣播,當該廣播接收器執(zhí)行完OnReceive()方法邏輯后,廣播才會繼續(xù)傳遞。?

特點:優(yōu)先級高者會先接收到廣播,并且可以攔截該條廣播是否繼續(xù)傳遞。

注意點

有些廣播可以通過動態(tài)(java代碼)靜態(tài)(xml文件)方式任一種來注冊;

有些廣播則必須通過某一種方式來注冊,比如開機廣播必須通過xml方式來注冊,監(jiān)聽手機屏幕解鎖開鎖則必須通過java代碼來注冊。

示例

接收系統(tǒng)廣播

1,監(jiān)聽手機是否插入耳機廣播(動態(tài)注冊)

注冊代碼

intentFilter = new IntentFilter(); intentFilter.addAction("android.intent.action.HEADSET_PLUG");registerReceiver(myBrodcast, intentFilter);Toast.makeText(this, "監(jiān)聽耳機廣播已注冊", Toast.LENGTH_SHORT).show();


廣播接收器代碼

classMyBrodcastextendsBroadcastReceiver{@OverridepublicvoidonReceive(Context context, Intent intent) {if(null!= intent)

?{? ? ? ? ? ? ??

? String action = intent.getAction();

switch(action)?

{

case"android.intent.action.HEADSET_PLUG":

if(intent.hasExtra("state")) {if(intent.getIntExtra("state",0) ==0)?

{? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

? Log.e(TAG,"headset not connected");? ? ? ? ??

? ? ? ? ? ? ? ? ? }elseif(intent.getIntExtra("state",0) ==1)

?{? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

?Log.e(TAG,"headset connected");? ? ? ??

? ? ? ? ? ? ? ? ? ? }? ? ? ? ? ? ? ? ?

?? ? ? }break;? ? ? ? ??

? ? ? }? ? ? ??

? ? }? ??

? ? }? ?

?}

?發(fā)送自定義廣播

上面講的都是系統(tǒng)廣播,系統(tǒng)廣播需要注冊;而自定義廣播則需要人為發(fā)送。?

一般情況使用自定義廣播來實現某個功能,下面就來看個例子:接收到自定義廣播后,啟動一個界面。?


注冊代碼



點擊注冊代碼

Intent intent =newIntent("com.example.mu16jj.broadcastreceiver");? ? ? ? ? ? ? ? sendBroadcast(intent);


接收器代碼

case"com.example.mu16jj.broadcastreceiver":? ? ??

? ? ? ? ? ? ? Log.e(TAG,"我是自定義的");// 在廣播接收器中打開Activity? ? ? ? ? ? ? ?

?? ? Intent inten = new Intent(context, MainActivity.class);inten.addFlags(Intent.FLAG_ACTIVITY_NEW_TAS

K);

context.startActivity(inten);

break;

很明顯,自定義的廣播需要多一步點擊注冊代碼,但是問題不大


發(fā)送有序廣播

發(fā)送方式由原來的 sendBroadcast(intent) 改變?yōu)?sendOrderedBroadcast(intent, null),不同的應用注冊同一個廣播,那么這兩個(或者更多)都是可以接收到這條廣播的。

既然是有序廣播,那么這個順序的確定就由有一個屬性來確定,例如:

priority 數越大優(yōu)先級別越高,最大值是2147483647;優(yōu)先級別也可以調用 IntentFilter 對象的 setPriority() 方法進行設置。

當然也可以攔截,只需要在廣播接收器的 onReceive() 方法中調用下面一句代碼就可以實現:

abortBroadcast();


使用本地廣播

上面的有序廣播提到了不同的應用可以相互接受廣播,那么就存在一個安全問題,為此,Android 系統(tǒng)為我們提供了本地廣播管理器類 LocalBroadcastManager,使用它來負責應用中的廣播發(fā)送,就相對安全多了,實例化方式:

LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);

當然了,既然是管理器,那么發(fā)送和取消就自然由它負責。


你可以這樣的想廣播:把手機當成是學校,不同的應用就是不同的教室,不同的activity后者是其他的是里面的一個個學生,廣播相當于里面的喇叭

它可以發(fā)送信息,但是也只是發(fā)送信息,具體需要發(fā)生什么動作就看你怎么寫了。一般會使用BroadcastReceiver來進行回調。


介紹就介紹到這里了。接下來直接奔主題:

以下是效果圖:








------------------------------------------------------------------------------------SMS類--------------------------------------------------------------------------------------------------



package com.example.acer.mymusic.Activity;

import android.Manifest;

import android.app.Activity;

import android.app.PendingIntent;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.content.IntentFilter;

import android.os.Build;

import android.os.Bundle;

import android.telephony.SmsManager;

import android.view.View;

import android.view.Window;

import android.view.WindowManager;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import com.example.acer.mymusic.R;

import java.util.List;

public class SMSextends Activity

{

StringSENT_SMS_ACTION="SENT_SMS_ACTION";

StringDELIVERED_SMS_ACTION="DELIVERED_SMS_ACTION";

/** Called when the activity is first created. */

? ? @Override

? ? public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

///設置全屏操作

? ? ? ? requestWindowFeature(Window.FEATURE_NO_TITLE);

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

setContentView(R.layout.main);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

requestPermissions(new String[]{

Manifest.permission.SEND_SMS,

Manifest.permission.RECEIVE_SMS

? ? ? ? ? ? },2);

}

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

btn.setOnClickListener(new View.OnClickListener() {

public void onClick(View arg0) {

// TODO Auto-generated method stub

? ? ? ? ? ? ? ? EditText telNoText =(EditText)findViewById(R.id.telNo);

EditText contentText = (EditText)findViewById(R.id.content);

String telNo = telNoText.getText().toString();

String content = contentText.getText().toString();

if (validate(telNo, content))

{

sendSMS(telNo, content);

}else{

}

}

});

}

/**

* Send SMS

? ? * @param phoneNumber

? ? * @param message

? ? */

? ? private void sendSMS(String phoneNumber, String message)

{

//create the sentIntent parameter

? ? ? ? Intent sentIntent =new Intent(SENT_SMS_ACTION);

PendingIntent sentPI = PendingIntent.getBroadcast(this,0, sentIntent,

0);

// create the deilverIntent parameter

? ? ? ? Intent deliverIntent =new Intent(DELIVERED_SMS_ACTION);

PendingIntent deliverPI = PendingIntent.getBroadcast(this,0,

deliverIntent,0);

SmsManager sms = SmsManager.getDefault();

if (message.length() >70) {

List msgs = sms.divideMessage(message);

for (String msg : msgs) {

sms.sendTextMessage(phoneNumber,null, msg, sentPI, deliverPI);

}

}else {

sms.sendTextMessage(phoneNumber,null, message, sentPI, deliverPI);

}

Toast.makeText(SMS.this, R.string.message, Toast.LENGTH_LONG).show();

//register the Broadcast Receivers

? ? ? ? registerReceiver(new BroadcastReceiver(){

@Override

? ? ? ? ? ? ? ? ? ? ? ? ? ? public void onReceive(Context _context, Intent _intent)

{

switch(getResultCode()){

case Activity.RESULT_OK:

Toast.makeText(getBaseContext(),

"短信發(fā)送成功行動",

Toast.LENGTH_SHORT).show();

break;

case SmsManager.RESULT_ERROR_GENERIC_FAILURE:

Toast.makeText(getBaseContext(),

"SMS通用故障行為",

Toast.LENGTH_SHORT).show();

break;

case SmsManager.RESULT_ERROR_RADIO_OFF:

Toast.makeText(getBaseContext(),

"短信關閉故障動作",

Toast.LENGTH_SHORT).show();

break;

case SmsManager.RESULT_ERROR_NULL_PDU:

Toast.makeText(getBaseContext(),

"PDU短信零失效行為",

Toast.LENGTH_SHORT).show();

break;

}

}

},

new IntentFilter(SENT_SMS_ACTION));

registerReceiver(new BroadcastReceiver(){

@Override

? ? ? ? ? ? ? ? ? ? ? ? ? ? public void onReceive(Context _context,Intent _intent)

{

Toast.makeText(getBaseContext(),

"短信傳遞行動",

Toast.LENGTH_SHORT).show();

}

},

new IntentFilter(DELIVERED_SMS_ACTION));

}

public boolean validate(String telNo, String content){

if((null==telNo)||("".equals(telNo.trim()))){

Toast.makeText(this,"請輸入電話號碼",Toast.LENGTH_LONG).show();

return false;

}

if(!checkTelNo(telNo)){

Toast.makeText(this,"請輸入正確的電話號碼",Toast.LENGTH_LONG).show();

return false;

}

if((null==content)||("".equals(content.trim()))){

Toast.makeText(this,"請輸入信息內容",Toast.LENGTH_LONG).show();

return false;

}

return true;

}

public boolean checkTelNo(String telNo){

if("5556".equals(telNo)){

return true;

}else{

String reg ="^0{0,1}(13[0-9]|15[0-9])[0-9]{8}$";

return telNo.matches(reg);

}

}

}


---------------------------------------------------------------------------BroadCastTest2_SMS-------------------------------------------------------------------------------------



package com.example.acer.mymusic.BroadCast;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.os.Bundle;

import android.telephony.SmsMessage;

import android.widget.Toast;

import com.example.acer.mymusic.Activity.BroadCastActivity2_SMS;

public class BroadCastTest2_SMSextends BroadcastReceiver

{

/**

* 以BroadcastReceiver接收SMS短信

* */

? ? public static final StringACTION ="android.provider.Telephony.SMS_RECEIVED";

@Override

? ? public void onReceive(Context context, Intent intent)

{

// TODO Auto-generated method stub

? ? ? ? if (ACTION.equals(intent.getAction())) {

Intent i =new Intent(context, BroadCastActivity2_SMS.class);

i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

SmsMessage[] msgs =getMessageFromIntent(intent);

StringBuilder sBuilder =new StringBuilder();

if (msgs !=null && msgs.length >0 ) {

for (SmsMessage msg : msgs) {

sBuilder.append("接收到了短信:\n發(fā)件人是:");

sBuilder.append(msg.getDisplayOriginatingAddress());

sBuilder.append("\n------短信內容-------\n");

sBuilder.append(msg.getDisplayMessageBody());

i.putExtra("sms_address", msg.getDisplayOriginatingAddress());

i.putExtra("sms_body", msg.getDisplayMessageBody());

}

}

Toast.makeText(context, sBuilder.toString(), Toast.LENGTH_SHORT).show();

context.startActivity(i);

}

}

public static SmsMessage[] getMessageFromIntent(Intent intent)

{

SmsMessage retmeMessage[] =null;

Bundle bundle = intent.getExtras();

Object pdus[] = (Object[]) bundle.get("pdus");

retmeMessage =new SmsMessage[pdus.length];

for (int i =0; i < pdus.length; i++) {

byte[] bytedata = (byte[]) pdus[i];

retmeMessage[i]? = SmsMessage.createFromPdu(bytedata);

}

return retmeMessage;

}

}


---------------------------------------------------------------------------ReceiverDemo-------------------------------------------------------------------------------------


package com.example.acer.mymusic.BroadCast;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.os.Bundle;

import android.telephony.SmsMessage;

import android.widget.Toast;

public class ReceiverDemoextends BroadcastReceiver

{

private static final StringstrRes ="android.provider.Telephony.SMS_RECEIVED";

@Override

? ? public void onReceive(Context arg0, Intent arg1) {

// TODO Auto-generated method stub

? ? ? ? if(strRes.equals(arg1.getAction())){

StringBuilder sb =new StringBuilder();

Bundle bundle = arg1.getExtras();

if(bundle!=null){

Object[] pdus = (Object[])bundle.get("pdus");

SmsMessage[] msg =new SmsMessage[pdus.length];

for(int i =0 ;i

msg[i] = SmsMessage.createFromPdu((byte[])pdus[i]);

}

for(SmsMessage curMsg:msg){

sb.append("You got the message From:【");

sb.append(curMsg.getDisplayOriginatingAddress());

sb.append("】Content:");

sb.append(curMsg.getDisplayMessageBody());

}

Toast.makeText(arg0,

"Got The Message:" + sb.toString(),

Toast.LENGTH_SHORT).show();

}

}

}

}


---------------------------------------------------------------------------xml文件sms-------------------------------------------------------------------------------------


? ? android:orientation="vertical"

? ? android:layout_width="fill_parent"

? ? android:layout_height="fill_parent"

? ? android:background="@mipmap/erq_jj"

? ? >

? ? ? ? android:layout_marginTop="120dp"

? ? ? ? android:layout_width="fill_parent"

? ? ? ? android:layout_height="wrap_content"

? ? ? ? android:text="@string/mobile"

? ? ? ? android:textColor="@color/white"

? ? ? ? />

? ? ? ? android:textColor="@color/white"

? ? ? ? android:id="@+id/telNo"

? ? ? ? android:layout_width="fill_parent"

? ? ? ? android:layout_height="50dp"

? ? ? ? android:theme="@style/MyEditText"

? ? ? ? android:layout_marginRight="98dp"

? ? ? ? />

? ? ? ? android:layout_width="fill_parent"

? ? ? ? android:layout_height="wrap_content"

? ? ? ? android:text="@string/content"

? ? ? ? android:textColor="@color/white"

? ? ? ? />

? ? ? ? android:textColor="@color/white"

? ? ? ? android:id="@+id/content"

? ? ? ? android:layout_width="fill_parent"

? ? ? ? android:layout_height="80dp"

? ? ? ? android:minLines="3"

? ? ? ? android:theme="@style/MyEditText"

? ? ? ? />

? ? ? ? android:layout_marginTop="50dp"

? ? ? ? android:id="@+id/btn"

? ? ? ? android:layout_width="wrap_content"

? ? ? ? android:layout_height="wrap_content"

? ? ? ? android:text="@string/button"

? ? ? ? android:textColor="@color/white"

? ? ? ? android:padding="12dp"

? ? ? ? android:shadowColor="#7f000000"

? ? ? ? android:shadowDx="0.0"

? ? ? ? android:shadowDy="1.0"

? ? ? ? android:shadowRadius="1.0"

? ? ? ? android:background="@drawable/button_pre"

? ? ? ? android:layout_marginLeft="150dp"

? ? ? ? />

---------------------------------------------------------------------------xml文件sms-------------------------------------------------------------------------------------



? ? android:layout_width="match_parent"

? ? android:layout_height="match_parent"

? ? android:orientation="vertical"

? ? android:background="#fff"

? ? android:padding="10dp">

? ? ? ? android:layout_width="match_parent"

? ? ? ? android:layout_height="wrap_content"

? ? ? ? android:orientation="vertical"

? ? ? ? android:gravity="center_horizontal" >

? ? ? ? ? ? android:id="@+id/textView1"

? ? ? ? ? ? android:layout_width="wrap_content"

? ? ? ? ? ? android:layout_height="wrap_content"

? ? ? ? ? ? android:text="短信"

? ? ? ? ? ? android:textColor="#000" />

---------------------------------------------------------------------------BroadCastActivity2_SMS-------------------------------------------------------------------------------------


package com.example.acer.mymusic.Activity;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.widget.TextView;

import com.example.acer.mymusic.R;

public class BroadCastActivity2_SMSextends Activity

{

private TextViewtextView;

@Override

? ? protected void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub

? ? ? ? super.onCreate(savedInstanceState);

setContentView(R.layout.activity_bc2_sms);

textView = (TextView) findViewById(R.id.textView1);

Intent intent = getIntent();

if (intent !=null) {

String address = intent.getStringExtra("sms_address");

if (address !=null) {

textView.append("\n\n發(fā)件人:\n" + address);

String bodyString = intent.getStringExtra("sms_body");

if (bodyString !=null) {

textView.append("\n短信內容:\n" + bodyString);

}

}

}

}

}

這里我使用了兩個廣播回調,所以就只介紹其中一個,使用兩個的原因是,感受一下廣播的強悍之處;

先從最簡單的那個講起:




這里這個作用是非常明顯的,收到一個意圖,獲取到內容后給textview。

到這里我們理所當然的去想intent是怎么來的。




這是一個廣播接收者,這里他的作用是:從intent里面獲取到信息,然后把后去到的信息裝在另一個intent里面

中間進行的字符串拼接就不說了,現在我們依舊不曉得intent是哪里來的

繼續(xù)看下去,也就是這段的核心代碼:




這里主要是設置的全屏和動態(tài)獲取權限也不多講了





首先是這個:只是做了一寫判斷,判斷電話號碼師傅有,是否符合規(guī)則。但是有個兼容性的問題


這一段是兼容模擬器而做的,在模擬器上是沒有辦法來使用電話號碼來進行發(fā)送短信的,所以需要用到模擬器對外開發(fā)的接口編號,同是也造成了一個問題,就是輸入

5556的時候真機上是沒有辦法去運行的。如果不需要這個在模擬器上運行,可以吧模擬器那部分的兼容刪了



利用類?SmsManager?發(fā)送信息,?smsManager?為?SmsManager?一個默認的實例.?SmsManager?smsManager?=?SmsManager.getDefault();?

  smsManager.sendTextMessage(destinationAddress,?scAddress,?text,?sentIntent,?deliveryIntent)??

  destinationAddress:?收件人號碼?

  scAddress:?短信中心服務號碼,?這里設置為null?

  text:?發(fā)送內容

  sentIntent:?發(fā)送短信結果狀態(tài)信號(是否成功發(fā)送),new?一個Intent?,?操作系統(tǒng)接收到信號后將廣播這個Intent.此過程為異步.

  deliveryIntent:?對方接收狀態(tài)信號(是否已成功接收).


到這里我們已經把intent的來源給找到了,就是這個intent咯。

這里說明一下,如果超過70的話會分條發(fā)送的。

基本上思路就是這樣了?。?/p>

有興趣的朋友可以繼續(xù)深入下去了解一下


?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 我們不要去挑戰(zhàn)大自然對人類的懲罰;不要挑戰(zhàn)最基本的道德準則; 不要挑戰(zhàn)無情的心以及冷酷的人。 如...
    烽火煤閱讀 220評論 0 0
  • 高考已過一年,現在說說上各種高考的說說刷屏,我從最初的只想簡單的三個數字,到最后想給那兩個我曾經熟悉的人加油,尤其...
    unravellll閱讀 412評論 0 0
  • 一個表演工作者,有時其實是一般人,都會有被人家仰望或者是輕視的時候,可是我覺得,只有他知道自己該是個什么樣的人、可...
    LilyanSiena閱讀 1,408評論 4 18
  • UIDynamicItemBehavior 定義的都是一些輔助行為
    Laughingg閱讀 602評論 0 0
  • 我所在的小城最近開了一家海洋館,之前旅游的時候也有去其他城市的海洋館去玩,只可惜都是匆匆的驚鴻一瞥,沒有機會細...
    愛寫詩的金先生閱讀 983評論 6 9

友情鏈接更多精彩內容