Android进阶之路 - 四大组件之BroadcaseReceiver

众所周知BroadcaseReceiver为Android中的四大组件之一,又名为广播、喇叭,这篇我为大家带来的就是BroadcaseReceiver的详细使用方式,说到使用其中又有些许不同,下面为大家进行讲解 ~
静态注册、动态注册、有序广播、无序广播、 自定义广播、广播拦截等功能的详细使用方式

        • 基础概念
          • 广播分类
          • 注册方式
          • 使用方式与注意点
        • 使用方式
            • MainActivity
            • CostomBroadcaseReceiver的代码(自定义广播)
            • DynamicBroadcaseReceiver的代码(动态注册)
            • LocalBroadcaseReceiver的代码(本地广播)
            • StaticBroadcaseReceiver的代码(静态注册)
            • QuickBroadcaseReceiver(优先级的广播接收者,做了拦截处理,静态广播被拦截,只能接收到优先级的广播)的代码
            • activity.xml
            • 清单文件

基础概念

广播分类
  • 有序广播(可拦截)
  • 无序广播(不可拦截)
注册方式
  • 动态注册(代码注册)
  • 静态注册(清单注册)
使用方式与注意点

1.使用广播首先要创建一个类继承BroadcaseReceiver,然后重写onReceiver方法(接收到广播的操作在这里执行)

2.在所依赖的Activity等寄生体之中发送广播(分有序和无序,下文都有介绍)

3.作为Android下的四大组件之一,必不可少的自然有动态注册和静态组测(清单注册)

补充:针对Android7.0的最好要实现动态注册

4.文中我并没有监听系统的一些广播,如开机,网络状态之类,而是为了方便自己定义的广播,有兴趣的可以举一反三进行广播处理

5.广播注册是必须的,那么注销也是必须的!否在会有OOM的隐藏风险!

使用方式

1.MainActivity主代码与各个接收者代码

2.MainActivity的Xml代码

3.清单文件(主要用于观察注册与优先级的处理)

MainActivity
package com.example.broadcasereceiver;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

	private TextView mCostomBroad;
	private TextView mLocalBroad;
	private LocalBroadcastManager localBroadcast;
	private TextView mDynamicBroad;
	private TextView mStaticBroad;
	private TextView mQuickBroad;
	private IntentFilter dynamic_filter;
	private DynamicBroadcaseReceiver dynamicBroadcaseReceiver;
	private LocalBroadcaseReceiver localBroadcaseReceiver;
	private TextView mQucly;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 事件
		init();
		// 处理
		initEvent();
		/**这里要注意注册是注册,发送广播是发送广播,是前后关系,而不可混为一谈*/
		// 获取本地管理者
		localBroadcast = LocalBroadcastManager.getInstance(this);
		//动态注册-都是一个套路
		IntentFilter localFilter = new IntentFilter();
		localFilter.addAction("LocalBroadcaseReceiver");
		localBroadcaseReceiver = new LocalBroadcaseReceiver();
		localBroadcast.registerReceiver(localBroadcaseReceiver, localFilter);
	}

	/**
	 * 放置find-Id
	 * */
	private void init() {
		mLocalBroad = (TextView) findViewById(R.id.Broadcase_local);
		mCostomBroad = (TextView) findViewById(R.id.Broadcase_costom);
		mDynamicBroad = (TextView) findViewById(R.id.Broadcase_dynamic);
		mStaticBroad = (TextView) findViewById(R.id.Broadcase_static);
		mQuickBroad = (TextView) findViewById(R.id.Broadcase_quick);
	}

	/**
	 * 设置Click事件
	 * */
	private void initEvent() {
		mCostomBroad.setOnClickListener(this);
		mLocalBroad.setOnClickListener(this);
		mDynamicBroad.setOnClickListener(this);
		mStaticBroad.setOnClickListener(this);
		mQuickBroad.setOnClickListener(this);
	}

	/**
	 * Event处理
	 * */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// 自定义广播
		case R.id.Broadcase_costom:
			Intent intent = new Intent("CostomBroadcaseReceiver");
			sendBroadcast(intent);
			break;
		// 动态注册广播
		case R.id.Broadcase_dynamic:
			//和清单文件格式对应,这里是添加广播的过滤
			dynamic_filter = new IntentFilter();
			//添加动作= 设置广播
			dynamic_filter.addAction("DynamicBroadcaseReceiver");
			//注册广播-确定监听者与广播
			dynamicBroadcaseReceiver = new DynamicBroadcaseReceiver();
			registerReceiver(dynamicBroadcaseReceiver, dynamic_filter);
			//Toast.makeText(MainActivity.this, "动态注册广播", 0).show();
			Intent DynamicIntent = new Intent("DynamicBroadcaseReceiver");
			sendBroadcast(DynamicIntent);
			break;
		// 静态广播-有序广播
		case R.id.Broadcase_static:
			Intent Staticintent = new Intent("StaticBroadcaseReceiver");
			//一般情况的使用这种方式就是标准方式,也就是无序广播
			//sendBroadcast(Staticintent);
			//这样就是有序的广播了 (注意:方法不同),我们可以对其做处理,如拦截之类,
			sendOrderedBroadcast(Staticintent, null);
			break;
		// 本地广播
		case R.id.Broadcase_local:
			Intent localIntent = new Intent("LocalBroadcaseReceiver");
			localBroadcast.sendBroadcast(localIntent);
			break;
		//优先级的测试-这里我们选择静态注册,也就是直接在清单注册-设置priority
		//经过测试很明显拦截广播是建立在有序广播的基础上面,同时拦截广播后只显示静态注册的Toask,而不是优先级的Toask
		case R.id.Broadcase_quick:
			Intent quickintent = new Intent("StaticBroadcaseReceiver");
			quickintent.setAction("QuickBroadcaseReceiver");
			sendOrderedBroadcast(quickintent, null);
			break;
		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		//注销广播-因为不是本地广播的话,会有数据隐患的,好比你已经关了APP但是还是一直发广播或者接收广播,系统会自己操作,所以极为不安全,
		//so if dynamicbRoadcaseReceiver ,we need shell all;(- -!)
		unregisterReceiver(dynamicBroadcaseReceiver);
		unregisterReceiver(localBroadcaseReceiver);
	}
}

