简体   繁体   中英

How Can get my App to Startup On Random Activity?

How can I get my app to start on random activity?

for example, i have 10 Activity ..What i want is on each time my app startup it open on one of 10 Activity randomly.

Please help, .

Make use of java.util.Random

You can use it return a random integer number between 0 and a particular number.

Then use that random value to start your activities.

To start a random activity during the start of your app, you will need to use a dummy activity as the launcher activity and start a random activity from there and finish that dummy activity.

For eg.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Random random = new Random();
        int index = random.nextInt(10); // assuming you have 10 activities.

        switch (index) {
            case 0:
                // start activity 1
                break;
            case 1:
                // start activity 2
                break;
            // other cases

        }

        finish();
    }

}

In you splash activity do write following code

List<Intent> intents = new ArrayList<>();

intents.add(new Intent(this,Random1Activity.class));
intents.add(new Intent(this,Random2Activity.class));
intents.add(new Intent(this,Random3Activity.class));

Random rand = new Random();
int  n = rand.nextInt(intents.size()) + 0;

new Handler().postDelayed(new Runnable(){
        @Override
        public void run() {
            startActivity(intents.get(n));
            finish();
        }
}, 1000);

here is complete code , instead of thread use handler

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM