Android configuration file (2) and android configuration file

Source: Internet
Author: User

Android configuration file (2) and android configuration file

We know that each module of the Android system provides very powerful functions (such as phones, power supplies, and settings). By using these functions, applications can be more powerful and flexible. However, using these functions is not unconditional, but requires some permissions. Next, we will begin to explain another important point-application permission statement, which mainly includes the application permission statement, custom application access permission, and SDK version limitation.

 

1. <uses-permission> -- Application permission Application

 

Permission Description
Android. permission. ACCESS_NETWORK_STATE Allow applications to access network status
Android. permission. ACCESS_WIFI_STATE Allow applications to access WI-FI status information
Com. android. voicemail. permission. ADD_VOICEMALL Allow applications to add a voice mail to the System
Android. permission. BATTERY_STATS Allow applications to update cell phone battery statistics
Android. permission. BIND_APPWIDGET Allow applications to notify AppWidget service which application can access AppWidget data
Launcher is an instance that uses this permission.
Android. permission. BLUETOOTH Allow applications to connect to a paired bluetooth device
Android. permission. javasth_admin Allow applications to actively discover and pair Bluetooth devices
Android. permission. BROADCAST_PACKAGE_REMOVED Allow medical programs to send notifications that application packages have been uninstalled
Android. permission. BROADCAST_SMS Allow applications to broadcast SMS receipt notifications
Android. permission. BROADCAST_STICKY Allow applications to broadcast Sticky Intent.
Some broadcast data is placed in the system after it is broadcast, so that applications can quickly access their data without waiting for the next broadcast to arrive.
Android. permission. CALL_PHONE Allow applications to initiate a call
Android. permission. CAMERA Request to access the camera Device
Android. permission. CHANGE_CONFIGURATION Allows the application to modify the current configuration, such as the language type and screen direction. For example, the setting module uses this permission.
Android. permission. CHANGE_NEWWORK_STATE Allow applications to change connection status
Android. permission. CHANGE_WIFI_STATE Allow applications to change the WI-FI connection status
Android. permission. DEVICE_POWER Allow applications to access underlying device power management
Android. permission. EXPAND_STATUS_BAR Allow the application to expand or collapse the status bar
Android. permission. INSTALL_LOCATION_PROVIDER Allow the application to install a data provider to the local manager.
Android. permission. INSTALL_PACKAGES Allow the application to install another application
Android. permission. INTERNET Allow applications to open the network.
If you want to develop a network-related application, you should first consider whether this permission is required.
Android. permission. KILL_BACKGROUND_PROCESSES Allow applications to call the killBackgroundProcesses () method
Android. permission. MODIFY_PHONE_STATE Modify the call status, but not the call status.
Android. permission. MOUNT_FORMAT_FILESYSTEMS Allow applications to format removable external storage devices
Android. permission. MOUNT_UNMOUNT_FILESYSTEMS Allow applications to mount or Detach external storage devices
Android. permission. NFC Allow applications to perform NFC input/output operations
Android. permission. READ_CALENDAR Allow applications to read calendar data
Android. permission. READ_CONTACTS Allow the application to read contact data
Android. permission. READ_PHONE_STATE Allow applications to access the phone status
Android. permission. READ_SMS Allow applications to access SMS messages
Android. permission. RECEIVE_BOOT_COMPLETED Allow applications to receive android. intent. action. BOOT_COMPLETED broadcast after system completion
Android. permission. RECEIVE_MMS Allow applications to monitor MMS
Android. permission. RECEIVE_SMS Allow applications to monitor SMS
Android. permission. RECEIVE_WAP_PUSH Allow applications to monitor push information of WAP
Android. permission. SEND_SMS Allow applications to actively send messages
Android. permission. SET_TIME Allow applications to set system time
Android. permission. SET_TIME_ZONE Allow applications to set the system time zone
Android. permission. SET_WALLPAPER Allow applications to set desktop wallpapers
Android. permission. STATUS_BAR Allow the application to operate (Open, close, disable) the status bar and its icon
Android. permission. VIBRATE Allow applications to access vibrating Devices
Android. permission. WAKE_LOCK Allow applications to use the screen lock function of the Power Manager
Android. permission. WRITE_CALENDAR Allows users to write calendar data. If we only apply for this permission, we only have the write permission for the calendar data and do not have the read permission.
Android. permission. WRITE_CONTACTS Allow users to write contact data. If we only apply for this permission, we only have the write permission and no read permission for the contact data.
Android. permission. WRITE_EXTERNAL_STORAGE Allow applications to write data to external storage devices
Android. permission. WRITE_SETTINGS Allow applications to read and write system settings
Android. permission. WRITE_SMS Allow applications to write text messages

 

 

