delphi 安卓广播Android-Broadcast广播事件(1)-简介及普通广播调用步骤

来自:https://blog.csdn.net/ohcezzz/article/details/71104641

前言

BroadcastReceiver即广播接收器,是专门用于接受广播消息以及做出相应处理的组件。其本质就是一个全局监听器,接收程序所发出的Broadcast Intent。
但是它是没有用户界面的,可以启动一个Activity来响应接收到的信息或者用NotificationManager来通知用户。
总体而言,广播机制包含三个要素:

  1. 发送广播的Broadcast;

  2. 接收广播的BroadcastReceiver;

  3. 以及用于前面两者之间传递消息的Intent;

  4. 广播事件开发步骤

  5. 定义一个广播接收器

只需重写onReceive方法

public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
//method
}
}
1
2
3
4
5
6
7
8
2. 注册广播事件

注册广播事件 有两种方式

动态注册,代码中调用BroadcastReceiver的Context的registerReceiver()方法进行注册
// 实例化定义好的BroadcastReceiver
MyReceiver receiver=new MyReceiver();
// 实例化过滤器,并设置过滤的广播的action,
IntentFilter filter=new IntentFilter(“MY_ACTION”);
// 注册
registerReceiver(receiver,filter);
1
2
3
4
5
6
静态注册





1
2
3
4
5
3. 发送广播

           Intent intent=new Intent();

// action需要与注册广播的action一样
intent.setAction(“MY_ACTION”);
// 传递的消息
intent.putExtra(“msg”,“send Broadcast”);
// 发送
sendBroadcast(intent);
1
2
3
4
5
6
7
4. 设置接受广播的处理函数

public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
//method
String msg=intent.getStringExtra(“msg”);
System.out.println(msg);
Toast.makeText(context,msg,Toast.LENGTH_LONG).show();
}
1
2
3
4
5
6
7
8
2. 例子

MainActivity
public class MainActivity extends AppCompatActivity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 实例化定义好的BroadcastReceiver
MyReceiver receiver=new MyReceiver();
// 实例化过滤器,并设置过滤的广播的action,
IntentFilter filter=new IntentFilter(“MY_ACTION”);
// 注册
registerReceiver(receiver,filter);

button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
// action需要与注册广播的action一样
intent.setAction(“MY_ACTION”);
// 传递的消息
intent.putExtra(“msg”,“send Broadcast”);
// 发送
sendBroadcast(intent);

       }
   });
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
BroadcastReceiver
ublic class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
//method
String msg=intent.getStringExtra(“msg”);
System.out.println(intent.getAction());
System.out.println(msg);
Toast.makeText(context,msg,Toast.LENGTH_LONG).show();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
测试
发送广播后,logcat显示为:
测试结果
在这里我们可以发现,广播接受器与发送的广播是通过intent的action属性来匹配的,当相互action一致,则广播接收器回调onReceive函数执行操作

发布了20 篇原创文章 · 获赞 1 · 访问量 5424

猜你喜欢

转载自blog.csdn.net/yygyyygy1233/article/details/86952982
今日推荐