知识库

wiki.linsakura.com

用户工具

站点工具


wiki:book:notes:android:第一行代码-android-第2版-郭霖:第5章

差别

这里会显示出您选择的修订版和当前版本之间的差别。

到此差别页面的链接

两侧同时换到之前的修订记录 前一修订版
后一修订版
前一修订版
wiki:book:notes:android:第一行代码-android-第2版-郭霖:第5章 [2022/04/06 16:27]
博丽幻月 [发送标准广播]
wiki:book:notes:android:第一行代码-android-第2版-郭霖:第5章 [2022/04/06 18:51] (当前版本)
博丽幻月 [使用本地广播]
行 111: 行 111:
 </code> </code>
 ==== 发送有序广播 ==== ==== 发送有序广播 ====
 +发送方式更改为:\\ 
 +<code java> 
 +sendOrderedBroadcast(intent, null); 
 +</code> 
 +添加''android:priority="100"'',数字大的优先接收到广播:\\ 
 +<code xml AndroidManifest.xml> 
 +            ... 
 +            <intent-filter android:priority="100"> 
 +                <action android:name="android.intent.action.BOOT_COMPLETED" /> 
 +            </intent-filter> 
 +            ... 
 +</code> 
 +最后在''onReceive()''中可以通过''abortBroadcast();''阻止广播继续传递。\\ 
 +===== 使用本地广播 ===== 
 +在MainActivity中添加LocalReceiver类:\\ 
 +<code java> 
 +class LocalReceiver extends BroadcastReceiver{ 
 +    @Override 
 +    public void onReceive(Context context, Intent intent) { 
 +        Toast.makeText(context, "received local broadcast", Toast.LENGTH_SHORT).show(); 
 +    } 
 +
 +</code> 
 +修改onCreate():\\ 
 +<code java> 
 +localBroadcastManager = LocalBroadcastManager.getInstance(this);    //获取实例 
 +intentFilter = new IntentFilter(); 
 +intentFilter.addAction("com.example.broadcasttest.LOCAL_BROADCAST"); 
 +localReceiver = new LocalReceiver(); 
 +localBroadcastManager.registerReceiver(localReceiver, intentFilter); 
 +</code> 
 +在按钮onClick()中添加:\\ 
 +<code java> 
 +Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST"); 
 +localBroadcastManager.sendBroadcast(intent);    //发送本地广播 
 +</code> 
 +onDestroy()添加:\\ 
 +<code java> 
 +localBroadcastManager.unregisterReceiver(localReceiver); 
 +</code>
wiki/book/notes/android/第一行代码-android-第2版-郭霖/第5章.1649233655.txt.gz · 最后更改: 2022/04/06 16:27 由 博丽幻月