当前位置: 首页 > news >正文

高版本Android跨应用广播通信实例

在高版本的Android上,应用间发送广播需要特别注意权限和导出设置。以下是完整的发送和接收广播的代码示例:

1. 发送广播的应用

AndroidManifest.xml 配置

<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.sender"><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"><!-- 发送广播的Activity --><activityandroid:name=".MainActivity"android:exported="true"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application>
</manifest>

MainActivity.java

package com.example.sender;import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;public class MainActivity extends AppCompatActivity {private static final String CUSTOM_ACTION = "com.example.CUSTOM_BROADCAST";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button sendButton = findViewById(R.id.send_button);sendButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {sendCustomBroadcast();}});}private void sendCustomBroadcast() {Intent intent = new Intent(CUSTOM_ACTION);// 添加接收应用的包名,提高安全性(必要,注意是接收应用的包名,不是发送应用的包名)intent.setPackage("com.example.receiver");// 传递数据intent.putExtra("message", "Hello from sender app!");intent.putExtra("timestamp", System.currentTimeMillis());try {// 发送广播sendBroadcast(intent);Toast.makeText(this, "Broadcast sent successfully", Toast.LENGTH_SHORT).show();} catch (Exception e) {Toast.makeText(this, "Failed to send broadcast: " + e.getMessage(), Toast.LENGTH_SHORT).show();}}
}

2. 接收广播的应用

AndroidManifest.xml 配置

<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.receiver"><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"><!-- 接收广播的Activity --><activityandroid:name=".MainActivity"android:exported="true"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><!-- 注册BroadcastReceiver exported必须设置为 true --><receiver android:name=".CustomBroadcastReceiver"android:exported="true"android:enabled="true"><intent-filter><action android:name="com.example.CUSTOM_BROADCAST" /></intent-filter></receiver></application>
</manifest>

CustomBroadcastReceiver.java

package com.example.receiver;import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;public class CustomBroadcastReceiver extends BroadcastReceiver {private static final String TAG = "CustomBroadcastReceiver";@Overridepublic void onReceive(Context context, Intent intent) {if (intent != null && "com.example.CUSTOM_BROADCAST".equals(intent.getAction())) {// 获取传递的数据String message = intent.getStringExtra("message");long timestamp = intent.getLongExtra("timestamp", 0);Log.d(TAG, "Received broadcast: " + message + ", timestamp: " + timestamp);// 显示通知或ToastToast.makeText(context, "Received: " + message, Toast.LENGTH_LONG).show();// 可以启动Activity或Service来处理数据Intent activityIntent = new Intent(context, MainActivity.class);activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);activityIntent.putExtra("received_message", message);context.startActivity(activityIntent);}}
}

MainActivity.java (接收应用的主Activity)

package com.example.receiver;import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;public class MainActivity extends AppCompatActivity {private TextView messageTextView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);messageTextView = findViewById(R.id.message_text);// 检查是否有从广播传递过来的消息String receivedMessage = getIntent().getStringExtra("received_message");if (receivedMessage != null) {messageTextView.setText("Received message: " + receivedMessage);}}
}

3. 布局文件

发送应用的 activity_main.xml

<?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"android:orientation="vertical"android:padding="16dp"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Sender App"android:textSize="24sp"android:layout_marginBottom="32dp" /><Buttonandroid:id="@+id/send_button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Send Broadcast" /></LinearLayout>

接收应用的 activity_main.xml

<?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"android:orientation="vertical"android:padding="16dp"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Receiver App"android:textSize="24sp"android:layout_marginBottom="32dp" /><TextViewandroid:id="@+id/message_text"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Waiting for broadcast..."android:textSize="16sp" /></LinearLayout>

4. 安全注意事项

使用权限保护(可选)

如果需要更高级别的安全保护,可以添加自定义权限:

在接收应用的 AndroidManifest.xml 中添加:

<permission android:name="com.example.receiver.CUSTOM_PERMISSION"android:protectionLevel="signature" /><uses-permission android:name="com.example.receiver.CUSTOM_PERMISSION" />

在发送应用中:

<uses-permission android:name="com.example.receiver.CUSTOM_PERMISSION" />

在发送广播时:

intent.putExtra("message", "Hello from sender app!");
sendBroadcast(intent, "com.example.receiver.CUSTOM_PERMISSION");

关键要点:

  1. 导出:接收广播的组件必须设置 android:exported="true"
  2. 安全性:使用特定的包名和自定义Action来避免广播被其他应用拦截
  3. 权限:根据需要添加适当的权限声明
  4. Intent Filter:确保发送和接收的Action字符串完全匹配

这样配置后,两个应用就可以在Android高版本上正常发送和接收广播了。

http://www.lryc.cn/news/597974.html

相关文章:

  • tensorflow搭建神经网络
  • 遨游三防平板|国产芯片鸿蒙系统单北斗三防平板,安全高效
  • Node.js特训专栏-实战进阶:18.密码加密与安全传输
  • AI赋能软件工程让测试左移更加可实施
  • 【机器学习之推荐算法】基于K最近邻的协同过滤推荐与基于回归模型的协同过滤推荐
  • LeetCode|Day24|383. 赎金信|Python刷题笔记
  • 微服务-springcloud-springboot-Skywalking详解(下载安装)
  • 用 Function Call 让 AI 主动调用函数(超入门级示例)|保姆级大模型应用开发实战
  • Linux 进程间通信:共享内存详解
  • Spring Boot 3整合Spring AI实战:9轮面试对话解析AI应用开发
  • 【OD机试】矩阵匹配
  • 【分布式锁】什么是分布式锁?分布式锁的作用?
  • redis前期工作:环境搭建-在ubuntu安装redis
  • 实验-OSPF
  • 开立医疗2026年校园招聘
  • 【论文|复现】YOLOFuse:面向多模态目标检测的双流融合框架
  • OSPF路由协议单区域
  • Selenium基础教程
  • 在Ubuntu上使用QEMU学习RISC-V程序(2)gdb调试
  • 【OpenCV篇】OpenCV——03day.图像预处理(2)
  • 征服 Linux 网络:核心服务与实战解析
  • 《从点击到共鸣:论坛前端如何用交互细节编织用户体验》
  • GISBox实操指南:如何将IFC文件高效转换为3DTiles格式‌‌
  • JVM 核心内容
  • Java并发编程第六篇(AQS设计理念与源码解析)
  • Linux724 逻辑卷挂载;挂载点扩容;逻辑卷开机自启
  • 快速启用 JMeter(macOS Automator 创建 JMeter 脚本)
  • VUE2 学习笔记5 动态绑定class、条件渲染、列表过滤与排序
  • 【AJAX】XMLHttpRequest、Promise 与 axios的关系
  • 最新免费使用Claude Code指南(Windows macOS/Linux)