AS移动开发——自定义广播

一、布局
在这里插入图片描述
二、自定义BroadcastRecevier
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
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
public class MainActivity extends AppCompatActivity {
private TextView tv; //用于显示接收到的广播信息
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
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);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

    //使用意图过滤器类IntentFilter动态注册广播接收者
    IntentFilter myintentfliter = new IntentFilter();
    myintentfliter.addAction("com.example.broadcast.MY_BROADCAST");
    registerReceiver(myReceiver, myintentfliter);

    tv = findViewById(R.id.txt);
    findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            Intent myintent = new Intent("com.example.broadcast.MY_BROADCAST");
            Bundle  bundle = new Bundle();
            bundle.putString("data1", "自定义广播与接收案例");
            bundle.putString("data2", "啦啦啦");
            myintent.putExtras(bundle);  //捆绑数据
            sendBroadcast(myintent);   //发送广播
            try {
                Thread.sleep(1000);  //休眠一下,模拟广播可能存在的延迟
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
}

}

四、运行结果
在这里插入图片描述
结语
个人理解自定义的广播核心就是BroadcastReceiver的编写。
这是最基础的自定义广播,但在实际应用时,广播通常是内嵌于activity和service的,之后会完善另一个作业——MusicBox。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值