android.Content包定义了一些类,这些类主要用于在设备上访问或是发布数据,主要有三个包构成。
- Content 共享 (android.content) 主要用于在Application的各个部件自己共享一些数据,主要的列有Content Provider,ContentResolver用于管理和发布数据。 Intent,IntentFilter 用于Application不同组件之间发送消息。
- Package 管理 (android.content.pm) 用于访问Android Package (.apk)定义的Activities, Permissions, Services,Signatures和Providers,主要的类为PackageManager。
- 资源管理 (android.content.res) 用于访问应用中定义的资源,如Strings,Drawables, Media,Device Configuration等等,主要的类为Resources。
一般来说Application把资源放在res目录下面,有些情况下Application需要使用一些自定义的文件,一种方法是将它们放在res/raw 目录下面,另外一种方法是将它们放在assets目录下,和res 目录不同的是,Android SDK不会为目录assets 下的文件生成资源ID,而是通过AssetManager 以文件的文件名来访问,放在/assets的目录机构是什么样的,使用AssetManager 访问时也是采用同样的文件结构。和res相比,assets 提供了更低一层次的资源访问。
本例使用AssetManager来访问assets 目录下的read_asset.txt 。
InputStream is = getAssets().open("read_asset.txt"); // We guarantee that the available method returns the total // size of the asset... of course, this does mean that a single // asset can't be more than 2 gigs. int size = is.available(); // Read the entire asset into a local byte buffer. byte[] buffer = new byte[size]; is.read(buffer); is.close(); // Convert the buffer into a string. String text = new String(buffer); // Finally stick the string into the text view. TextView tv = (TextView)findViewById(R.id.text); tv.setText(text);在Activity 中可以通过getAssets() 来取得AssetManager对象,和文件操作类似AssetManager可以通过字节流的方式来读取文件。