Android 广播接收者(具体例子)
16lz
2021-01-23
Android 广播接收者
1.简介
在现实生活中,很多人会收听广播,例如,通过广播收听音乐。同样在Android系统中也内置了很多广播,例如手机开机会发送一条广播,电量不足也会发送一条广播等等。
为了监听这些广播事件,Android系统提供了一个BroadcastReceiver(广播接收者)组件,该组件可以监听来自系统或者应用程序的广播。
2.例子
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/bg" tools:context=".MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="发送求救广播!" android:onClick="send" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:paddingLeft="5dp" android:paddingRight="5dp" android:background="#FFD2D2" android:textSize="20sp" />RelativeLayout>
MainActivity.java
package com.example.forhelp;import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.view.View;public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void send(View view){ Intent intent = new Intent(this,MyBroadcastReceiver.class); //定义广播的事件类型 intent.setAction("Help_stitch"); //发送广播 sendBroadcast(intent); }}
SpSaveQQ.java
package com.example.forhelp;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.util.Log;public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.i("MyBroadcastReceiver","自定义广播接受者,收到了求救广播事件"); Log.i("MyBroadcastReceiver",intent.getAction()); }}
运行截图:
点击按钮
log打印出以下信息,成功!
更多相关文章
- 如何使Android应用程序获取系统权限来修改系统时间
- Android7.0 系统启动流程---system_server
- Android系统服务 WMS与AMS简单理解
- 室内定位导航系统设计实现指南
- Android系统框架简单理解
- Android代码里或者XML设置android:clickable="false"无效。点击
- android 文件系统分析
- 第一章:Android系统介绍android虚拟机
- [置顶] Android系统移植与调试之------->如何修改Android设备存