22 广播动态创建

结构
这里写图片描述

清单文件AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.qf.day22_broadcastreceiver_demo2"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.qf.day22_broadcastreceiver_demo2.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>
    </application>

</manifest>

MainActivity.java

package com.qf.day22_broadcastreceiver_demo2;

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

public class MainActivity extends Activity {

    //获取广播接收器对象
    private MyBroadCastReceiver01 myBroadCastReceiver01 = new MyBroadCastReceiver01();
    private MyBroadCastReceiver02 myBroadCastReceiver02 = new MyBroadCastReceiver02();

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

        //获取意图过滤器
        IntentFilter intentFilter = new IntentFilter();
        //添加Action 只接受广播意图为qq.weixin.mm
        intentFilter.addAction("qq.weixin.mm");

        //动态注册广播接收器qq.weinxin
        registerReceiver(myBroadCastReceiver01, intentFilter);
        registerReceiver(myBroadCastReceiver02, intentFilter);
    }


    public void MySendClick(View v){

        Intent intent = new Intent();
        //创建广播意图为
        intent.setAction("qq.weixin.mm");
        intent.putExtra("str", "小米5");
        //发送广播
        sendBroadcast(intent);
    }


    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        //可以取消注册
        unregisterReceiver(myBroadCastReceiver01);
    }


}

MyBroadCastReceiver01.java

package com.qf.day22_broadcastreceiver_demo2;

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

public class MyBroadCastReceiver01 extends  BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        if(intent!=null){
            String str = intent.getStringExtra("str");
            Toast.makeText(context, "=1111=>"+str, 0).show();
        }

    }

}

MyBroadCastReceiver02类似

结果:两个都接受到广播

posted on 2016-09-21 19:29  木鱼哥  阅读(94)  评论(0编辑  收藏  举报

导航