androidandroid-servicedelaystart-activity

How to start activity after x seconds from service class in android


I have a service class which has to launches an activity after x seconds

after = intent.getIntExtra("After", 0);
Toast.makeText(this, " Started", Toast.LENGTH_SHORT).show();

new Handler().postDelayed(() -> {
    Intent dialogIntent = new Intent(this, MainActivity2.class);
    SharedPreferences sharedPreferences = getSharedPreferences("USERDATA", MODE_PRIVATE);
    dialogIntent.putExtra("screen", sharedPreferences.getString("screen", "ios"));
    dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    this.startActivity(dialogIntent);
}, after);

This is my all service class code

Thanks in Advance


Solution

  • You can try this

    Intent dialogIntent = new Intent(this, MainActivity2.class);
    SharedPreferences sharedPreferences = getSharedPreferences("USERDATA", MODE_PRIVATE);
    dialogIntent.putExtra("screen", sharedPreferences.getString("screen", "ios"));
    dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    Handler handler = new Handler();
    
            handler.postDelayed(new Runnable() {
                public void run() {
                    this.startActivity(dialogIntent);
                }
            }, after);