Android - Open Random Activity

1

Well, my question is: Can I make a function call a Random Activity?

    
asked by anonymous 07.05.2018 / 22:00

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);
    
07.05.2018 / 22:18
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 way I find it more interesting to open a random activity would be to use the nextInt() function 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 the Activity, you could do something like this:

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

I've used this answer and this other answer .

    
07.05.2018 / 22:18