【问题标题】:Android get package name of current opened application [duplicate]Android获取当前打开的应用程序的包名[重复]
【发布时间】:2016-03-27 04:34:15
【问题描述】:

我正在使用自定义键盘,当键盘打开时我需要当前包名称。该键盘将使用不同的不同应用程序打开,因此我需要当前打开的应用程序包名称。我正在使用以下代码,但它无法正常工作。

   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();
            }

【问题讨论】:

  • 这是大约一千个问题的副本。仅供参考,您使用的 hack 在 Android 5.1.1 和 6.0 中被破坏。官方认可的替代品是 Usage Stats API,但并非在所有设备上都可用。

标签: android package-managers custom-keyboard


【解决方案1】:

在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();

将此添加到您的项目清单权限

<uses-permission android:name="android.permission.GET_TASKS"/>

【讨论】:

    【解决方案2】:
    ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
    
    Log.d("current task :", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getPackageName());
    

    【讨论】:

    • 这个 hack 在 Android 5.0 中被破坏了。
    【解决方案3】:

    使用以下代码:-

     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
        }
    }
    

    别忘了使用权限

    <uses-permission android:name="android.permission.GET_TASKS"/>
    

    【讨论】:

    • 您好,Ravindra Kushwaha,感谢您的回复。它无法正常工作,因为它获得了自定义键盘的相​​同包名称,而不是当前正在运行的打开的应用程序。我在 Android 5.0 中使用
    • @SakibSyed ...好的...让我试试...
    猜你喜欢
    • 2022-12-30
    • 2016-03-28
    • 1970-01-01
    • 2016-04-03
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 2012-12-21
    • 2016-04-04
    相关资源
    最近更新 更多