Android 6.0: Get package name of current activity [duplicate]

白昼怎懂夜的黑 提交于 2019-11-26 17:25:11

问题


How to get current activity package name? as getRunningAppProcesses() not working in Android 6.0.

Below is my code:

grdPhoto.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        //get package name of current running application.
        ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        packageName = mActivityManager.getRunningAppProcesses().get(1).processName;

        Log.e("Package name:===========      ", "Package name     " + packageName);

    }
});

回答1:


Get the package name:

getApplicationContext().getPackageName();

Refer to this as well: Get package name.




回答2:


This code is unnecessary:

//get package name of current running application.
ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
packageName = mActivityManager.getRunningAppProcesses().get(1).processName;

Try this:

grdPhoto.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //get package name of current running application.
        Log.e("Package name:===========      ", "Package name     " + getApplicationContext().getPackageName());
           }
});

If that doesn't work, you know there's a problem with your ontemclicklistener, so try this in your oncreate method or as a log to show proof that getApplicationContext().getPackageName() will get the correct application package name.

Toast.makeText(this, getApplicationContext().getPackageName(),Toast.LENGTH_SHORT).show();


来源:https://stackoverflow.com/questions/34528283/android-6-0-get-package-name-of-current-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!