Analyze the Android resource files and their reading methods _android

Source: Internet
Author: User
Sam has two ways to process resource files in Android development. One is to put all the resource files and JNI programs in a separate resource bundle. When used to them, read by using the file method. or read directly using C + + layer code. Secondly, the resource file is added to the APK. Use a variety of different methods to get their content.
method One: Suitable for porting larger C + + programs, because of the large number of C + + code, is unlikely to be modified to Java code. So it's a good idea to store them in a certain way with the resource files and let them call themselves the system. However, this causes the release of the software to be published as a apk+ resource bundle.
Method Two: Then the comparison of the appropriate code is not very large, and the number of resources is not particularly much. At this point, the user installs APK, no longer laborious copy resource bundle. Easy to publish.
This main introduction is the second way, the resources to join the APK way.
0.Android Resource Introduction:
When you develop an Android application, you typically use the following resources:
Res/drawable: Usually used for storing picture resources. such as logo and so on.
Res/layout: Layout file.
Res/values: Store string, such as program name.
But Android can actually use other types of resources. Today we introduce 3 types as follows:
Res/xml: Store XML files, similar to previous resources, the resource files stored in them are compiled into binary data and stored in the installation package. Read the XML file through the R class.
Res/raw: Storage file. The files in this directory are different from the previous resources and they are not compiled into binary files. Instead, they are stored in file form. Read through the R class.
Assets: You can create subdirectories and store different files here. is not compiled into binary, but is stored as a directory/file. Read by file name.
1. Read all kinds of files:
1.1:res/raw:
Android.app.Activity has an indirect parent class: Android.content.Context
It has a method that is very much related to the application resource bundle:
public abstract getresources ()
It returns an instance of the resource bundle for this application. This instance is the Android.content.res.Resources class object.
The SAM first adds the raw directory. The cursor selects Res. Menu: File->new->folder. Enter directory name: Raw.
and copy a WAV---tennis_room.wav file into this directory and refresh the project.
Now look at the R class in Gen.
Discovery has been added into:
Copy Code code as follows:

public static final class Raw {
public static final int tennis_room=0x7f040000;
}

Example:
Copy Code code as follows:

int byteread = 0;
byte[] buf = new byte[4096];
FileInputStream instream = null;

res = getresources ();
Assetfiledescriptor fd = RES.OPENRAWRESOURCEFD (r.raw.tennis_room);