Applications may need certain permissions shown in the preceding table in different scenarios. For example, if you want to use an SD card, you need to apply for permissions related to the SD card. The following is an example to explain this problem.

 

In this example, we will change the helloworldapplication and create a text file named "“abc.txt" under the root directory of sdcard. To access the external storage device, you need to apply for the permission of android. permission. WRITE_EXTERNAL_STORAGE. Otherwise, the code will fail. The procedure is as follows.

 

① Add the corresponding permissions to the AndroidManifest. xml file of the HelloWorld application, as shown in the following code:

 

<Uses-permission android: name = "android. permission. WRITE_EXTERNAL_STORAGE"/>

 

② Add some code for creating a file in the original code, as shown below:

 

 

public class MainActivity extends FragmentActivity {
    private static final String SDCARD= Environment.getExternalStorageDirectory()+File.separator;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(savedInstanceState==null){
            getSupportFragmentManager().beginTransaction().add(android.R.id.content,new FileFragment()).commit();
        }
    }
    public static class FileFragment extends Fragment {
        public FileFragment(){}
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view=inflater.inflate(R.layout.file_fragment,container,false);
            Button mybut= (Button) view.findViewById(R.id.mybut);
            mybut.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    File sdcardFile=new File(SDCARD+"abc.txt");
                    try {
                        sdcardFile.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            return view;
        }
    }
}

 

 

 

When the SDK starts the program, we will find that the abc.txt file has been created in the directory linked by sdcard, as shown in.

 


 

Finally, we will conduct an experiment to import AndroidManifest. the <uses-permission> node in the xml file is deleted. No created file is found in the same directory. After this operation, we can find some exception information in the log, as shown in.

 


 

 

From the log, we can find that the program throws a java. io. IOException and prompts "Permission denied", where it occurs exactly where the file is created. Therefore, we can draw a conclusion that when trying to read and write external storage devices, we must first apply for android. permission. WRITE_EXTERNAL_STORAGE permission. Otherwise, the program throws a warning exception and related operations cannot be performed.

 

Android provides a variety of software and hardware functional modules, which can make applications more powerful and more convenient in the development process. However, before using it, you must apply for necessary permissions for the application. This is very important, otherwise the application will encounter inexplicable errors.

 

As you can see in the previous instance, if you do not have the corresponding permissions, you cannot create a file, and the program does not display an exception prompt, in this case, it may take a lot of time to find the root cause of the problem.

 

 

Therefore, I suggest you carefully analyze the requirements before development and analyze the functions of the application, and whether these functions require permissions for access.

 

 

2. <permission> node -- Custom Application Access Permissions

 

We learned how to use permissions. In fact, in addition to permissions, an application can also define its own permissions to restrict access to special components or functions of the application or other applications. Here, we will learn the role of the <permission> node-how to declare its own permissions.

 

Manually add a <permission> node to the AndroidManifest. xml file, which can only be included in the <manifest> node. The syntax is as follows:

 

<Permission android: description = "string resource"

Android: icon = "drawable resource"

Android: logo = "drawable resource"

Android: label = "string resource"

Android: name = "string"

Android: permissionGroup = "string"

Android: protectionLevel = ["normal" | "dangerous" | "signature" | "signatureOrSystem"]/>

 

In the preceding code, you must specify the following three attributes.

 

 

① Android: name: the name of the declared permission. This name must be unique. Therefore, you should use a Java-style name, such as com. test. permission. TEST.

 

② Android: permissionGroup: Permission group to which the permission belongs. The permission group can be pre-compiled by Android or custom. The following table lists the permission groups pre-compiled by the Android system.

 

Permission group name Description
Android. permission-group.ACCOUNTS Used to directly access an account managed by the account manager
Android. permission-group.COST_MONEY This permission allows users to spend money without having to directly participate.
Android. permission-group.DEVELOPMENT_TOOLS Permission groups related to development features
Android. permission-group.HARDWARE_CONTROLS Provides the permission to directly access the hardware of the device.
Android. permission-group.LOCATION Used to allow users to access the current user location
Android. permission-group.MESSAGES This permission allows an application to send information in the name of a user or intercept information received by the user.
Android. permission-group.NETWORK Applies to access permissions for Network Services
Android. permission-group.PERSONAL_INFO It is applicable to providing permissions to access users' private data, such as contacts, calendar events, and email information.
Android. permission-group.PHONE_CALLS This permission applies to associated access and modify the phone status, such as intercepting power-off requests, reading and modifying the phone status.
Android. permission-group.STORAGE Permission groups related to SD card access
Android. permission-group.SYSTEM_TOOLS Permission groups related to system APIs

 

 

