Appwidgetservice at the core of Android appwidget

Source: Internet
Author: User

Tian haili @ csdn

2012-9-12

 

This article describes the core appwidgetservice of the appwidget System in Android. This article describes the external interfaces, internal data structures, initialization processes, and typical scenarios provided by appwidgetservice.

As mentioned above, instances of the host and provider roles in the androidappwidget system participate in the appwidget system through the methods provided by the appwidgethost/appwidgetmanager component. The actual appwidgethost/appwidgetmanager uses androidaidl to interact with appwidgetservice through iappwidgetservice, thus implementing the coordinated operation of host/provider/service running in different processes. In addition, appwidgethost provides callback to appwidgetservice by implementing iappwidgethost to notify the host when the provider is updated. The notification to the provider directly sends a broadcast message to the provider [7].

 

1. external interface of appwidgetservice

Describes the external interface of appwidgetservice.


Figure 1 external interface of appwidgetservice

 

Appwidgetservice provides external services through the standard aidl method iappwidgetservice.

Appwidgethost provides the methods required for host operations. These methods are actually implemented by calling iappwidgetservice using aidl. appwidgetmanager provides the methods required for host and provider operations, these methods are implemented by calling iappwidgetservice through aidl.

 

2. Internal data structure of appwidgetservice-Static Analysis

 

Is the data structure in appwidgetservice.

 

Figure 2 appwidgetservice Internal Data Structure

 

Minstalledproviders: Arraylist <appwidgetservice. provider> record all installed appwidgetprovider [Analysis and Application of appwidget in Android: appwidgetprovider] describes the process that a single appwidgetprovider is recognized by the appwidget system. Section #3.1 (1) describes the process of loading appwidgetprovider in all systems ]. Where,

  • UID: int records the UID of the process where the appwidgetprovider is running;
  • Info: appwidgetproviderinfo records the appwidgetprovider information;
  • Instances: arraylist <appwidgetid> records information bound to the appwidgetprovider (it can be bound to multiple hosts );
  • Broadcast: pendingintent when the provider needs to be periodically refreshed (updateperiodmillis attribute value is greater than 0), appwidgetmanager. action_appwidget_update is generated periodically to update the provider;
  • Zombie records whether the appwidgetprovider state is dead, because it manages multiple processes. If the process where the provider is located is dead, it also processes the host bound to it.
  • Tag: records the index value when the int is saved.

Mhosts: Arraylist <appwidgetservice. Host> records appwidgethost information. Where,

  • UID: int records the UID of the process where the appwidgethost runs;
  • Hostid: the int records the ID of appwidgethost, which is specified when appwidgethost is registered;
  • Packagename: String record
  • Instances: arraylist <appwidgetid> records information bound to the appwidgethost (it can be bound to multiple providers );
  • Callbacks: iappwidgethost is used to notify the host when the provider bound to the host changes.
  • Zombie records whether the appwidgethost state is dead, because it manages multiple processes. If the process of the host is dead, the provider bound to it should also be processed.
  • Tag: records the index value when the int is saved.

Mappwidgetids: Arraylist <appwidgetservice. appwidgetid> records information bound to the host of all providers. Where,

  • Appwidgetid: The ID bound to the int record, applied by allocateappwidgetid;
  • Provider: The provider bound to appwidgetservice. provider;
  • HOST: the host bound to appwidgetservice. Host;
  • Views: remoteviews records the remoteviews created by the provider, which notifies the host to display the content provided by the provider.

 

Now, these attributes may be vague. In the subsequent analysis, you can fully understand the meaning of these attributes.

 

3. appwidgetservice Initialization

Appwidgetservice runs in the system_process process. The initialization process is as follows:

  • Systemready initialization;
  • Initialization after receiving action_boot_completed.

 

3.1 appwidgetservice. systemready () initialization

Start serverthread in init2 () of systemserver. In the serverthread, create an appwidgetservice instance, add it to servicemanager, and then execute appwidgetservice. systemready ().

 

In appwidgetservice. systemready (), execute the followingThree operations:

 

(1) execute loadappwidgetlist () to search for all installed appwidgetproviders from the Android system, parse the information in it into appwidgetservice. provider, and add it to minstalledproviders: arraylist <provider>.

    void loadAppWidgetList() {       PackageManager pm = mPackageManager;        Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);       List<ResolveInfo> broadcastReceivers =pm.queryBroadcastReceivers(intent,               PackageManager.GET_META_DATA);        final int N = broadcastReceivers == null ? 0 :broadcastReceivers.size();       for (int i=0; i<N; i++) {           ResolveInfo ri = broadcastReceivers.get(i);           addProviderLocked(ri);        }    }

