Android: How to get a modal dialog or similar modal behavior?

后端 未结 11 1910
暗喜
暗喜 2020-12-01 05:17

These days I\'m working on simulating modal dialog in Android. I\'ve googled a lot, there\'s much discussions but sadly there\'s not much options to get it modal. Here\'s so

11条回答
  •  醉梦人生
    2020-12-01 05:44

    As hackbod and others have pointed out, Android deliberately doesn't provide a method for doing nested event loops. I understand the reasons for this, but there are certain situations that require them. In our case we have our own virtual machine running on various platforms and we wanted to port it to Android. Internally there a lot of places where it requires a nested event loop, and it isn't really feasible to rewrite the whole thing just for Android. Anyway, here is a solution (basically taken from How can I do non-blocking events processing on Android?, but I have added a timeout):

    private class IdleHandler implements MessageQueue.IdleHandler
    {
        private Looper _looper;
        private int _timeout;
        protected IdleHandler(Looper looper, int timeout)
        {
            _looper = looper;
            _timeout = timeout;
        }
    
        public boolean queueIdle()
        {
            _uiEventsHandler = new Handler(_looper);
            if (_timeout > 0)
            {
                _uiEventsHandler.postDelayed(_uiEventsTask, _timeout);
            }
            else
            {
                _uiEventsHandler.post(_uiEventsTask);
            }
            return(false);
        }
    };
    
    private boolean _processingEventsf = false;
    private Handler _uiEventsHandler = null;
    
    private Runnable _uiEventsTask = new Runnable()
    {
        public void run() {
        Looper looper = Looper.myLooper();
        looper.quit();
        _uiEventsHandler.removeCallbacks(this);
        _uiEventsHandler = null;
        }
    };
    
    public void processEvents(int timeout)
    {
        if (!_processingEventsf)
        {
            Looper looper = Looper.myLooper();
            looper.myQueue().addIdleHandler(new IdleHandler(looper, timeout));
            _processingEventsf = true;
            try
            {
                looper.loop();
            } catch (RuntimeException re)
            {
                // We get an exception when we try to quit the loop.
            }
            _processingEventsf = false;
         }
    }
    

提交回复
热议问题