在没有上下文的情况下获取应用程序的存储路径

Get app's storage path without context

我有一个后台服务,当它收到一些内容时会激活 BroadcastReceiver class。我想将其保存到外部目录中的应用程序路径,这是通过调用 Context.getExternalFilesDir() (/sdcard/Android/data/com.example.app/) 返回的。但是,由于这是在后台发生的,所以我没有上下文,所以我无法获得该路径。我绝对不希望对路径进行硬编码,并希望在卸载应用程序时删除数据。还有其他方法可以获得完整路径吗?

在 Android 6 之前和强制范围存储之前,以下内容适用于 Android 5。

String path = Environment.getExternalStorageDirectory().getAbsolutePath();

此答案不再适用于 Android 11 和 2020。

服务本身是一个上下文http://developer.android.com/reference/android/app/Service.html您可以使用。

this.getExternalFilesDir()

在服务中。

如果您知道要读取的文件的地址,则不需要上下文。

String getKey(String filename) throws IOException {
    // Read from file
    String myStringFromFile= "";
    BufferedReader br = new BufferedReader(new FileReader(filename));
    String line;
    while ((line = br.readLine()) != null) {
        myStringFromFile+= line;
    }
    br.close();
    return myStringFromFile;
}

其中文件名是路径。

String privatePem = "/sdcard/someFolder/someFile.txt";

我想你可以在静态class中定义一个关于外部文件夹路径的静态字段,然后在你的应用程序中初始化它class。

例如:

public class BaseApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        IOUtils.cacheFolder = IOUtils.getCacheDir(this);
    }
}

public class IOUtils {
    public static File cacheFolder;
    /**
    * Return the folder for cache files.
    */
   public static File getCacheDir(Context context) {
       File cache = context.getExternalCacheDir();
       if (cache == null)
           cache = context.getCacheDir();
       return cache;
   }
}

有点难看但有效。您可以在没有上下文的情况下在后台线程中使用 IOUtils.cacheFolder。在静态字段中缓存文件引用,不会导致任何内存问题。