安卓静态广播注册案例

布局相对简单,界面上放置一个按钮,单击按钮以后就会发送一个广播,当广播接收器收到该广播时就会在界面弹出一个提示消息。
1.界面设计

​<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/send"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="发送广播"/>
</LinearLayout>

​

2.编写MainActivity代码

public class MainActivity extends AppCompatActivity {
private Button send;
private final String action="MyBroadcast";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout);
        send=(Button)findViewById(R.id.send);
            send2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setAction(action);
                MainActivity.this.sendBroadcast(intent);
           }
        });
    }
}

上述代码为按钮添加了单击事件,当单击按钮时,就会发送广播。其中 Action 的值与清单文件中定义的值相同。

3.自定义广播接收器自定义广播接收器继承自 BroadcastReceiver ,然后实现它的 onReceiver()方法。

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
          Toast.makeText(context,"广播接收成功",Toast.LENGTH_SHORT).show();
    }
}

从上述代码中可以看出,当接收广播时,就会在主界面上显示一个内容为“广播接收成功”的通知。

4.注册广播接收器

注册广播接收器由于本案例使用的是静态的注册方式,所以需要在 Androidmanifest . xml 文件中注册。

       <receiver
            android:name=".MyReceiver">
            <intent-filter>
                <action android:name="MyBroadcast"/>
            </intent-filter>
        </receiver>

 从上述代码中可以看出,</ intent - filter >中定义的 action 的 name 属性值要与发送广播时的字符串相同。

5.运行程序

运行程序上述操作完成以后,运行程序,单击主界面上的“发送广播”按钮,就会弹出一个通知。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值