'Change int value in Android Studio

How do i change the "64" to a random number from 40 to 120 every 20 seconds in Android Studio ?

public class MainActivity extends AppCompatActivity {

    Random rand = new Random();

    @Override
    protected void onCreate(Bundle savedBundleInstance) {
        super.onCreate(savedBundleInstance)
        setContentView(R.layout.activity_main)
    }
}

enter image description here



Solution 1:[1]

Here is a Simple Way to use forever loop which will generate random number between minimum and maximum after every given seconds.

    new Thread(() -> {
        while (true){
            final int min=40, max =120;
            final int second = 20;
            Random random = new Random();
            int rn = random.nextInt(max);
            if (rn<min) rn+=min;
            int randomNumber = rn;
            new Handler(Looper.getMainLooper()).post(() -> {
                //run the code to show random number in UI...
                //tv.setText(""+randomNumber);
                Log.d("xyz", "showNotification: "+ randomNumber);

            });
            try {
                Thread.sleep(1000*second);//sleep for 20 second
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }).start();

Solution 2:[2]

There is different way to do this type of task. One of the easy method is using timer and and calling it after a certain period of time. You can call handler from onResume(). This guy has make it a bit clear https://stackoverflow.com/a/40058010/10926972

Hope it works for you.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 eFortsHub
Solution 2 Lazy Mind