-3

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

Nice Books
  • 1,675
  • 2
  • 17
  • 21
Flashsloth
  • 25
  • 5

2 Answers2

0

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.

Lazy Mind
  • 143
  • 9
0

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();
eFortsHub
  • 28
  • 5
  • the thread will run forever even you pause the app so better to assign the thread in a private variable like Thread thread; and then init the thread with given number in onResume() method, and call thread.interrupt(); inside onPause() method – eFortsHub Mar 21 '22 at 13:28