③ Android: protectionLevel: Describes the potential risks hidden in permissions. The value of this attribute can be a string in the following table.

 

 

Value Meaning
Normal Default value. Low-risk permissions, which allow requested applications to access isolated application-level functions and bring minimum risks to other applications, systems, or users. During installation, the system automatically grants this type of permission to the requested application, without the need to explicitly declare it.
Dangerous High-risk permission, which allows the requesting application to access the user's private data or control devices that negatively affect the user. Because of the potential risks of such permissions, the system may not be automatically assigned to the requested application. For example, any dangerous Permission requested by the application may be displayed to the user and required to be confirmed before processing. For example, the following permissions belong to these permissions.
<Permission android: name = "android. permission. RECEIVE_SMS"
Android: permissionGroup = "android. permission-group.MESSAGES"
Android: protectionLevel = "dangerous"/>
If the application uses this permission, other applications may be unable to receive SMS notifications. In this case, we think this permission is dangerous.
Signature Signature level. The permission is granted only when the requested application uses the same signature as the Declaration permission. If the authentication matches, the system does not notify the user or automatically authorizes the user without explicit approval.
SignatureOrSystem Signature or system level. The system only grants it to applications in the Android system image file (*. imgfile), or applications that use the same authentication signature as those in the system image. In general, avoid using this option whenever possible, because the signature protection level should meet most of the needs and projects, regardless of where the application is installed. The signatureOrSystem Permission applies to a specific special environment. In such an environment, multiple vendors have built applications into the system image and need to clearly share specific features.

 

 

In the <permission> node, in addition to the three attributes described above, some other attributes exist for ease of reading. We will not detail them here.

 

In the applications provided by the Android system, some permissions are defined, such as Launcher. The following code snippet uses the AndroidManifest. xml snippet of Launcher to demonstrate how to manually declare your permissions:

 

<Permission

Android: name = "com. android. launcher. permission. INSTALL_SHORT-CUT"

Android: permissionGroup = "android. permission-group.SYSTEM_TOOLS"

Android: protectionLevel = "normal"

Android: label = "@ string/permlab_install_shortcut"

Android: description = "@ string/perdesc_install_shortcut"/>

 

The permission declaration function is frequently used. Therefore, when developing an application, you need to consider whether it is necessary to declare your own permissions.

 

 

3. <uses-sdk> node -- SDK version limit

 

As we all know, the software has certain requirements for the platform version. If the platform version meets the software operation requirements, the stability of the software can be ensured. For example, we all know that NFC functions cannot be run in Android 1.5. If you are developing applications with similar functions, you must have requirements on your platform, the <uses-sdk> node meets this requirement.

 

<Uses-sdk> A node uses an integer value to express the compatibility between an application and one or more Android platform versions. It is worth noting that these integer values represent the API level. The API level given by the application is compared with the API level of a given Android system. Of course, for different Android devices, this may be different. Note that this node is used to specify the API level, rather than the SDK version or Android platform.

 

The code for using this node is as follows:

 

<Uses-sdk android: minSdkVersion = "integer"

Android: targetSdkVersion = "integer"

Android: maxSdkVersion = "integer"/>

 

① Android: minSdkVersion: used to specify the minimum API level required to run the application. If the system's API level is smaller than the value specified by this attribute, the Android system will prevent users from installing this application. In most cases, this attribute should be specified. If this attribute is not specified, the system considers this attribute as "1 ".

 

② Android: targetSdkVersion: used to specify the target API level of the application.

 

③ Android: maxSdkVersion: specifies the maximum API level.

 

4. <instrumentation> node-application Monitor

 

<Instrumentation> A node is used to monitor the interaction between an application and the system. It is instantiated before the application component is instantiated. This node is used for unit testing in most cases. The syntax structure is as follows:

 

<Instrumentation android: functionalTest = ["true" | "false"]

Android: handleProfiling = ["true" | "false"]

Android: icon = "drawable resource"

Android: label = "string resource"

Android: name = "string"

Android: targetPackage = "string">

 

These attributes are described in detail below:

 

① Android: functionalTest: identifies whether the Instrumentation class is run as a function test. Its default value is false.

 

② Android: handleProfiling: identifies whether the Instrumentation object enables or disables performance analysis. Its default value is false.

 

③ Android: icon: This attribute represents the icon of the Instrumentation class.

 

④ Android: label: the title of the Instrumentation class.

 

⑤ Android: name: the name of the sub-class of Instrumentation. It is a Java-style name of the class, for example, com. example. liyuanjinglyj. myInstrumentation.

 

