Android access to resources outside of activity

后端 未结 2 1984
萌比男神i
萌比男神i 2021-01-13 21:09

I would like to know - are there ways to access android resources and/or assets files (or files from any other folder) outside of an Activity (without passing context

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-13 21:28

    If the folders are included in the Project Build Path, you can use ClassLoader access files under them outside the android.content.Context, for instance, from a POJO (in case if you don't want to pass a reference of android.content.Context):

    String file = "res/raw/test.txt";
    InputStream in = this.getClass().getClassLoader().getResourceAsStream(file);
    
    • The res folder is included into Project Build Path by default by all Android SDK version so far.
    • The assets folder was included into Project Build Path by default before Android SDK r14.

    To add folders into Project Build Path, right click your project -- Build Path -- Configure Build Path, add your folder (for example, assets if using later SDK version) as a Source folder in build path.

    Check out the similar question I answered before at here.

提交回复
热议问题