Skip to content

Instantly share code, notes, and snippets.

@erdemtopak
Created March 13, 2019 16:49
Show Gist options
  • Save erdemtopak/912e44158bcc760d00f9678b1f8e8202 to your computer and use it in GitHub Desktop.
Save erdemtopak/912e44158bcc760d00f9678b1f8e8202 to your computer and use it in GitHub Desktop.
Restart Android Application
package com.erdem.test;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.PersistableBundle;
import android.support.annotation.RequiresApi;
import static android.content.Context.JOB_SCHEDULER_SERVICE;
public class RestartApp {
public static void restartThroughPendingIntentAlarmManager(Context context) {
int delayTime = 1000;
Context currentActivity = context;
Intent intent = new Intent(currentActivity, MainActivity.class);
AlarmManager mAlarmManager = (AlarmManager) currentActivity.getSystemService(Context.ALARM_SERVICE);
PendingIntent restartIntent = PendingIntent.getActivity(currentActivity, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
mAlarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + delayTime, restartIntent);
System.exit(0);
}
public static void restartThroughIntentCompatMakeRestartActivityTask(Context context) {
Context currentActivity = context;
Intent intent = new Intent(currentActivity, MainActivity.class);
Intent restartIntent = Intent.makeRestartActivityTask(intent.getComponent());
currentActivity.startActivity(restartIntent);
System.exit(0);
}
public static void restartThroughPendingIntentJobScheduler(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
restartThroughPendingIntentJobSchedulerInternal(context);
} else {
restartThroughPendingIntentAlarmManager(context);
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private static void restartThroughPendingIntentJobSchedulerInternal(Context context) {
int delayTimeMin = 1000;
int delayTimeMax = 2000;
JobInfo.Builder jobInfoBuild = new JobInfo.Builder(0, new ComponentName(context, JobSchedulerService.class));
jobInfoBuild.setMinimumLatency(delayTimeMin);
jobInfoBuild.setOverrideDeadline(delayTimeMax);
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(jobInfoBuild.build());
System.exit(0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment