Android第22天 BroadCast

 无序广播:

1.       动态定义广播接收者

 

public class MainActivity extends Activity {

         privateMyBroadCast myBroadCast;

         privateButton button;

 

    @Override

    protectedvoid onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.activity_main);

       myBroadCast=new MyBroadCast();

      button=(Button) findViewById(R.id.button1);

       button.setOnClickListener(newOnClickListener() {

                 

                  @Override

                  publicvoid onClick(View v) {

                             Intent intent=newIntent();

                          intent.setAction("heheh");

                          intent.putExtra("name","jajaja");

                          sendBroadcast(intent);

                           

                  }

         });

     

    }

    @Override

    protectedvoid onResume() {

    IntentFilter filter=newIntentFilter("heheh");

    registerReceiver(myBroadCast, filter);

    super.onResume();

    }

    @Override

    protectedvoid onPause() {

    // TODO Auto-generated method stub

    unregisterReceiver(myBroadCast);

    super.onPause();

    }

}

package com.qianfeng.lx_broadcastsend;

 

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.widget.Toast;

 

public class MyBroadCast extends BroadcastReceiver {

 

         @Override

         publicvoid onReceive(Context context, Intent intent) {

                  String message=intent.getStringExtra("name");

                  System.out.println("=========================================="+message);

 

         }

 

}



静态定义广播接收者

           只要在清单文件中进行如下配置就可以了:

                  <receiverandroid:name="com.jason.android23_broadcastreceiver.MyBroadcastReceiver">

            <intent-filter>

                <actionandroid:name="SIMPLE_BROADCAST" />

           </intent-filter>

       </receiver>

有序广播 :

        2.1发送有序广播

              /**

          * 发送有序广播

          * @param view

          */

         publicvoid send2(View view){

                   Intentintent = new Intent();

                   intent.setAction("com.itheima.broadcasttest.songwennuan");

                   //有序广播,可被拦截,可终止,可以修改数据。

                   sendOrderedBroadcast(intent,null, new FinalReceiver(), null, 0, "给农民兄弟发10000块钱", null);

         }

       2.2接收广播:

        接收并修改广播:

         Stringmessage = getResultData();

                   System.out.println("省级部门得到中央的消息:"+message);

                   abortBroadcast();

                   setResultData("给农民兄弟发5000块钱");

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值