title: How to get Top Activity name of own App
body: <p>In <code>MainActivity</code> I want to know the current Top <code>Activity</code> opened inside App.</p>
  
  <p>For pre-lollipop I used following</p>
  
  <pre><code>ActivityManager am = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
  ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
  </code></pre>
  
  <p>On other posts I found, I should use:</p>
  
  <pre><code>getAppTasks() and gettaskinfo
  </code></pre>
  
  <p>But I am not able to find any complete example demonstrating how to use the above. Any help is thankful. Regards. </p>
  
  <p>Edit:
  Current code:</p>
  
  <pre><code>if (Build.VERSION.SDK_INT &gt;= 23) {
        cn = am.getAppTasks().get(0).getTaskInfo().topActivity;
  }else{
        cn = am.getRunningTasks(1).get(0).topActivity;
  }
  </code></pre>
  
  <p>am.getRunningTasks is deprecated in API 21. And am.getAppTasks#topActivity is available in API 23. So updated question is how to handle it for API 21 and 22. </p>