Service of four components (iv)-service threads, worker threads, permissions, and system service

Source: Internet
Author: User
Tags add time

Section 5th service threads and worker threads

When you start using it Service , there's always a myth: think of it as Service running in a separate thread in your app. In fact, the Service components, like other components, are running in the main thread of the application, all running on the same single thread.

Can be Service simply understood as a no interface display Activity (this metaphor is not accurate, because Service you can invoke WindowManager the implementation of the interface display, but here for the moment to understand it).

If you need to Service do a continuous, time-consuming task, you need to open a worker thread for it.

Now that you have a Service separate thread to open for time-consuming work, why not let Activity Service the job replace it? For example, to download a file from the network, you can have the application corresponding to Activity open a download thread to download the work separately. Even if the user wants to use other apps when downloading, it's OK to click on the HOME button. The one that downloads the file Activity is automatically hidden and doesn't affect the use of other apps at all.

This may seem to be possible, but you must not overlook the recovery mechanism of the Android system. If the system resources need to be recycled, the operating system may have hidden up Activity to the recycling, so it is necessary to run a long-term task and may be purged at any time the Activity association is very dangerous. So the Android system introduced Service components to handle this situation. The Service importance of components in the system is second only to "actvity interacting with the user" and is the most unlikely component to be automatically reclaimed by the system. This ensures that long-running tasks can always be run.

5.1 Intentservice

Most of the time, starting one Service is to get it to complete a complex and time-consuming task, and when it's done, it's Service ready to quit.

For example, file download. ActivityInterface start responsible for downloading Service , Service quiet Download, download completed, you can exit. During the download process, Activity you can continue to show the progress of the download, or you can exit completely without worrying about the current status.

The Android SDK has prepared such a ready-made for Service developers IntentService .

IntentServiceis a Service subclass that is designed to use the scene above. The Android SDK Service further encapsulates and expands the class to make it easy for developers to use it without having to reinvent the wheel.

Use IntentService ,

  1. Inherit Intentservice to implement its onhandlerintent () function. onhandlerintent () is called in a worker thread, so you can add time-consuming task handling to it,

    publicclass MyIntentService extends IntentService {    publicMyIntentService() {        super("MyIntentService");    }    @Override    protectedvoidonHandleIntent(Intent intent) {        //添加耗时的任务处理        //如果intent携带参数,可以从intent中获取参数        ......    }}
  2. In the AndroidManifest.xml document, declare this Service ;

When you use it, you can start it directly Service .

Intent intent=new Intent(this,MyIntentService.class);//如果需要传递参数,可以将参数放到intent当中startService(intent);

IntentServiceThere are several places to be aware of,

    1. The task Intent is published and, if necessary, parameters can be Intent passed through;
    2. Once the task is completed, Service it exits;
    3. Can handle multiple Intent requests, but will be processed according to the requested first served, one after the completion, if there is no task, Service then quit;
Section 6th Service usage rights

As with all other application components, Service it needs to be declared in a AndroidManifest.xml file.

In the applied AndroidManifest.xml file, to set the Service properties on android:exported ,

<service    android:name=".MyService"    android:enabled="true"    android:exported="true"></service>
    1. android:exportedproperty is set true to: can be used by other applications;
    2. android:exportedproperty is set false to: can only be used by their own application;

When opening to other apps Service , you can also set up access permissions, only those that are open to some apps.

6.1 Service Set permissions
  1. In a AndroidManifest.xml file, Service android:permission The property value can optionally specify a string for the property on which you want to set permissions. It is common to use the package name of a program as part of it to avoid conflicts with permission declarations in other apps. For example "com.anddle.serviceaccess ,

    <service    android:name=".MyService"    android:enabled="true"    android:exported="true"    android:permission="com.anddle.serviceaccess" />
  2. In the AndroidManifest.xml file, with the position of the sibling, declare the label previously used, indicating that the application published a com.anddle.serviceaccess permission called,

    <manifest  xmlns:android  = "http://schemas.android.com/apk/res/android"  package  = "Com.anddle.lifetime"  >  <permission  andro Id:name  = "com.anddle.serviceaccess"  android: Label  = "service Pomission"  android: ProtectionLevel  = "normal" />  <application   ...  />,  </manifest ;  

    The android:name value of the property, which is the <service/> value set in the label android:permission .

6.2 Using a service with permissions

If app B wants to use app A with permissions, you need to add permission to the use of application Service B AndroidManifest.xml ,

<manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.anddle.calculator">    <uses-permission android:name="com.anddle.serviceaccess"/>    <application            ....../></manifest>

Where the <uses-permission/> value set in the tag android:name is the permission value of the one declared in application a service .

Section 7th ADB Commissioning and system-brought Service7.1 ADB start-up service

Start a known service with the ADB tool,

$ ./adb shell am startservice -n 包名/包名.activity名称

Here the package name is like: com.android.xxx, for example

com.android.xxx/com.android.xxx.MyService
7.2 The system comes with the service

The Android system also comes with a lot of Service , for example, and so WindowManager BluetoothManager on.

It's also easy to use them, for example,

//获取WindowManagerWindowManager windowmanager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);windowmanager.xxx();//获取BluetoothManagerBluetoothManager bluetoothmanager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);bluetoothmanager.xxx();

After obtaining these Service externally available interfaces, these interfaces can be used.

There's a lot of similar service,

Service of four components (iv)-service threads, worker threads, permissions, and system service

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.