1. Retrieve all intent-filter action in the system as the handler of appwidgetmanager. action_appwidget_update and put it into broadcastreceivers: List <resolveinfo>; [line #2 ~ 6]

2. For each such broadcast receiver, add it to the list of installed appwidgetprovider minstalledproviders: arraylist <provider>. [Line #8 ~ 12]

Addproviderlocked () is used to add to the appwidgetprovider list:

   boolean addProviderLocked(ResolveInfo ri) {       Provider p = parseProviderInfoXml(newComponentName(ri.activityInfo.packageName,                    ri.activityInfo.name), ri);        if(p != null) {           mInstalledProviders.add(p);            return true;        }else {           return false;        }    }

Parseproviderinfoxml () parses the configuration information of the provider configured in the XML file pointed to by appwidgetmanager. meta_data_appwidget_provider ("android. appwidget. provider") in meta-data and stores it in info: appwidgetproviderinfo of the provider. In addition, the UID of the provider is also retrieved.

Provider is added to minstalledproviders: arraylist <provider>.

For details about how to configure appwidgetprovider, see appwidget Analysis and Application in Android: appwidgetprovider.

 

(2) execute loadstatelocked (), read the information bound to provider and host and provider from the/data/system/appwidgets. xml file, and put the informationMinstalledproviders, mhostsAndMappwidgetids.

In the system, only the launcher has a corresponding appwidgets. xml file of the "power control" appwidget.

<gs>    <ppkg="com.android.settings"      cl="com.android.settings.widget.SettingsAppWidgetProvider"/>    

Where,

  • Node P corresponds to appwidgetprovider. PKG and CL are packagename and classname respectively.
  • Node H corresponds to appwidgethost. PKG is packagename; ID is hostid.
  • Node G is the binding relationship between provider and host. ID is its identifier. It is applied before binding through allocateappwidgetid; H corresponds to the index of appwidgethost; P corresponds to the index of appwidgetprovider.

 

The following describes how to establish the data structure in section #2:

For P nodes, retrieve the minstalledproviders: arraylist <provider> obtained in step (1) Through packagename and classname to obtain the specific provider Information. The provider is temporarily saved;

For the H node, create appwidgetservice.HostObject, andPackagenameObtainUID, Obtained by parsing the IDHostidIt is in hexadecimal format. Add the Host objectMhosts: Arraylist

For G nodes, createAppwidgetidThe ID parsed by XML is also in hexadecimal format and assignedAppwidgetid. Locate the provider by pointing to the index (hexadecimal) of the provider through P and assign the value to appwidgetid.Provider. Locate the host through H pointing to the host index (hexadecimal) and assign it to appwidgetid.Host. Provider and hostInstancesAll point to the current appwidgetid object. Then add the appwidgetid objectMappwidgetids: Arraylist <appwidgetid>.

 

In this way, the provider object, the host object, and the binding relationship with the provider are also used separately.Minstalledproviders: Arraylist <appwidgetservice. provider>,Mhosts: Arraylist <appwidgetservice. Host>, andMappwidgetids: Arraylist <appwidgetservice. appwidgetid> is created.

 

(3) register four broadcastreceiver:

1) intent. action_boot_completed

After the Android system is started, some initialization work is required for appwidgetservice.

2) intent. action_configuration_changed

Android configuration changes

3) intent. action_package_added/intent. action_package_removed

Application added/deleted

4) intent. action_external_applications_available/intent. action_external_applications_unavailable

Install and uninstall sdcard

 

3.2 initialize appwidgetservice after the system is started

After the Android system is started, intent. action_boot_completed broadcast is sent.

 

Appwidgetservice is in the receiver of intent. action_boot_completed broadcast.Sendinitialbroadcasts:

Retrieve minstalledproviders to obtain all the providers and obtain the bound appwidgetproviders through provider. instances.

For these providers,

  • Send an appwidgetmanager. action_appwidget_enabled broadcast.
  • Send an appwidgetmanager. action_appwidget_update broadcast.
  • According to the provider configuration, if updateperiodmillis is greater than 0, register the timed update broadcast. The appwidgetmanager. action_appwidget_update broadcast is sent to the provider periodically.

 

3.3 entire initialization process

The above appwidgetservice Initialization is part of the appwidget system initialization, as well as the initialization process involving appwidgethost and appwidgetprovider.

 

The complete process is as follows:

(1) appwidgetservice. systemready () initialization

Section #3.1, complete:

  • Obtain all appwidgetproviders from packagemanager and initialize minstalledproviders;
  • Read the bound appwidget from the file/data/system/appwidgets. xml and initialize mhosts and mappwidgetids;
  • Register the required broadcast receivers.

 

(2) launcher registers with startlistening () of appwidgethost.