⑥ Android: targetPackage: This attribute is the name of the target application to be monitored. This name comes from the package attribute value of the <manifest> node in the target application AndroidManifest. xml.

 

Of course, you need to create a test project in eclipse and configure this node, but you do not need to do so in android studio. Considering that Google no longer supports eclipse by the end of 2015, therefore, I only want to explain the unit test of android studio, and explained this node because eclipse still has a large number of developers, So I explained the node details.

 

The following is an example of how to perform a unit test:

 

① When creating a project, we still use HelloWorld as an experiment. You will find a test package in the project directory:

 


 

② Right-click the package and select the NEW-CLASS Menu item to create a NEW MyFirstTest inherited from ActivityInstrumentationTestCase2 <T>, as shown in:

 

 

package com.example.liyuanjing.helloworld;
import android.test.ActivityInstrumentationTestCase2;
/**
 * Created by liyuanjing on 2015/7/14.
 */
public class MyFirstTest extends ActivityInstrumentationTestCase2<MainActivity>{

    public MyFirstTest(){
        super(MainActivity.class);
    }
}

 

 

In this Code, the <T> In ActivityInstrumentationTestCase2 <T> is replaced with the class we are testing, because we want to test MainActivity.

 

③ Test content: Enter some characters in the edit box. When you click the button, the text box equals the string entered in the edit box. The MainActivity code is as follows:

 

 

public class MainActivity extends FragmentActivity {
    private static final String SDCARD= Environment.getExternalStorageDirectory()+File.separator;
    private FileFragment  fileFragment=new FileFragment();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(savedInstanceState==null){
            getSupportFragmentManager().beginTransaction().add(android.R.id.content,fileFragment).commit();
        }
    }
    public static class FileFragment extends Fragment {
        private View mRootView;
        public FileFragment(){}
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view=inflater.inflate(R.layout.file_fragment,container,false);
            final EditText myEdit=(EditText)view.findViewById(R.id.myEdit);
            final TextView content=(TextView)view.findViewById(R.id.content);
            Button myBut=(Button)view.findViewById(R.id.myBut);
            myBut.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    content.setText(myEdit.getText().toString());
                }
            });
            this.mRootView=view;
            return view;
        }
        public View getRootView(){
            return this.mRootView;
        }
    }
    public FileFragment getFragment(){
        return fileFragment;
    }
}

 

 

The code for the test class is as follows:

 

 

public class MyFirstTest extends ActivityInstrumentationTestCase2<MainActivity>{
    private TextView content;
    private EditText myEdit;
    private Button myBut;
    private MainActivity mainActivity;
    public MyFirstTest(){
        super(MainActivity.class);
    }
    @Override
    protected void setUp() throws Exception {
        super.setUp();
        this.mainActivity=(MainActivity)getActivity();
        this.content=(TextView)this.mainActivity.getFragment().getRootView().findViewById(R.id.content);
        this.myEdit=(EditText)this.mainActivity.getFragment().getRootView().findViewById(R.id.myEdit);
        this.myBut=(Button)this.mainActivity.getFragment().getRootView().findViewById(R.id.mybut);
    }
    public void testButtonClick(){
        getInstrumentation().sendCharacterSync(KeyEvent.KEYCODE_H);
        getInstrumentation().sendCharacterSync(KeyEvent.KEYCODE_E);
        getInstrumentation().sendCharacterSync(KeyEvent.KEYCODE_L);
        getInstrumentation().sendCharacterSync(KeyEvent.KEYCODE_L);
        getInstrumentation().sendCharacterSync(KeyEvent.KEYCODE_O);
        getInstrumentation().waitForIdleSync();
        getInstrumentation().runOnMainSync(new Runnable() {
            @Override
            public void run() {
                myBut.performClick();
            }
        });
        getInstrumentation().waitForIdleSync();
        SystemClock.sleep(1000);
        assertEquals(this.content.getText().toString(),this.myEdit.getText().toString());
    }
}

 

 

 

Note:

 

I. In the construction of the MyFirstTest class, because the detailed information of the Activity of the tested project is specified, MyFirstTest is associated with the Activity.

 

The Ⅱ setUp () method is an override method. It serves to make necessary settings before testing, such as instantiating some objects and opening the network. It works with tearDown () methods appear in pairs. The tearDown () method is not implemented here. After the test is completed, the Framework automatically calls back the base class, that is, the tearDown () method.

 

Finally, run the test class, as shown in:

 


 

 

After the system completes the test, you can get the following results in the integrated development environment of Android studio:

 

 


 

 

As shown in the figure, the return value of the Test class is OK, which proves that the Test has achieved the expected purpose.


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.