title: Cycle through the recently opened application in android
body: <p>Please help me to cycle through the recently opened application in android. for example, if I have 1, 2, 3, 4, 5 and now I'm in the application 3 and I want to go to 2 and 1 application, in the same way, I want to go to 4 and 5 application.</p>
  <p>I have used the below code to navigate to the next app, but it did not work as expected.</p>
  <pre class="lang-java prettyprint-override"><code>final Intent intent = new Intent(Intent.ACTION_MAIN);
  final ActivityManager am = (ActivityManager) mContext
                              .getSystemService(Context.ACTIVITY_SERVICE);
  String defaultHomePackage = &quot;com.android.launcher&quot;;
  intent.addCategory(Intent.CATEGORY_HOME);
  final ResolveInfo res = mContext.getPackageManager().resolveActivity(intent, 0);
  if (res.activityInfo != null &amp;&amp; !res.activityInfo.packageName.equals(&quot;android&quot;)) {
      defaultHomePackage = res.activityInfo.packageName;
  }
  List &lt;ActivityManager.RunningTaskInfo&gt; tasks = am.getRunningTasks(5);
  // lets get enough tasks to find something to switch to
  // Note, we'll only get as many as the system currently has - up to 5
  while ((lastAppId == 0) &amp;&amp; (looper &lt; tasks.size())) {
      packageName = tasks.get(looper).topActivity.getPackageName();
      if (!packageName.equals(defaultHomePackage) &amp;&amp; !packageName.equals(&quot;com.android.systemui&quot;)) {
          lastAppId = tasks.get(looper).id;
      }
      looper++;
  }
  if (lastAppId != 0) {
      am.moveTaskToFront(lastAppId, ActivityManager.MOVE_TASK_NO_USER_ACTION);
  } else {
      Toast.makeText(mContext, mStrNoPrevApp, Toast.LENGTH_SHORT).show();
  }
  </code></pre>