Ram Vignesh
Ram Vignesh

Reputation: 3

How to start an activity at a given time in future?

I want to start an activity on a particular time if the app is open. Basically I am having a Firestore Timestamp (future timestamp only), I want to start the activity in the timestamp time only. Also the user should not be able to hack the time (like increase their local device time)and start the activity before only. The activity should only start automatically if the user is inside the app....If app is closed or app is in background the activity should not start. I heard somewhere to use pending intent but how can I implement this i am not getting the direction.

Upvotes: 0

Views: 273

Answers (1)

Maede Jalali
Maede Jalali

Reputation: 326

You need to use a JobScheduler and on its onStartJob you can start your activity.

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        val jobScheduler =
            context.getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler?
        val componentName = ComponentName(context, MyJobService::class.java)
        val jobInfoObj =
            JobInfo.Builder(REQUEST_CODE, componentName)
                .setMinimumLatency(x)
                .build()
        jobScheduler?.schedule(jobInfoObj)
    }

In the above code in setMinimumLatency(x) you can replace x with the amount of time that you need. also MyJobService is a class which you have to implement it like this:

class MyJobService : JobService() {

override fun onStartJob(params: JobParameters?): Boolean {
    return false
}

override fun onStopJob(params: JobParameters?): Boolean {
    return false
}

}

then in onStartJob you can simply start your activity.

just make sure that you add your service to the manifest.

Upvotes: 1

Related Questions