Android 6.0:获取当前活动的包名称

时间:2015-12-30 11:06:45

标签: android android-activity android-6.0-marshmallow android-package-managers

如何获取当前活动包名称?由于getRunningAppProcesses()无法在Android 6.0中运行。

以下是我的代码:

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

    }
});

2 个答案:

答案 0 :(得分:4)

获取包名称:

getApplicationContext().getPackageName();

请参阅此内容:Get package name.

答案 1 :(得分:2)

此代码是不必要的:

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

试试这个:

getApplicationContext().getPackageName()

如果这不起作用,您知道ontemclicklistener存在问题,请在您的oncreate方法或日志中尝试此操作,以证明Toast.makeText(this, getApplicationContext().getPackageName(),Toast.LENGTH_SHORT).show(); 将获得正确的应用程序包名。

<body>
<div id="container">
    <div id="background"></div>
  <div id="dialog">
        <p>Hello there!</p>
    </div>
    <div id="button" onclick="showDialog()">
        <img src="images/images/sceond3.jpg" width="126" height="210" alt=""/>
    </div>
</div>
</body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>

var counter = 0;
function showDialog() {
    if (counter == 0) {
        $("#dialog p").html("Testing Second Line!");
    }
    if (counter == 1) {
        $("#dialog p").html("Testing Third Line!");
    }
    if (counter == 2) {
        window.location.href = 'third.html';
    }
    //increase counter by 1
    counter++;
}

</script>
</html>