获取应用程序目录

有人知道如何获取应用程序目录的路径吗? (例如 /data/data/my.app.lication/)

目前我正在使用这种方法: myActivity.getFilesDir().getParent();,但在我看来,当有更简单的解决方案时,它似乎是一种解决方案。另外,副作用是创建了不需要的 files目录。

澄清: 首先-感谢回复。我试图理解是否已经存在这样做的方法,而不是另一种解决办法。

212773 次浏览

If you're trying to get access to a file, try the openFileOutput() and openFileInput() methods as described here. They automatically open input/output streams to the specified file in internal memory. This allows you to bypass the directory and File objects altogether which is a pretty clean solution.

PackageManager m = getPackageManager();
String s = getPackageName();
PackageInfo p = m.getPackageInfo(s, 0);
s = p.applicationInfo.dataDir;

If eclipse worries about an uncaught NameNotFoundException, you can use:

PackageManager m = getPackageManager();
String s = getPackageName();
try {
PackageInfo p = m.getPackageInfo(s, 0);
s = p.applicationInfo.dataDir;
} catch (PackageManager.NameNotFoundException e) {
Log.w("yourtag", "Error Package name not found ", e);
}

I got this

String appPath = App.getApp().getApplicationContext().getFilesDir().getAbsolutePath();

from here:

For current Android application package:

public String getDataDir(Context context) throws Exception {
return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).applicationInfo.dataDir;
}

For any package:

public String getAnyDataDir(Context context, String packageName) throws Exception {
return context.getPackageManager().getPackageInfo(packageName, 0).applicationInfo.dataDir;
}

Based on @jared-burrows' solution. For any package, but passing Context as parameter...

public static String getDataDir(Context context) throws Exception {
return context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0)
.applicationInfo.dataDir;
}

There is a simpler way to get the application data directory with min API 4+. From any Context (e.g. Activity, Application):

getApplicationInfo().dataDir

http://developer.android.com/reference/android/content/Context.html#getApplicationInfo()

Just use this in your code

 context.getApplicationInfo().dataDir