以下Recevice方法均是一个简单的Toask

CostomBroadcaseReceiver的代码(自定义广播)
package com.example.broadcasereceiver;

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

/**
 * 自定义广播
 * */
public class CostomBroadcaseReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent arg1) {
		Toast.makeText(context, "自定义广播触发", 0).show();
	}
}
DynamicBroadcaseReceiver的代码(动态注册)
package com.example.broadcasereceiver;

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

/**
 * 自定义广播
 * */
public class DynamicBroadcaseReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent arg1) {
		Toast.makeText(context, "动态注册广播触发", 0).show();
	}
}
LocalBroadcaseReceiver的代码(本地广播)
package com.example.broadcasereceiver;

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

/**
 * 自定义广播
 * */
public class LocalBroadcaseReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent arg1) {
		Toast.makeText(context, "本地自定义广播触发", 0).show();
	}
}
StaticBroadcaseReceiver的代码(静态注册)
package com.example.broadcasereceiver;

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

/**
 * 自定义广播
 * */
public class StaticBroadcaseReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent arg1) {
		Toast.makeText(context, "静态广播广播触发", 0).show();
	}
}
QuickBroadcaseReceiver(优先级的广播接收者,做了拦截处理,静态广播被拦截,只能接收到优先级的广播)的代码
package com.example.broadcasereceiver;

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

public class QuickBroadcaseReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
			Toast.makeText(context, "优先级的测试广播触发", 0).show();
			abortBroadcast();
	}
}

activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/Broadcase_costom"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:gravity="center"
        android:text="@string/CostomBroadcase" />
    <TextView
        android:id="@+id/Broadcase_dynamic"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:gravity="center"
        android:text="@string/DynamicBroadcase" />
    <TextView
        android:id="@+id/Broadcase_static"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:gravity="center"
        android:text="@string/StaticBroadcase" />

    <TextView
        android:id="@+id/Broadcase_local"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:gravity="center"
        android:text="@string/LocalBroadcase" />
     <TextView
        android:id="@+id/Broadcase_quick"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:gravity="center"
        android:text="优先级测试" />
LinearLayout>
清单文件

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.broadcasereceiver"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.broadcasereceiver.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="com.example.broadcasereceiver.CostomBroadcaseReceiver" >
            <intent-filter>
                <action android:name="CostomBroadcaseReceiver"/>
            intent-filter>
        receiver>
      
          <receiver android:name="com.example.broadcasereceiver.StaticBroadcaseReceiver"
               >
            <intent-filter >
                <action android:name="StaticBroadcaseReceiver"/>
            intent-filter>
        receiver>
        
      
        <receiver android:name="com.example.broadcasereceiver.QuickBroadcaseReceiver"
               >
            <intent-filter  android:priority="100" >
                <action android:name="QuickBroadcaseReceiver"/>
                  <action android:name="StaticBroadcaseReceiver"/>
            intent-filter>
        receiver>
        
    application>

manifest>

你可能感兴趣的:(Android进阶之路)