Search code examples
androidalarmmanagerandroid-alarms

How to close activity completely so that I can prevent user to start the activity


I use AlarmManager to start an activity at specific time

Intent intent = new Intent(getApplicationContext(),AlarmActivity.class);
PendingIntent sender = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, 24);
calendar.set(Calendar.HOUR_OF_DAY, 7);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0);

AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(getApplicationContext().ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);

This is the code of AlarmActivity, when the activity started, it will play alarm sound, if user tap on screen, alarm will be dismissed.

public class AlarmActivity extends Activity {

    MediaPlayer mediaPlayer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm);
        View v =((ViewGroup)findViewById(android.R.id.content)).getChildAt(0);
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        try {
            Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setLooping(true);
            mediaPlayer.setDataSource(this, notification);
            mediaPlayer.prepare();
            mediaPlayer.start();
        }
        catch(Exception e)
        {
        }


    }

    public void onDestroy() {
        super.onDestroy();
        mediaPlayer.stop();
        mediaPlayer.release();

    }

}

When this activity closed, it is still in the recent app list, if user click on recent app, this activity will start and play sound again

I also tried this, but it is useless

android.os.Process.killProcess(android.os.Process.myPid());

AlarmActivity must only be started by AlarmManager, user should not able to start it. How can I close my app completely?


Solution

  • Use android:excludeFromRecents="true" in the manifest of your activity

    http://developer.android.com/guide/topics/manifest/activity-element.html#exclude