try {
Instream = Fd.createinputstream ();
catch (IOException e) {
TODO auto-generated Catch block
LOG.E ("3DiJoy", "Createinputstream error");
E.printstacktrace ();
}

try {
while ((Byteread = Instream.read (BUF))!=-1)
{
Do something
}
catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}

1.2:res/xml:
Similar to raw, but related to XML. We'll talk about it in the next section.
GETXML (int id)
1.3:assets:
Similarly, Android.app.Activity's indirect parent class: Android.content.Context
There is a way: Public abstract Assetmanager getassets ()
Returns the Assetmanager instance of the application package.
Use InputStream open (String fileName);
Returns a InputStream.
You can read the file.
Note that the file is rooted in assets.
Copy Code code as follows:

Assetmanager am = getassets ();

try {
Am.open ("A.txt");
catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}

Assets file has the maximum limit:
uncompress_data_max:1048567 bytes
Assets File Directory Analysis:
After using Getassets () to get the Assetsmanager instance. You can open the file and list all the files and directories. But what is its path and directory? We do the following tests:
First: Let's do a program to list all the files and directories in a given directory:
Copy Code code as follows:

public void Listassetsfile (String assetspath)
{
Assetmanager am = getassets ();
try {
string[] Fileordirname = am.list (Assetspath);
LOG.E ("3DiJoy", String.Format ("in Assets Path: [%s]. There is:[%d] "file or Dir", Assetspath, Fileordirname.length));
for (int i = 0; i < fileordirname.length; i++)
{
LOG.E ("3DiJoy", String.Format ("File Or dir:[%s]", fileordirname[i));
}
catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}

Return
}

Attention point 1:
How to determine if a node in assets is a file or directory:
The way Sam sees some friends on the web is to determine if there is a "." in the filename. That this approach was not particularly effective, so another attempt was made.
Copy Code code as follows:

True:dir. False:file
public boolean isassetsdirs (String fileordirname)
{
Assetmanager am = getassets ();

try {
Am.open (Fileordirname);
return false;
}
catch (FileNotFoundException e)
{
return true;
}
catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
return true;
}

Return! (Filename.startswith (".") | | (Filename.lastindexof (".")!=-1));
}

When you use Am.open (), if you specify a directory, a FileNotFoundException exception is thrown. Sam uses this to determine whether it's a directory.
Attention Point 2:
How to copy a directory under assets to a local:
That is to do the same:
Copy Code code as follows:

#cp dir_a/*-rf/data/data/.../
public boolean Copyassetspath (String Assetspath, String objectpath)
{
File Objpath = new file (ObjectPath);
if (! Objpath.exists () | | ! Objpath.isdirectory ())
{
LOG.E ("3DiJoy", "Object Path not found" or not Dir: "+ ObjectPath");
return false;
}



Assetmanager am = getassets ();

try {
string[] Fileordirname = am.list (Assetspath);
LOG.E ("3DiJoy", String.Format ("in Assets Path: [%s]. There is:[%d] "file or Dir", Assetspath, Fileordirname.length));
for (int i = 0; i < fileordirname.length; i++)
{
If it is a DIR
if (Isassetsdirs (assetspath+ "/" + Fileordirname[i])
{
File N_dir = new file (ObjectPath + "/" + fileordirname[i]);
if (! N_dir.exists ())
{
LOG.E ("3DiJoy", String.Format ("would Create dir:[%s]", ObjectPath + "/" + fileordirname[i));
N_dir.mkdir ();
Copyassetspath (Assetspath + "/" +fileordirname[i], ObjectPath + "/" + fileordirname[i]);
}
}
else//If this is file. Then Copy It
{
LOG.E ("3DiJoy", String.Format ("would Create file:[%s]", ObjectPath + "/" + fileordirname[i));
Copyassets (Assetspath + "/" + fileordirname[i], ObjectPath + "/" + fileordirname[i]);
}
LOG.E ("3DiJoy", String.Format ("File Or dir:[%s]", fileordirname[i));
}
catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}


return true;
}

The program is simple:
Use list to list all files and directories.
If directory: Creates a directory of the same name in the target area.
If it is a file, copy it.
Attention point 3:
How to access and copy a file over 1M:
The above program, if there are more than 1M files, will report an exception.
The exception that throws the Java.io.IOException is as follows
Debug/asset (1123): Data exceeds Uncompress_data_max (xxxxxxxx vs 1048576);
Note, however, that the following files are not subject to the 1M size limit
Copy Code code as follows:

JPG ",". jpeg ",". png ",". gif ",". wav ",". Mp2 ",". mp3 ",". Ogg ",". AAC ",". mpg ",". Mpeg ",". Mid ",". Midi ",". SMF ",". Jet ",". RT TTL ",". Imy ",". Xmf ",". mp4 ",". m4a ",". m4v ",". 3gp ",". 3GPP ",". 3g2 ",". 3gpp2 ",". Amr ",". AWB ",". wma ",". wmv "

You can add the following file names to files that are larger than the size.
Test 1:
Test root directory Location:
Listassetsfile ("/");
Get the information:
The more directory is actually the root directory after APK decompression:
The content includes:
Androidmanifest.xm.
Assets
Meta-info
Lib
Res
Classes.dex
Resources.arsc
Test 2:
Test relative path Location:
Listassetsfile ("");
The content listed is the contents of the assets directory. But somehow, three things were added:
Image, sound, WebKit.
Test 3: Test the current path location:
Listassetsfile ("./");
In theory, the./directory should be the same as the current directory, somehow, but no files are available here. Don't quite understand.
Because of the test 3, the Android assets directory is suspected of being the same as our Linux concept, so test again:
Test 4:
See if the absolute path is available:
Listassetsfile ("/assets");
Hehe, it was confirmed that it could not get any of the documents.
Test 4:
See if you can access files other than assets using an absolute path:
Listassetsfile ("/lib");
Sure enough to return 0 files. Oh.
Conclusion:
To access the assets file, you can only use a relative path, and the front cannot be added.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.