-1

I am working with custom keyboard ,I need current package name when keyboard is open . This keyboard will be open with different different application ,so i need that application package name which is open currently. I am using following code but its not working properly.

   ActivityManager mActivityManager = (ActivityManager)PhotoActivity.this.getSystemService(Context.ACTIVITY_SERVICE);
            if(Build.VERSION.SDK_INT > 20){
                String mPackageName = mActivityManager.getRunningAppProcesses().get(0).processName;
                Log.e("Checking package:      ","Checking current application package"+mPackageName);
            }
            else{
                String mPackageName = mActivityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
            }
Mohd Sakib Syed
  • 1,679
  • 1
  • 25
  • 42
  • 1
    This is a duplicate of about a thousand questions. FYI, the hack you're using was broken in Android 5.1.1 and 6.0. The officially sanctioned replacement is the Usage Stats API, but it's not available on all devices. – Kevin Krumwiede Dec 21 '15 at 06:41

3 Answers3

1

getting current package name in android

     ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
     List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);

// display the current class name
         Toast.makeText(getApplicationContext(), taskInfo.get(0).topActivity.getClassName(), Toast.LENGTH_LONG).show();
         ComponentName componentInfo = taskInfo.get(0).topActivity;

// current class package name
             String packageName = componentInfo.getPackageName();

add this to your project manifest permissions

<uses-permission android:name="android.permission.GET_TASKS"/>
0
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);

Log.d("current task :", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getPackageName());
Ravi
  • 34,851
  • 21
  • 122
  • 183
0

Use the following code:-

 ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List l = am.getRecentTasks(1, ActivityManager.RECENT_WITH_EXCLUDED);
Iterator i = l.iterator();
PackageManager pm = this.getPackageManager();
while (i.hasNext()) {
    ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo)(i.next());
    try {
        CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(
        info.processName, PackageManager.GET_META_DATA));
        Log.w("LABEL", c.toString());
    } catch (Exception e) {
        // Name Not FOund Exception
    }
}

And do not forget to use the permission

<uses-permission android:name="android.permission.GET_TASKS"/>
Ravindra Kushwaha
  • 7,846
  • 14
  • 53
  • 103