• Android BroadcastReceiver应用


    1. 创建Receiver,两种方式,动态和静态:

      (1)静态注册:

     首先自定义个Receiver,

    public class MyReceiver extends BroadcastReceiver {

        @Override
        
    public void onReceive(Context context, Intent intent) {
            
    // TODO Auto-generated method stub
            Toast.makeText(context, "MyReceiver broadcast"10000).show();
        }

    }

    然后在AndroidManifest注册即可:

            <receiver android:name=".MyReceiver">
                
    <intent-filter>
                    
    <action android:name="com.test.broadcasting" />
                
    </intent-filter>
            
    </receiver>

      (2)动态注册:

        private void regReceiver() {
            IntentFilter intentFilter 
    = new IntentFilter();
            intentFilter.addAction(
    "com.test.broadcasting");
            
    // 注册BroadcastReceiver
            this.registerReceiver(receiver, intentFilter);

            
    // 取消注册
            
    // this.unregisterReceiver(receiver);
        }

        
    private BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            
    public void onReceive(Context context, Intent intent) {
                Toast.makeText(context, 
    "receive broadcast"10000).show();
            }
        };

        2.发送广播:

    这个非常简单,只需一行代码即可:

    this.sendBroadcast(new Intent("com.test.broadcasting"));

    3. 应用场景:

      最常见的就是SD插拔的广播注册(android.content.Intent.ACTION_MEDIA_MOUNTED).

  • 相关阅读:
    序列化限流排序
    linux常用命令
    Django路径问题
    asp.net 后台 修改 javascript 变量
    支持 IE8 IE11 和 FF, Chrome 浏览器的圆角
    Asp.net Response.Redirect with post data
    gridview 字段没有绑定由于column visible= false
    聪明的小技巧
    GridView
    各种集合
  • 原文地址:https://www.cnblogs.com/KiloNet/p/1916093.html
Copyright © 2020-2023  润新知