Returns Package name of top activity - Android Activity

Android examples for Activity:Top Activity

Description

Returns Package name of top activity

Demo Code


//package com.java2s;
import java.util.List;
import android.app.ActivityManager;

import android.app.ActivityManager.RunningTaskInfo;
import android.content.ComponentName;
import android.content.Context;

public class Main {
    /**//from w w w  .ja v  a 2 s  . c  o  m
     * Returns Package name of top activity
     * @param context Context to provide activity information
     * @return String representing package name of top activity
     */
    public static String getTopActivityPackageName(Context context) {
        ComponentName activity = getTopActivity(context);
        if (activity == null) {
            return null;
        }
        return activity.getPackageName();
    }

    private static ComponentName getTopActivity(Context context) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        if (am == null) {
            return null;
        }
        List<RunningTaskInfo> info = am.getRunningTasks(1);
        if (info == null) {
            return null;
        }
        ComponentName activity = info.get(0).topActivity;
        return activity;
    }
}

Related Tutorials