一、广播组件
广播,分为系统广播,与用户自定义广播
二、静态注册接收广播
不常见
在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);
}