Android基础学习(十二)—— BroadcastReceiver

一、广播组件

广播,分为系统广播,与用户自定义广播

二、静态注册接收广播

不常见

在AndroidManifest.xml清单文件中注册

<receiver android:name=".CustomReceiver">
    <intent-filter>
    	<action android:name="com.derry.receiver_flag_"/>
    </intent-filter>
</receiver>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="发送广播"
    android:onClick="sendAction2"
   />
public class CustomReceiver extends BroadcastReceiver{
    
    private static final String TAG = CustomReceiver.class.getSimpleName();
    
    @Override
    public void onReceive(Context context, Intent intent){
        Log.e(TAG, "CustomReceiver onReceive 广播接收者");
    }
}
public interface ActionUtils{
    //广播注册时 与 发送广播时 的唯一标识,必须要保持一致(给动态注册用)
    String ACTION_EQUES_UPDATE_IP = "com.derry.receiver_study_";
    
    //广播注册时 与 发送广播时 的唯一标识,必须要保持一致(给静态注册用)
    String ACTION_FLAG = "com.derry.receiver_flag_";
}
public class MainActivity4 extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main4);
    }
    
    //静态发送广播给接收者
    public void sendAction2(View view){
        Intent intent = new Intent();
        //action 与注册时保持一致
        intent.setAction(ActionUtils.ACTION_FLAG);
        sendBroadcast(intent);
    }
}

三、动态注册接收广播

不需在清单文件中注册

1、定义广播接收者

public class UpdateIpSelectCity extends BroadcastReceiver{
    
    private static final String TAG = UpdateIpSelectCity.class.getSimpleName();
    
    @Override
    public void onReceive(Context context, Intent intent){
        Log.e(TAG, "UpdateIpSelectCity onReceive 广播接收者");
    }
}

2、在 Activity 中注册广播接受者

//MainActivity
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    UpdateIpSelectCity updateSelectCity = new UpdateIpSelectCity();
    IntentFilter filter = new IntentFilter();
    filter.addAction(ActionUtils.ACTION_EQUES_UPDATE_IP);
    registerReceiver(updateSelectCity, filter);
}

3、在 Activity 中 发送给 动态注册的接收者

 //静态发送广播给接收者
 public void sendAction2(View view){
      Intent intent = new Intent();
      //action 与注册时保持一致
       intent.setAction(ActionUtils.ACTION_EQUES_UPDATE_IP);
       sendBroadcast(intent);
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值