Search code examples
androidalarmmanagerandroid-alarms

How to force an activity to close before it starts ?


I'm doing an alarm application and I'm using a method to start an activity in specific time, and I have an option in my application which called enable\disable and I do not want the alarm to open the activity (which play the sound and having an image I've chosen) when I check the disable box! So I'm looking for a way to close the activity before it starts & do not make any display on the screen to show that the activity is starting and closing! I'm using this method for opening specific activity in specific time

     Intent myIntent = new Intent(SharedPrefs.this,MainPhoto.class);
     pendingIntent = PendingIntent.getActivity(MainPhoto.this, 0, myIntent, 0);
     AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
     Calendar calendar = Calendar.getInstance();
     calendar.setTimeInMillis(System.currentTimeMillis()+10000);
     alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

Any help in this?


Solution

  • Canceling the alarm is the probably the best solution here.

    There may be some rare cases where you don't know until after the activity is already called. In these cases just call finish() before setContentView

     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            if (/* Check here if valid */) {
                finish();
            } else {
                setContentView(R.layout.some_layout);
                /* Actually do your initialization. */
            }
        }