Search code examples
javaandroidhandler

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


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


Solution

  • 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()