how to broadcast Receiver and MVVM?

后端 未结 2 1907
星月不相逢
星月不相逢 2021-01-27 19:23

my manifest


            
                

        
2条回答
  •  隐瞒了意图╮
    2021-01-27 19:40

    1. define base class for LiveData of BroadcastReceiver
    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));
            }
        };
    }
    
    1. declare your variable in ViewModel, for example battery change 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);
            }
        }
    
    1. initialize ViewModel in Activity::onCreate
        @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());
        }
    
    1. use batteryIntentLiveData & activeNetworkInfoLiveData in your DataBinding layout
    
    
    
        
    
            
    
            
    
            
        
    
        
    
            
    
            
    
            
    
        
    
    

提交回复
热议问题