Android学习6: BroastcastReceiver的注册方法

来源:互联网 发布:大数据云平台 编辑:程序博客网 时间:2024/06/13 13:10

BroastcastReceiver的具体使用方法, 还不是很清楚,  

今天又学习了一下大神张国威的博客. 有点收获. 

忙里抽闲也要找点时间来学习..


动态和静态调用的方法都不是很复杂.

这个例子里面还包函了获取系统参数的方法.


动态注册比静态注册要简单一些:

两步就可以了.

// 动态注册广播消息registerReceiver(bcrIntenal1, new IntentFilter(INTENAL_ACTION_1));

    /*     * 接收动态注册广播的BroadcastReceiver     */    private BroadcastReceiver bcrIntenal1 = new BroadcastReceiver() {        public void onReceive(Context context, Intent intent) {            String action = intent.getAction();            Toast.makeText(context, "动态:" + action, 1000).show();        }    };


静态注册的方法:

首先要在XML中声明:

        // 静态注册方法        <receiver android:name=".StaticReceiver">            <intent-filter>                <action                    android:name="com.testBroadcastReceiver.Internal_2"/>            </intent-filter>        </receiver>

两个name, 第一个name 是类名. 第二个是action名称.


然后再声明类:

public class StaticReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        String action = intent.getAction();        Toast.makeText(context, "静态:" + action, 1000).show();    }}



上图:


具体代码:

src/main/AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.youtwo.testbroastcast" >    <application        android:allowBackup="true"        android:icon="@drawable/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=".StaticReceiver">            <intent-filter>                <action                    android:name="com.testBroadcastReceiver.Internal_2"/>            </intent-filter>        </receiver>    </application></manifest>

布局文件:

layout/activity_main.xml

<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">    <LinearLayout        android:orientation="vertical"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:layout_alignParentTop="true"        android:layout_alignParentLeft="true"        android:layout_alignParentStart="true">        <Button            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:text="内部动态注册BroadCastReceiver"            android:id="@+id/button1" />        <Button            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:text="内部静态注册BroadCastReceiver"            android:id="@+id/button2" />        <Button            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:text="系统BROADCASTReceiver"            android:id="@+id/button3"            android:layout_gravity="center_horizontal" />    </LinearLayout></RelativeLayout>

com/example/youtwo/testbroastcast/MainActivity.java

package com.example.youtwo.testbroastcast;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.Button;import android.widget.Toast;public class MainActivity extends ActionBarActivity {    Button btnInnerDynamic, btnInnerStatic, btnSystem;    static final String INTENAL_ACTION_1 = "com.testBroadcastReceiver.Internal_1"; // 动态    static final String INTENAL_ACTION_2 = "com.testBroadcastReceiver.Internal_2"; // 静态    static final String INTENAL_ACTION_3 = "com.testBroadcastReceiver.Internal_3"; // 系统    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        btnInnerDynamic = (Button)this.findViewById(R.id.button1);        btnInnerDynamic.setOnClickListener(new ClickEvent());        btnInnerStatic = (Button)this.findViewById(R.id.button2);        btnInnerStatic.setOnClickListener(new ClickEvent());        btnSystem = (Button)this.findViewById(R.id.button3);        btnSystem.setOnClickListener(new ClickEvent());        // 动态注册广播消息        registerReceiver(bcrIntenal1, new IntentFilter(INTENAL_ACTION_1));    }    @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);    }    class ClickEvent implements View.OnClickListener {        @Override        public void onClick(View v) {            if(v == btnInnerDynamic) {                Intent intent = new Intent(INTENAL_ACTION_1);                sendBroadcast(intent);            }            else if(v == btnInnerStatic) {                Intent intent = new Intent(INTENAL_ACTION_2);                sendBroadcast(intent);            }            else if(v == btnSystem) {                // 获取系统参数的方法                IntentFilter filter = new IntentFilter();//                filter.addAction(Intent.ACTION_BATTERY_CHANGED);//系统电量检测信息                filter.addAction(INTENAL_ACTION_3);//第三组自定义消息                registerReceiver(batInfoReceiver, filter);                Intent intent = new Intent(INTENAL_ACTION_3);                intent.putExtra("Name", "大神");                intent.putExtra("Blog", "http://blog.csdn.net/hellogv"); // 有时间去膜拜一下.                sendBroadcast(intent);//传递过去            }        }    }    /*     * 接收动态注册广播的BroadcastReceiver     */    private BroadcastReceiver bcrIntenal1 = new BroadcastReceiver() {        public void onReceive(Context context, Intent intent) {            String action = intent.getAction();            Toast.makeText(context, "动态:" + action, 1000).show();        }    };    private BroadcastReceiver batInfoReceiver = new BroadcastReceiver() {        public void onReceive(Context context, Intent intent) {            String action = intent.getAction();            //如果捕捉到的action是ACTION_BATTERY_CHANGED            if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {                //当未知Intent包含的内容,则需要通过以下方法来列举                Bundle b=intent.getExtras();                Object[] lstName=b.keySet().toArray();                for(int i=0;i<lstName.length;i++)                {                    String keyName=lstName[i].toString();                    Log.e(keyName, String.valueOf(b.get(keyName)));                }            }            //如果捕捉到的action是INTENAL_ACTION_3            if (INTENAL_ACTION_3.equals(action)) {                //当未知Intent包含的内容,则需要通过以下方法来列举                Bundle b=intent.getExtras();                Object[] lstName=b.keySet().toArray();                for(int i=0;i<lstName.length;i++)                {                    String keyName=lstName[i].toString();                    Log.e(keyName,b.getString(keyName));                }            }        }    };}

com/example/youtwo/testbroastcast/StaticReceiver.java

package com.example.youtwo.testbroastcast;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.widget.Toast;/** * Created by YouTwo on 2015/1/19. */public class StaticReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        String action = intent.getAction();        Toast.makeText(context, "静态:" + action, 1000).show();    }}




0 0
原创粉丝点击