DialogFragment背景下的有效轮询

时间:2019-09-02 14:40:59

标签: java android android-activity android-dialogfragment polling

我正在尝试轮询包含来自另一个DialogFragment的API调用的活动中的方法,并带有维护屏幕,该屏幕显示API调用何时失败,然后在成功时关闭。

问题在于,根据当前的现有代码,该片段将被堆叠并附加多次。我需要将其设为Fragment的单个实例,但不能使用singleton片段。

目标:在api调用失败并成功删除时显示维护页面。

我的活动具有以下方法:

void someMethodForAPICall() {

if(APICallSuccess()) {
//do task 
} else {

          NetworkErrorDialog networkErrorDialog = NetworkErrorDialog.Companion.getNetworkErrorDialog(4, null);
          networkErrorDialog.setCancelable(false);
          networkErrorDialog.show(getSupportFragmentManager(), "NetworkErrorDialog");
}

 }

我的DialogFragment:

class NetworkErrorDialog : DialogFragment() {

  private var retryClick : NetworkErrorDialog.RetryClick? = null

  companion object {
    private const val REQUEST_CODE = "request_code"
    fun getNetworkErrorDialog(requestCode: Int, bundle: Bundle?): NetworkErrorDialog = NetworkErrorDialog().apply {
      arguments = Bundle().apply {
        putInt(REQUEST_CODE, requestCode)
        bundle?.let {
          putAll(it)
        }
      }
    }
  }


  override fun onAttach(context: Context?) {
    super.onAttach(context)
    if (parentFragment is NetworkErrorDialog.RetryClick) {
      retryClick = parentFragment as NetworkErrorDialog.RetryClick
    } else if (context is NetworkErrorDialog.RetryClick) {
      retryClick = context
    }
  }

  override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
  ): View? {
    return inflater.inflate(R.layout.maintenance_dialog, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    mBinding = DataBindingUtil.bind(view)
    mBinding?.tvRetry?.setOnClickListener {
      dismiss()
      retryClick?.callRetryClick(arguments?.getInt(REQUEST_CODE), arguments)
    }
  }

  override fun onResume() {
    super.onResume()
    //do polling based on requestCode
    val handlerTimer = Handler()
    handlerTimer.postDelayed({
      retryClick?.callRetryClick(arguments?.getInt(REQUEST_CODE), arguments)
    }, 5000)
  }

  interface RetryClick {
    fun callRetryClick(requestCode : Int?, data : Bundle?)

    fun onDismiss(requestCode : Int?, data : Bundle?)
  }
}

0 个答案:

没有答案