Android - Open Random Activity

Asked

Viewed 64 times

1

Well, my question is this: is it possible to make a function call a Random Activity?

2 answers

4


Random r = new Random();
int randomIndex = r.nextInt(5); // Index aleatorio de 0 a 4

Class<?>[] activities = new Class<?>[]{
        Activity1.class,
        Activity2.class,
        Activity3.class,
        Activity4.class,
        Activity5.class
};

Intent intent = new Intent(this, activities[randomIndex]);
startActivity(intent);

1

Yes, it is possible.

The way to open an Activity on Android is through Intents, as below:

Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Parametros opcionais
CurrentActivity.this.startActivity(myIntent);

In this case, the most interesting way to open a random Activity would be by using the function nextInt() of the Random class.

Random r = new Random();
int i = r.nextInt(numero de resultados possiveis) + resultado inicial;
// Por exemplo, gerar um numero de 65(incluído)-80(excluido), você usaria nextInt(80 - 65) + 65

With the random decision made, we can launch Activity, you could do something like this:

switch (randomNumber) {
    case 1: abre activity 1; break;
    case 2: abre activity 2; break;
    .
    .
    .
}

I used that answer and this other answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.