作业2:广播和服务----作业一

要求

编写广播代码,参考网址:http://www.wustwzx.com/as/sy/sy06.html#mk1中的example6_3模块。

功能说明

点击发送广播按钮,Receiver接受类以提示的方式显示出广播发送的数据,同时实现动态注册广播接受者

核心代码展示

广播(Broadcast)是一种运用在应用程序之间传递消息的机制;
广播接收者(BroadcastReceiver)是用来过滤、接收井响应广播的一类组件;
广播接收者可以监听系统中的广播消息,在不同组件之问进行通信;
自定义Receiver类:

 @Override
    public void onReceive(Context context, Intent intent) {

//        Intent serviceIntent = new Intent(context, MyService.class);
        //在广播组件里,通过上下文对象启动音乐播放服务组件
//        context.startService(serviceIntent);

        //新建调用Activity组件的意图
//        Intent activityIntent = new Intent(context, MainActivity.class);
//        activityIntent.putExtra("iscast", true);  //携带数据
//        //新建栈用来存放被启动的Activity(当已经存在时,只做移动处理)
//        activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        //在广播组件里,通过上下文对象启动Activity组件
//        context.startActivity(activityIntent);
//        Toast.makeText(context,"系统广播方式启动音乐播放",500).show();


        Bundle mybundle =  intent.getExtras();
        String str1 = mybundle.getString("data1");
        String str2 = mybundle.getString("data2");
        Toast.makeText(context, str1+" " +str2,Toast.LENGTH_LONG).show();
//        tv.setText(str1+" " +str2);
    }

MainActivity类代码:

		//广播的动态注册
		IntentFilter myintentfliter = new IntentFilter();
        myintentfliter.addAction("com.example.broadcast.MY_BROADCAST");
        registerReceiver(myReceiver, myintentfliter);


	//为button按钮设置监听器
	button_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent myintent = new Intent("com.example.broadcast.MY_BROADCAST");
                Bundle  bundle = new Bundle();
                String result = text_send.getText().toString();
                bundle.putString("data1", "自定义广播与接收案例");
                bundle.putString("data2", "金东-----20182211...014");
                myintent.putExtras(bundle);  //捆绑数据
                sendBroadcast(myintent);   //发送广播
                try {
                    Thread.sleep(1000);  //休眠一下,模拟广播可能存在的延迟
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });

广播的静态注册与动态注册的区别
在这里插入图片描述

功能演示

当点击发送广播之后:
在这里插入图片描述

仓库地址:https://gitee.com/hubu8/android/tree/master/MyService3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值