Why my refreshing is slower after few secounds than immediately after start

点点圈 提交于 2019-12-13 20:12:14

问题


I am beginner in android and I am doing my test project. I have such a problem when I start the Handler method then let's say refreshing is approximately desired. But after few secounds this is slower than in the begin, immediately after clicking startGameButton

There are two handler nested to make screen refreshing.

The following code is nested in onCreate() method

    final Handler handler = new Handler();

    final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            MainLoopClass mainLoop;     
            mainLoop=newMainLoopClass(HelperMethods.context,HelperMethods.rl);
            handler.postDelayed(this, 100);
        }
    };

    ...

    startGameButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            handler.postDelayed(runnable, 100);
        }
    });

My desired effect is to make refresh every 700 milisecounds


回答1:


It seems what your code have perfomance side effect Better solution for your problem is 1. Add RxJava in your app:gradle

android {
    ...
}

dependencies {
    ...
    implementation 'io.reactivex.rxjava2:rxjava:2.2.6'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
    ...
}

add

val disposable = Observable.interval(700, TimeUnit.MILLISECONDS)
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe {
        //refresh your UI here        
    }

PS:

  1. If you call subscribe in MainThread
.observeOn(AndroidSchedulers.mainThread())

is not necessary

  1. When you want to stop update your UI (for example in onStop) - call disposable.dispose()


来源:https://stackoverflow.com/questions/57490798/why-my-refreshing-is-slower-after-few-secounds-than-immediately-after-start

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!