Appwidgethost constructs the iappwidgethost object, and passes the list of callback, hostid, and remoteviews to the service through startlistening () of the iappwidgetservice. The implementation in appwidgetservice is as follows:

    public int[] startListening(IAppWidgetHost callbacks, String packageName, int hostId,            List<RemoteViews> updatedViews) {       int callingUid = enforceCallingUid(packageName);       synchronized (mAppWidgetIds) {           Host host = lookupOrAddHostLocked(callingUid, packageName, hostId);           host.callbacks = callbacks;            updatedViews.clear();            ArrayList<AppWidgetId> instances = host.instances;           int N = instances.size();           int[] updatedIds = new int[N];           for (int i=0; i<N; i++) {               AppWidgetId id = instances.get(i);               updatedIds[i] = id.appWidgetId;               updatedViews.add(id.views);           }           return updatedIds;        }    }

  • You can use lookuporaddhostlocked () to retrieve whether a host object exists in mhosts: arraylist <appwidgetservice. Host>. If not, create a new host object and add it to mhosts. [Line #5]
  • Save the callback of appwidgethost to host. callbacks. Here is only the remote proxy of appwidgethost in the service; [line #6]
  • Host. Instances stores the binding relationship with the host, from which:
    • Obtain appwidgetid;
    • Add existing remoteviews to the list of remoteviews on appwidgethost.

 

Returns all appwidgetid associated with the host.

 

(3) launcher starts loading the appwidget in the database normally

Analysis of APP widget processing by launcher in Android: appwidgethost role #3.

At the first startup, load the initialization appwidget from default_workspace.xml and add it to the data model;

Read the appwidget information from the database and create an appwidgethostview local display.

 

(4) appwidgetservice initialization after the system is started

Section #3.2

Send enable and update broadcasts to all associated appwidgetproviders, and set up a periodic refresh mechanism based on the configuration.

 

(5) After the appwidgetprovider receives the broadcast, it will call the onenabled () method and onupdate () method to execute the operation.

The process described in appwidget Analysis and Application in Android: appwidgetprovider.

  • Initialize the onenabled () method;
  • Create a remoteviews layout object in the onupdate () method, and notify appwidgethost to update the appwidgetihost corresponding to appwidgetid through appwidgetmanager. updateappwidget (intappwidgetid, remoteviews.

After the appwidgetservice receives the appwidgetid and remoteviews, it finds the binding relationship between the provider and the host through appwidgetid, and notifies the host to update the layout in remoteviews to the appwidgethostview layout object through the callback of the iappwidgethost.

In this way, the appwidget is displayed in launcher.

 

IV. Implementation of appwidgetservice

Appwidgetservice provides various services through iappwidgetservice. appwidgethost and appwidgetmanager encapsulate the use of this method. The appwidgethost role uses appwidgethost and appwidgetmanager to use appwidgetservice services. The appwidgetprovider role uses appwidgetservice through appwidgetmanager, and appwidgetservice directly operates or notifies appwidgetprovider.

Section #2 Internal Data StructureMinstalledproviders,MhostsAndMappwidgetidsThese mechanisms are crucial.

 

This chapter describes how appwidgetservice implements various functions provided by appwidgethost and appwidgetmanager Based on typical scenarios.

 

See the implementation of the services provided by appwidgetservice.Sequence Chart. Mainly include:

Appwidgethost. startlistening ()

Appwidgethost registers with the appwidget system.

Appwidgethost. allocateappwidgetid ()

Appwidgethost applies for appwidgetid. Before appwidgethost (e.g. launcher) selects appwidgetprovider, it first applies to the appwidget system and describes this scenario in Android select and bind appwidget. For the first time in launcher to read the appwidget information from the configuration, you must also apply for appwidgetid. In Android, launcher's analysis of appwidget processing: appwidgethost role #2 describes this scenario. The implementation is described in appwidgetservice in this article 4.2.

Appwidgetmanager. getinstalledproviders ()

Obtain all appwidgetprovider in the system. Appwidgetpicker lists all appwidgetproviders in the system. This scenario is described in "select and bind appwidget in Android" #3. The implementation is described in appwidgetservice in this article 4.3.

Appwidgetmanager. bindappwidgetid ()

Bind appwidgetid and appwidgetprovider. Appwidgetpicker selects an appwidgetprovider and binds it with the applied appwidgetid. Select and bind an appwidget in Android #4 to describe this scenario. For the first time in launcher to read the appwidget information from the configuration, you must also apply for appwidgetid. In Android, launcher's analysis of appwidget processing: appwidgethost role #2 describes this scenario. The implementation is described in appwidgetservice in this article 4.4.

Appwidgetmanager. getappwidgetinfo ()

Appwidgetid is used to obtain the bound appwidgetproviderinfo. After the appwidget is selected and bound in Android, appwidgetid can be used to obtain the appwidgetproviderinfo bound to it. The selected launcher is used as an example. In Android, the launcher analyzes appwidget processing: appwidgethost role, which is described in #1 and #3.4. This article 4.5 describes the implementation in appwidgetservice.

Iappwidgetservice. getappwidgetviews ()

Obtain the remoteviews provided by appwidgetprovider. After appwidgethost creates appwidgethostview, if appwidgetprovider already provides remoteviews, you can obtain them and set them to appwidgethostview. Analysis on appwidget processing by launcher in Android: appwidgethost role #1 this scenario is described in figure 2. This article 4.6 describes the implementation in appwidgetservice.

Appwidgetmanager. updateappwidget ()

Set remoteviews provided by appwidgetprovider. After appwidgetprovider creates remoteviews, it notifies appwidgetservic through this interface. The analysis and application of appwidget in Android: appwidgetprovider #5 describes this scenario. This article 4.7 describes the implementation in appwidgetservice.

 

4.1 register appwidgethost

Prototype: publicint [] startlistening (iappwidgethost callbacks, string packagename, int hostid, list <remoteviews> updatedviews)

Appwidgethost hasIappwidgethost(Via callbacks) Implementation mcallbacks: appwidgethost. callbacks. In appwidgethost. startlistening (), appwidgethost registers iappwidgethost, hostid, and other information to appwidgetservice through iappwidgetservice.

From 3.3 (2), you can see the specific implementation. Mhosts stores the registered appwidgethost; mhosts. Instances stores the information bound to the Host: appwidgetid. The views of appwidgetid stores the remoteviews created and provided by the provider. At this time, content may already exist and be added to the parameters passed in by appwidgethost. If appwidgethostview already exists, appwidgethost updates appwidgethostview with remoteviews through appwidgethostview. updateappwidget.

 

4.2 apply for appwidgetid

Prototype: publicint allocateappwidgetid (string packagename, int hostid)

Implementation:

Generate an ID: int;

Search by packagename and hostidMhostsAppwidgetservice. Host Object in;

Create an appwidgetid objectAppwidgetidAnd hostid, and add it to the instances of the host andMappwidgetids:Appwidgetservice. appwidgetid.

 

4.3 obtain the list of all appwidgetproviders

Prototype: publiclist <appwidgetproviderinfo> getinstalledproviders ()

Implementation: during system initialization, all appwidgetprovider information has been retrieved and putMinstalledproviders: Appwidgetservice. provider. Here, we can directly combine info in minstalledproviders into a linked list.

 

4.4 bind an appwidget

Prototype: publicvoid bindappwidgetid (INT appwidgetid, componentname provider)

Implementation:

Search by appwidgetidMappwidgetids: appwidgetservice. appwidgetidAppwidgetid object in;

Search by providerMinstalledproviders: appwidgetservice. ProviderProvider object in;

Associate the provider object with the appwidgetid object through the provider of appwidgetid and the instances of the provider;

Send enable and update broadcasts to appwidgetprovider.

 

4.5 obtain the specified appwidgetproviderinfo

Prototype: publicappwidgetproviderinfo getappwidgetinfo (INT appwidgetid)

Implementation:

Search by appwidgetidMappwidgetids: appwidgetservice. appwidgetidAppwidgetid object in;

Return the info in the provider of the appwidgetid object.

 

4.6 obtain remoteviews

Prototype: publicremoteviews getappwidgetviews (INT appwidgetid)

Implementation:

Search by appwidgetidMappwidgetids: appwidgetservice. appwidgetidAppwidgetid object in;

Return the views: remoteviews in the appwidgetid object.

 

4.7 provide remoteviews

Prototype: publicvoid updateappwidgetprovider (componentname provider, remoteviews views)

Search by parameter <provider>Minstalledproviders: Provider object in appwidgetservice. provider;

Get arraylist <appwidgetid> through instances of the provider object, that is, all objects associated with the provider;

Notify appwidgethost of all objects in the arraylist <appwidgetid> through the callback interface of the host, and update appwidgethostview with remoteviews.

 

Related Articles

 

Through this series of related articles, you can obtain the information associated with this article:

 

Androidappwidget framework

Briefly describe the appwidget system framework and briefly describe the components.

Select and bind an appwidget in Android

Describes the process in which launcher is initiated as appwidgethost and appwidgetpickactivity is selected and bound to appwidgetprovider in settings.

Appwidget Analysis and Application in Android: appwidgetprovider

Taking settingsappwidgetprovider as an example, through the description of the internal implementation mechanism of appwidgetprovider, readers can deeply understand what to pay attention to when developing appwidgetprovider.

Analysis of appwidget processing by launcher in Android: appwidgethost role

Taking launcher as an example, it is used as a description of appwidgethost's appwidget implementation process, so that readers can understand how appwidgethost is implemented.

Implementation of remoteviews in Android

Analyzes the internal implementation of remoteviews in Android based on the appwidget application scenario.

Appwidgetservice, the core of Android appwidget

Appwidgetservice provides services and internal implementation.

 

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.