- Related Concepts of testing
- Unit Tests in Android
- Introduction of the Diary Cat
- Login case
- Save the data to the SD card
- Several common directories in Android
- Get the size and free space of your SD card
- The concept of file permissions
- Sharedpreferences use
- How Android is officially recommended to generate XML
- The way Android officially recommends parsing XML
Related Concepts of testing
A good program is not developed, it is tested.
-
Depending on whether the source code is known:
-
black box test: Do not know the source code, just test the function of the program
-
White Box test: Know the source code, according to the source of the test
-
Depending on the granularity of the test: (Size of the module)
-
unit tested:
Unit Test
-
Functional tests: function test
-
Integration test: Integration test: Testing of several modules, server/client-side tuning
-
Systems Testing: System Test:javaee is often used in enterprise-level development
-
Depending on the number of tests: (Violence test)
-
① Smoke test: Smoke test, keep performing operations until the system crashes
-
② Monkey test, the test method is as follows
-
ADB Shell: Enter the emulator directory, Monkey 2000, via Monkey is randomly clicked 2000 times
# monkey –p 包名 次数:只测试某个应用程序com.bzh.beijingwisdom2000
-
③ pressure test: pressure
test
Unit Tests in Android
-
-
To manually add unit tests
-
-
① write a class inheritance
AndroidTestCase
-
-
② adding instruction sets in the manifest file
<instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="程序包名" ></instrumentation>
-
-
③ adding test libraries under the node under the manifest file application
<uses-library android:name="android.test.runner"/>
-
-
Create an Android test project for testing
-
-
Create a project
-
-
Post-creation manifest file
Introduction of the Diary Cat
-
Android Logcat is available in two ways:
-
1, DDMS provided by Logcat view
-
2, LOGC provided via ADB command line
-
DDMS The at view is as follows
-
① If the view is not open, click Window->showview->other->android->logcat to select
-
② On the left side of the view, you can select or add filtering information, and when you run an application, a filter for that package is created by default. The upper-right area of the view is used to select the log level of the Logcat, with verbose, debug, info, warn, error, assert6 options available. :
-
③ The body part of the view is the details of the log, including the error level, time, process ID (PID), thread ID (TID), application package name (application), label (TAG), The log body (text). The
Tid is not equivalent to Thread.CurrentThread () in Java. getId (), but the thread ID in our Linux, which is the same as the PID.
-
logcat log levels and use
-
Android.util.Log commonly used methods have the following 5:
-
log.v () log.d () log.i () LOG.W () and LOG.E ().
-
corresponds to Verbose,debug,info, Warn,error, according to the first letter.
LOG.V debugging color is black, any message will be output, here V for verbose wordy meaning, usually used is LOG.V ("", "");
The output color of the LOG.D is blue, only the meaning of debug debugging is output, but he will output the upper-level information, filtering can be selected by Ddms's Logcat tag.
LOG.I output is green, general informational message information, it will not output LOG.V and LOG.D information, but will display I, W and e information, System.out output information is the info level
LOG.W, which is orange, can be seen as a warning warning, generally requires us to focus on optimizing the Android code, while selecting it will also output LOG.E information.
LOG.E is red, you can think of error errors, here only the red error message, these errors will require us to carefully analyze, view the stack of information.
In the program we can use the log class to output information
Results:
Login case
Get/data/data/com.xxx.xxx/files Path
String savePath = MainActivity.this.getFilesDir().getPath();
Directly using ANDROIDAPI to get the input, output stream of the internal storage path
// 1FileInputStream fis = context.openFileInput("info3.txt");// 2FileOutputStream fos = context.openFileOutput("info3.txt", Context.MODE_PRIVATE);
Save the data to the SD card
Increase permissions
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Get the storage path for the SD card
String savePath = Environment.getExternalStorageDirectory().getPath();
Several common directories in Android
-
-
Default file path for internal applications
-
-
API to use:
context.getFilesDir().getPath()
-
-
Path:/data/data/com.itheima.getsdavail/files
// /data/data/com.itheima.getsdavail/files"内部应用程序的默认文件目录:" + getFilesDir().getPath());
-
-
Default cache path for internal applications
-
-
API to use:
context.getCacheDir().getPath()
-
-
Path:/data/data/com.itheima.getsdavail/cache
// /data/data/com.itheima.getsdavail/cache"内部应用程序的默认缓存目录:" + getCacheDir().getPath());
-
-
Default file directory for SD card application
-
-
API to use:
context.getExternalFilesDir(null).getPath()
-
-
Path:/mnt/sdcard/Android/data/com.itheima.getsdavail/files
// /mnt/sdcard/Android/data/com.itheima.getsdavail/files"SD卡应用程序的默认文件目录:" + getExternalFilesDir(null).getPath());
-
-
Default cache directory for SD card applications
-
-
API to use:
context.getExternalCacheDir().getPath()
-
-
Path:/mnt/sdcard/Android/data/com.itheima.getsdavail/cache
// /mnt/sdcard/Android/data/com.itheima.getsdavail/cache"SD卡应用程序的默认缓存目录:" + getExternalCacheDir().getPath());
-
-
SD Card Root Path
-
-
API to use:
Environment.getExternalStorageDirectory().getPath()
-
-
Path:/mnt/sdcard
// /mnt/sdcard"SD卡根路径:" + Environment.getExternalStorageDirectory().getPath());
Get the size and free space of your SD card
How to obtain the Andoird2.3 version above
// 获取到SD卡目录File file = Environment.getExternalStorageDirectory();TextView tvTotal = (TextView) findViewById(R.id.tv_total);// 获取SK卡目录的总共空间大小,返回值为long型 long totalSpace = file.getTotalSpace();// 使用AndroidAPI进行数据的格式化String total = Formatter.formatFileSize(this, totalSpace);tvTotal.setText(total);TextView tvAvail = (TextView) findViewById(R.id.tv_avail);// 获取SK卡目录的可用空间大小,返回值为long型 long usableSpace = file.getUsableSpace();// 使用AndroidAPI进行数据的格式化String avail = Formatter.formatFileSize(this, usableSpace);tvAvail.setText(avail);
How to obtain compatible versions of Andoird2.2
/*** Get External free space on your phone * * @return */ Public Static Long getavailableexternalmemorysize() {//Determine if the SD card is available if(Android.os.Environment.getExternalStorageState (). Equals (Android.os.Environment.MEDIA_MOUNTED)) {//Get SD card directoryFile path = Environment.getexternalstoragedirectory (); StatFs stat =NewStatFs (Path.getpath ());LongBlockSize = Stat.getblocksize ();LongAvailableblocks = Stat.getavailableblocks ();returnAvailableblocks * BLOCKSIZE; }Else{Throw NewRuntimeException ("Don ' t have sdcard."); }}
/** * Get phone external space size * * @return */ Public Static Long gettotalexternalmemorysize() {if(Android.os.Environment.getExternalStorageState (). Equals (Android.os.Environment.MEDIA_MOUNTED)) {File path = Environment.getexternalstoragedirectory ();//Get an external storage directory that is //SDcardStatFs stat =NewStatFs (Path.getpath ());LongBlockSize = Stat.getblocksize ();LongTotalblocks = Stat.getblockcount ();returnTotalblocks * BLOCKSIZE; }Else{Throw NewRuntimeException ("Don ' t have sdcard."); }}
The concept of file permissions
Below is a typical Linux under Directory file permission graph
-
Linux directory file permissions are made up of 10 bits
-
1th bit: For
d
directory,
-
-
2-4 bits for file (current user):
r
Read permission,
w
write permission,
x
executable permission
-
5- 7-bit (current user group):
r
for Read permission,
w
write permission,
x
for executable permission
-
8-10 for (other user):
r
Read permission,
w
write permission, for executable permissions
The schematic is as follows
-
-
Create a private, append, readable, writable file
-
-
It is mainly
context.openFileOutput()
set by the second parameter of the method
-
-
① Private
-
-
The code is as follows
publicvoidPrivatethrows Exception { FileOutputStream fos = context.openFileOutput("Private.txt", MODE_PRIVATE); fos.write("Private".getBytes()); fos.close();}
-
-
, you can see that private permissions in other user groups are
- - -
-
-
② can be added
-
-
The code is as follows
FileOutputStream fos = openFileOutput("Append.txt", MODE_APPEND);fos.write("Append".getBytes());fos.close();
-
-
, you can see that the permissions that can be appended to the other user groups are
- - -
, consistent with the private, can be appended and private, and cannot be reflected in the file permissions.
-
-
③ readable
-
-
The code is as follows
FileOutputStream fos = openFileOutput("Read.txt", MODE_WORLD_READABLE);fos.write("Read".getBytes());fos.close();
-
-
, you can see that the permissions in the other user groups are readable
r - -
-
-
④ can write
-
-
The code is as follows
FileOutputStream fos = openFileOutput("Write.txt", MODE_WORLD_WRITEABLE);fos.write("Write".getBytes());fos.close();
-
-
, you can see that the writable permissions in the other user groups are
- r -
Sharedpreferences use
-
-
Use steps
-
-
① getting to Sharedpreferences instances through the context API
SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);
-
-
② storing data via Sharedpreferences.editor
Editor editor = sp.edit();editor.putString("username", username);editor.putString("password", password);
-
-
③ Submitting data via editor
editor.commit();
-
-
④ using the Sharedpreferences instance object to get the data for the key
String username = sp.getString("username""");String password = sp.getString("password""");
files created with sharedpreferences, such as
You can see that you have created a folder under the internal application directory with the SP storage file, shared_prefs
and created an XML file under the folder with the specified permissions.
How Android is officially recommended to generate XML
-
Use steps
-
① Generating an XML serializer
-
② setting Serialization parameters
-
③ Start Document
-
④ Generating the root node
-
⑤ Loop generation of child node elements
The specific code is as follows, written with detailed comments:
//1. Generate an XML serializerXmlSerializer XmlSerializer = Xml.newserializer ();//2. Set serialization parameters, parameters 1:xml file output stream; parameter 2:xml file encoding formatFileOutputStream fos = Openfileoutput ("Users.xml", context.mode_private); Xmlserializer.setoutput (FOS,"UTF-8");//3. Start the document, parameter 1:xml the encoding content of the first line in the document; Parameter 2: Whether it is independent, not dependent on constraintsXmlserializer.startdocument ("UTF-8",true);//4. Build the users root nodeXmlserializer.starttag (NULL,"Users");//5. Loop generation of user child node elements for(User user:userlist) {Xmlserializer.starttag (NULL,"User");//6. Set label PropertiesXmlserializer.attribute (NULL,"id", User.getid ());//7. Set the user propertyXmlserializer.starttag (NULL,"Name"); Xmlserializer.text (User.getname ()); Xmlserializer.endtag (NULL,"Name");//8. Setting the Password propertyXmlserializer.starttag (NULL,"Password"); Xmlserializer.text (User.getpassword ()); Xmlserializer.endtag (NULL,"Password"); Xmlserializer.endtag (NULL,"User");} Xmlserializer.endtag (NULL,"Users"); Xmlserializer.enddocument ();//When the document finishes, the output stream is flushed and all data is output to the file.
The serialized XML file is as follows:
The way Android officially recommends parsing XML
-
Steps to use:
-
① get XML Parser
-
② get XML parser Parameters
-
③ Gets the event, Xmlpull is an event-based, line-by-line resolution similar to sax
-
④ Loop Processing Events
-
⑤ Processing root nodes, child nodes, child node elements, etc.
The code is as follows:
List<user> userlist =NULL; User User =NULL;//1. Get the XML ParserXmlpullparser parser = Xml.newpullparser ();//2. Set ParserInputStream in = GetClass (). getClassLoader (). getResourceAsStream ("Users.xml");///Parameter 1: Parsed file stream, Parameter 2: Parsing XML encoding FormatParser.setinput (In,"UTF-8");//3. Get events, Xmlpull is an event-based, one-line parsing of sax-likeintEventType = Parser.geteventtype ();//4. Cyclic Processing of events while(EventType! = xmlpullparser.end_document) {Switch(EventType) { CaseXmlpullparser.start_tag:if("Users". Equals (Parser.getname ())) {///root node, initialize the collectionUserList =NewArraylist<user> (); }Else if("User". Equals (Parser.getname ())) {///child element, initialize the objectuser =NewUser ();//Get properties in child elementsString id = parser.getattributevalue (0); User.setid (ID); }Else if("Name". Equals (Parser.getname ())) {String name = Parser.nexttext (); User.setname (name); }Else if("Password". Equals (Parser.getname ())) {String password = parser.nexttext (); User.setpassword (password); } Break; CaseXmlpullparser.end_tag:if("User". Equals (Parser.getname ())) {//Add elements to the collectionUserlist.add (user); } Break;default: Break; } EventType = Parser.next ();} System.out.println (Userlist.tostring ());
Android Basic notes (ii)