I'm new to both android and java, now im trying to update a textview with the state of the call, but the view model doesn't get the value from the telephony callback class.
Im using post value since app goes background when it rings.
The permissions for read_phone_state and call_phone are given on mainActivity.
CallstateListener class
public class CallStateListener extends TelephonyCallback implements TelephonyCallback.CallStateListener {
private MutableLiveData<String> callState = new MutableLiveData<>();
//Construtor com ref ao viewmodel
public CallStateListener() {
}
@Override
public void onCallStateChanged(int state) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
callState.postValue("IDLE");
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
callState.postValue("OFFHOOK");
break;
case TelephonyManager.CALL_STATE_RINGING:
callState.postValue("RINGING");
break;
default:
callState.postValue("NULL");
break;
}
}
public MutableLiveData<String> getCallState() {
return callState;
}
viewmodel
public class LteViewModel extends ViewModel {
private CallStateListener callState = new CallStateListener();
private MutableLiveData<String> state;
public LteViewModel() {
state = new MutableLiveData<>();
state = callState.getCallState();
}
public LiveData<String> getCallState(){ return state;}
}
fragment with registerTelephonyCallback and method to update the textview which is named mIntraHOLte
public class LteFragment extends Fragment {
private FragmentLteBinding binding;
private LteViewModel lteViewModel;
public TelephonyManager telephonyManager;
public CallStateListener callStateListener;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
callStateListener = new CallStateListener();
telephonyManager = (TelephonyManager) requireActivity().getSystemService(TELEPHONY_SERVICE);
lteViewModel =
new ViewModelProvider(this).get(LteViewModel.class);
binding = FragmentLteBinding.inflate(inflater, container, false);
View root = binding.getRoot();
TextView mIntraHOLte = binding.titleLteIntraho;
telephonyManager.registerTelephonyCallback(Runnable::run, callStateListener);
lteViewModel.getCallState().observe(getViewLifecycleOwner(), mIntraHOLte::setText);
return root;
}
@Override
public void onDestroyView() {
super.onDestroyView();
telephonyManager.unregisterTelephonyCallback(callStateListener);
}
}