public class ReceiverLiveData extends LiveData {
private final Context context;
private final IntentFilter filter;
private final BiFunction mapFunc;
public ReceiverLiveData(Context context, IntentFilter filter, BiFunction mapFunc) {
this.context = context;
this.filter = filter;
this.mapFunc = mapFunc;
}
@Override
protected void onInactive() {
super.onInactive();
context.unregisterReceiver(mBroadcastReceiver);
}
@Override
protected void onActive() {
super.onActive();
setValue(mapFunc.apply(context, new Intent()));
context.registerReceiver(mBroadcastReceiver, filter);
}
private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
setValue(mapFunc.apply(context, intent));
}
};
}
public static class ViewModel extends AndroidViewModel {
public final LiveData batteryIntentLiveData = new ReceiverLiveData<>(getApplication(), new IntentFilter(Intent.ACTION_BATTERY_CHANGED), (context, intent) -> intent);
public final LiveData activeNetworkInfoLiveData = new ReceiverLiveData<>(getApplication(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION), ((context, intent) -> ((ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE)).getActiveNetworkInfo()));
public ViewModel(@NonNull Application application) {
super(application);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater());
binding.setViewModel(new ViewModelProvider(this).get(ViewModel.class));
binding.setLifecycleOwner(this);
setContentView(binding.getRoot());
}