Android Test & Permissions mechanism & data storage

Source: Internet
Author: User
Tags throw exception xml parser

Test
    • Black box test-testers do not know the source code
    • White box test-testers know the source code, can write some test cases
According to the granularity of the test
    • Method tests the function test

    • Unit test the Test JUnit framework

    • Integration Testing Integration Test

    • System test

According to the level of violence tested
    • Smoke Testing smoke Test
    • Stress test pressure test
Unit Test Framework (JUNIT)

Android code can only be run in the Dalvik virtual machine in the phone, in the PC's JVM will be error exception, write test cases, usually upload to Android phone or emulator run.

Android Next Unit Test process
  • 1. Write Business logic code

  • 2. Write test case Inheritance Androidtestcase class

  • 3. Write test method public void Testadd () throw exception{}

  • 4. Configure the manifest file

    <?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.itheima.junit "android:versioncode=" 1 "android:versionname=" 1.0 "&GT;&LT;USES-SDK android: minsdkversion= "8" android:targetsdkversion= "/><"!--place instruction set under the root node manifest node instrumentation--><instrum Entation android:name= "Android.test.InstrumentationTestRunner" android:label= "Tests for My App" Android:targetpac Kage= "Com.itheima.junit"/><application android:allowbackup= "true" android:icon= "@drawable/ic_launcher" and Roid:label= "@string/app_name" android:theme= "@style/apptheme" > <!--Use the following application node of the function library--><uses-li Brary android:name= "Android.test.runner"/><activity android:name= "Com.itheima.junit.MainActivity" Android: Label= "@string/app_name" > <intent-filter> <action android:name= "Android.intent.action.MAIN"/&GT;&L T;category android:name= "Android.intent.category.LAUNCHER "/></intent-filter></activity></application></manifest> 
  • 5. Select the test method, right-click Run as-->android JUnit test
Logcatlogcat Panel
    • Filter filters
Log level
    • Verbose reminder Black
    • Debug Debugging Blue
    • Info Info Green
    • Warn warning Orange
    • Error RED
Love the code every day ~ ~
    • Note Configure the appropriate permissions
    • Write the SD card must declare permissions. such as: Write files, delete files
    • Read SD card default is not required permission.
    • If the user has set the read SD card must use permission, the application needs to add permissions
    • Basic concept: Phone internal storage space, a piece of the phone's micro-hard disk, the phone memory ROM power off, the data is still existing cell phone memory: the equivalent of memory on the computer RAM breakpoint data is gone. External storage space: SD card
Save data to SDcard
//获取sdcard剩余空间long usableSpace = Environment.getExternalStorageDirectory().getUsableSpace();// 获取外置sdcard目录File path = Environment.getExternalStorageDirectory();// 获取sdcard的状态(是否挂载)String state = Environment.getExternalStorageState();
Save data to internal storage device (apply private folder, no write permission required) (secure)

Each installed application is assigned a separate user-owned file by default by the operating system and cannot be read/modified by other applications.

    • Apply private folders By default, other apps are inaccessible to keep their data safe
    • Apply private file path:/data/data/Package name/
    • Get Path Method:

      File path = 当前类名.this.getFilesDir();//获取目录是会自动创建files文件夹                 Context.getFilesDir();返回:/data/data/包名/files
    • Get temporary cache directory caches:

      File path = 当前类名.this.getCacheDir();                 Context.getCacheDir();返回:/data/data/包名/cache
(Files & folders) permissions mechanism

MainActivity.this.openFileOutput ("Private.txt", mode_private);

Parameter 1: File

Parameter 2:

  MODE_PRIVATE 私有文件(不可读写)  MODE_WORLD_READABLE 只读文件  MODE_WORLD_WRITEABLE 只写文件  MODE_WORLD_READABLE + MODE_WORLD_WRITEABLE 可读写文件

One app reads files under the private folder of another app:

    * 私有文件:没有权限    * 可读文件:可读    * 可写文件:没有权限    * 可读可写文件:可读

A file that an app writes to another app's private folder:

    * 私有文件:没有权限    * 可读文件:没有权限    * 可写文件:可写    * 可读可写文件:可写
Permission representations: 0 123 456 789
0 表示文件类型:l(小写L)软连接,d 表示文件夹,- 表示文件1 4 7 表示是否可读。r 可读,- 不可读2 5 8 表示是否可写。w 可写,- 不可写3 6 9   表示是否可执行。x 可执行,- 不可执行(一般用于开发人员常用的二进制可执行程序)

Permissions grouping

123:应用权限,用户权限456:所在组其他用户权限789:其他应用,其他用户

Permission value:

    r 权限值对应 4    w 权限值对应 2    - 权限值对应 1

Example of a Change permission command:

chmod 777 file.txt 更改文件权限全局可读可写可执行
XML parsing

Resolution steps:

    Get asset manager Assetmanager AM = this.getassets ();    try {/***************************************///1. Read XML data InputStream is = Am.open ("Weather.xml"); /***************************************///2.        Parsing data (pull parsing, XML parsing under Android)//2.1 Creating an XML parser Xmlpullparser parser = Xml.newpullparser ();        2.2 Initial XML parser, specifying which stream to parse, and what encoding to parse Parser.setinput (IS, "UTF-8");        2.3 Parsing XML data int type = Parser.geteventtype ();                while (type = = Xmlpullparser.start_tag) {String str = parser.nexttext (); }} ...../***************************************/} catch (Exception e) {//TODO auto-g). ...... ....... *.    Enerated Catch block E.printstacktrace ();        }finally{/***************************************///Close Data flow try {is.close ();        } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();    }; }
Android under XML generation (serialization)

XML Saving Data

  ...//Get the Application Private directory temporary cache directory File Path = MainActivity.this.getCacheDir (); FileOutputStream fos = new FileOutputStream (new File (Path, "Info.xml"));/************************************** *//A. Creating an Xml serializer XmlSerializer serializer = Xml.newserializer ();/***************************************///b. Initial The initialization XML serializer sets the output stream, and the encoding method Serializer.setoutput (FOS, "UTF-87");/***************************************///C. Writing XML data/        /document at the beginning of serializer.startdocument ("UTF-8", true);            Serializer.starttag (NULL, "info");            Serializer.starttag (NULL, "QQ");            Serializer.text (QQ);            Serializer.endtag (NULL, "QQ");            Serializer.starttag (NULL, "PW");            Serializer.text (PW);        Serializer.endtag (NULL, "PW");    Serializer.endtag (NULL, "info");    Document End Serializer.enddocument ();    .../***************************************///Off-flow fos.close ();. ......  
Big strokes: Sharedpreferences Package/Read XML data

sharedpreferences Save Data (save location:/data/data/Package name/shared_prefs/xxx.xml)

            // 获取应用私有目录临时缓存目录            File path = MainActivity.this.getCacheDir();            FileOutputStream fos = new FileOutputStream(new File(path,                    "info.xml"));/***************************************/            //初始化SharedPreferences            SharedPreferences sp = this.getSharedPreferences("config", MODE_PRIVATE);/***************************************/            //通过SharedPreferences获取编辑器            Editor ed =sp.edit();/***************************************/            //写入数据            ed.putString("qq",qq);            ed.putString("pw",pw);/***************************************/            //提交数据            ed.commit();/***************************************/            //关闭流            fos.close();            …………

Sharedpreferences reading XML data

        //初始化SharedPreferences        SharedPreferences sp2 = this.getSharedPreferences("config", MODE_PRIVATE);        //读取数据        sp2.getString("qq", "");        ……        sp2.getXXX(key, defValue);

Android Test & Permissions mechanism & data storage

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.