Restarts an activity wherever the method is run. - Android Activity

Android examples for Activity:Activity Feature

Description

Restarts an activity wherever the method is run.

Demo Code


import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

public class Main {
  /**//w w  w .  java  2s  . c  om
   * Restarts an activity wherever the method is run.
   * 
   * @param activity
   *          activity to be restarted.
   */
  public static void restart(Activity activity) {
    try {
      Intent i = activity.getPackageManager().getLaunchIntentForPackage(activity.getPackageName());
      i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      int mPendingIntentId = 223344;
      PendingIntent mPendingIntent = PendingIntent.getActivity(activity, mPendingIntentId, i,
          PendingIntent.FLAG_CANCEL_CURRENT);
      AlarmManager mgr = (AlarmManager) activity.getSystemService(Context.ALARM_SERVICE);
      mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
      System.exit(0);
    } catch (Exception e) {
      e.printStackTrace();
      activity.finish();
    }
  }
}

Related Tutorials