Broadcast发送广播

移动开发 作者: 2024-08-25 03:45:01
一、知识介绍 1、【广播分类】 ①有序广播:接收者A收到广播传递给B,B传给C,有序传递。任何一个环节都可以终止广播,也可以修改广播中携带的数据。 发送的方式:sendOrderedBroadcast

一、知识介绍

二、项目一【发送广播】

 1 import android.content.BroadcastReceiver;
 2  android.content.Context;
 3  android.content.Intent;
 4  android.widget.Toast;
 5 
 6 public class MyReceiver extends BroadcastReceiver {
 7 
 8     @Override
 9     void onReceive(Context context,Intent intent) {
10         // TODO: This method is called when the BroadcastReceiver is receiving
11         Toast.makeText(context,"收到广播",Toast.LENGTH_SHORT).show();
12     }
13 }
1 <receiver
2             android:name=".receiver.MyReceiver"
3             android:enabled="true"
4             android:exported="true">
5             intent-filter6                 action ="com.example.MyApplication2.myreceiver" />
7             </8         receiver>
1     Button
2        android:id="@+id/btn"
       android:text="发送广播"
       android:layout_width="match_parent"
5        android:layout_height="wrap_content" />
 android.support.v7.app.AppCompatActivity;
 android.os.Bundle;
 android.view.View;
 5  android.widget.Button;
 6 
 7 class MainActivity  AppCompatActivity {
 8 
 9     Button btn;
10 11     protected  onCreate(Bundle savedInstanceState) {
12         super.onCreate(savedInstanceState);
13         setContentView(R.layout.activity_main);
14 
15         btn = findViewById(R.id.btn);
16         btn.setOnClickListener(new View.OnClickListener() {
17             @Override
18              onClick(View view) {
19                 Intent intent = new Intent("com.example.MyApplication2.myreceiver");
20                 sendBroadcast(intent);
21             }
22         });
23         
24 25 }

 二、项目二【发送有序广播】

 2             =".receiver.MyOrderReceiver1"
 3  4  5             intent-filter android:priority="1000" 6                 ="com.example.MyApplication2.myreceiver"  7              8          9         10             =".receiver.MyOrderReceiver2"
11 12 13             ="100"14                 15             16         17         18             =".receiver.MyOrderReceiver3"
19 20 21             ="10"22                 23             24         >
1         btn2 = findViewById(R.id.btn2);
2         btn2.setOnClickListener(3 4             5                 Intent intent = new Intent("com.example.MyApplication2.myreceiver"6                 sendOrderedBroadcast(intent,null7 8         });
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_68183.html
Broadcast发送广播