(八)Android廣播接收器BroadcastReceiver

來源:互聯網
上載者:User

標籤:

一、使用Broadcast Reciver 1.右擊java檔案夾,new->other->Broadcast Receiver後會在AndroidManifest.xml檔案中產生一個receiver項
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.shiyanshi.learnbroadcast" >

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

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

<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true" >
</receiver>
</application>

</manifest>
2.同時產生了一個MyReceiver 的類,該類中onReceive用於響應sendBroadcast函數發送的訊息
package com.example.shiyanshi.learnbroadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}

@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
// throw new UnsupportedOperationException("Not yet implemented");
System.out.println("Recv Data:"+intent.getStringExtra("data"));
}
}
3.調用sendBroadcast函數進行發送訊息,該函數需要一個Intent
package com.example.shiyanshi.learnbroadcast;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;


public class MainActivity extends Activity implements View.OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

findViewById(R.id.btnSendMsg).setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btnSendMsg:
Intent intent =new Intent(this,MyReceiver.class);
intent.putExtra("data","henry");
sendBroadcast(intent);
break;
}
}
}
二、動態註冊和登出1.刪去AndroidManifest.xml檔案中的receiver時,需要動態註冊和登出,才能發送和接收訊息<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true" >
</receiver>
2.MainActivity更改如下:發送訊息訊息時,Intent要使用隱式Intent(MyReceiver.ACTION為定義的一個常量字串public static final String ACTION="com.example.shiyanshi.learnbroadcast.intent.action.MyReceiver";//前半部分時包名,後半部分時intent的格式,MyReceiver是上述中用於響應sendBroadcast的類),註冊時使用registerReceiver函數,登出時使用unregisterReceiver函數函數原型為:public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter)public void unregisterReceiver(BroadcastReceiver receiver)receiver是我們建立Broadcast時聲稱的用於響應sendBroadcast的MyReceiver類,filter是過濾器,需想起傳遞隱式Intent類似的參數。

 

public class MainActivity extends Activity implements View.OnClickListener {

private MyReceiver receiver=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

findViewById(R.id.btnSendMsg).setOnClickListener(this);
findViewById(R.id.btnRegister).setOnClickListener(this);
findViewById(R.id.btnUnregister).setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btnSendMsg:
// Intent intent =new Intent(this,MyReceiver.class);
//動態註冊和登出時要使用隱式Intent,而不能使用顯示Intent了
Intent intent=new Intent(MyReceiver.ACTION);
intent.putExtra("data","henry");
sendBroadcast(intent);
break;
case R.id.btnRegister:
if (receiver==null){
receiver=new MyReceiver();
registerReceiver(receiver,new IntentFilter(MyReceiver.ACTION));
}
break;
case R.id.btnUnregister:
if(receiver!=null){
unregisterReceiver(receiver);
receiver=null;
}
break;
}
}
}
三、Broadcast的優先順序當發送資料時,採用隱式Intent的形式(如上),兩個receiver中的action name相同時,二者可以同時接收到資料。預設情況下最後寫的那個receiver所對應的優先順序高,此外可以顯示的在receiver下的Intent-filter中指明優先順序priority,其數值越大,優先順序越高,越先響應資料
 <receiver
android:name=".MyReceiver1"
android:enabled="true"
android:exported="true" >
<intent-filter android:priority="2">
<action android:name="com.example.shiyanshi.learnbroadcast.intent.action.MyReceiver"/>
</intent-filter>
</receiver>
<receiver android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1">
<action android:name="com.example.shiyanshi.learnbroadcast.intent.action.MyReceiver"/>
</intent-filter>
</receiver>
</application>
此外,當優先順序高的那個onReceive執行後,可以在其中調用abortBroadcast來終止資料的傳遞,優先順序別低的onReceive便不會執行了.注意:若想使用abortBroadcast函數,發送時需使用sendOrderedBroadcast而非sendBroadcast,否則會彈出錯誤java.lang.RuntimeException: BroadcastReceiver trying to return result during a non-ordered broadcast。
Intent intent=new Intent(MyReceiver.ACTION);
intent.putExtra("data","henry");
// sendBroadcast(intent);
sendOrderedBroadcast(intent,null);
其中sendOrderedBroadcast的第二個參數用來指明許可權,可以為空白


(八)Android廣播接收器BroadcastReceiver

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.