跨应用发送和接收广播

跨应用发送和接收广播,与同应用下的情况差不多,只需要添加一个权限,以及配置一下receiver的android:process属性即可

 

 

发送广播的应用中:

 

Java代码   收藏代码
  1. Intent intent = new Intent("info.zhegui.receiver.interprocess");  
  2. sendBroadcast(intent);  

 注意要在manifest.xml添加接收广播的权限,这个权限是receiver自定义的

Java代码   收藏代码
  1. <uses-permission android:name="info.zhegui.receiver.RECEIVE"/>  

 

接收广播的应用中:

Java代码   收藏代码
  1. public class MyReceiver extends BroadcastReceiver {  
  2.     private final String TAG = this.getClass().getName();  
  3.   
  4.     @Override  
  5.     public void onReceive(Context content, Intent intent) {  
  6.         Log.i(TAG, "intent:" + intent);  
  7.     }  
  8.   
  9. }  

 在manifest.xml中添加自定义权限,以及配置receiver的几个属性

Java代码   收藏代码
  1. <permission android:name="info.zhegui.receiver.RECEIVE" />  
  2.   
  3. <application  
  4.     android:allowBackup="true"  
  5.     android:icon="@drawable/ic_launcher"  
  6.     android:label="@string/app_name"  
  7.     android:theme="@style/AppTheme" >  
  8.     <receiver  
  9.         android:name="info.zhegui.receiver.MyReceiver"  
  10.         android:exported="true"  
  11.         android:permission="info.zhegui.receiver.RECEIVE"  
  12.         android:process=":remote" >  
  13.         <intent-filter>  
  14.             <action android:name="info.zhegui.receiver.interprocess" />  
  15.         </intent-filter>  
  16.     </receiver>  
  17. </application>  

 

 

需要注意的三个地方:

1,自定义权限

2,android:exported="true"

3,android:process=":remote" (有时候可以不要该属性)

 

参考文档:

http://developer.android.com/guide/topics/manifest/receiver-element.html

http://developer.android.com/training/articles/security-tips.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 广播可以实现应用通信,即一个应用程序发送广播,另一个应用程序接收广播。这种应用通信的方式可以用于实现不同应用程序之间的协作和数据交换。 具体来说,广播分为两种类型:标准广播和有序广播。标准广播是一种完全异步的广播机制,即发送者不需要等待接收者的响应,接收者也不能阻止其他接收接收广播。而有序广播则是一种同步的广播机制,即广播发送者会依次将广播发送给每个接收者,并且每个接收者都可以在接收广播后终止广播或将广播继续传递给下一个接收者。 如果你想实现应用广播,需要在发送广播时指定广播的 Action 和 Package,以及在接收广播时声明相应的 Intent Filter。具体来说,可以使用以下代码在一个应用程序中发送广播: ```java Intent intent = new Intent(); intent.setAction("com.example.MY_ACTION"); intent.setPackage("com.another.application.package"); sendBroadcast(intent); ``` 在另一个应用程序中,可以使用以下代码声明广播接收器,并在 Manifest 文件中注册该接收器: ```java public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if ("com.example.MY_ACTION".equals(intent.getAction())) { // 处理接收到的广播 } } } ``` ```xml <receiver android:name=".MyBroadcastReceiver"> <intent-filter> <action android:name="com.example.MY_ACTION" /> </intent-filter> </receiver> ``` 需要注意的是,为了保证广播的安全性和合法性,Android 8.0 及以上版本对广播发送接收做了一些限制,具体可以参考官方文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值