From scratch - the system in-depth study android (practice - let's start writing code -Android framework for learning -7.App Widgets) ...

 

Chapter 7 App Widgets

App Widgets is a miniature view of an application can be embedded in other applications (such as a main screen) and can be periodically updated. You can publish an application App Widget, which view is called the user interface window. An application component can support other applications App Widgets App Widget is called the host (host). The following is a screenshot App Widget music.

This document describes how to publish and use App Widget in the application.

7.1 Basics

To create an App Widget, you need to know the following:

◆ AppWidgetProviderInfo objects:
metadata describing a App Widget, as in the App Widget layout, update frequency, and AppWidgetProvider class. It should be defined in XML.
◆ AppWidgetProvider achieve class:
defines an interface method for broadcasting events and App Widget based. With it, you will receive broadcast on App Widget update, enable, disable, and delete.
◆ view layouts:
a preliminary App Widget layout is defined in XML.
Additionally, you can achieve Activity App Widget configurable. When a user adds your App Widget, and allow him or her to start the Activity configurable when you modify settings when you create.
This document describes how to publish and use App Widget in the application.

7.2 Manifest.xml in the statement App Widgets

First, you should declare AppWidgetProvider class in AndroidManifest.xml file your application. E.g. Listing 7-1:

Copy the code
<receiver android:name="ExampleAppWidgetProvider" >
    <intent-filter>
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
    </intent-filter>
    <meta-data android:name="android.appwidget.provider"
               android:resource="@xml/example_appwidget_info" />
</receiver>
Copy the code

 

Listing 7-1

<Receiver> nodes need android: name attribute, using the specified App Widget AppWidgetProvider. <Intent-filter> node must contain a <action> name attribute nodes. This attribute specifies AppWidgetProvider accepted ACTION_APPWIDGET_UPDATE broadcast. This is the only broadcast, you must explicitly declare. Other App widget is automatically sent to the broadcast AppWidgetProvider is necessary in AppWidgetManager. <Meta-data> AppWidgetProviderInfo specified resource nodes, you require the following properties:

android: name - the name of the specified metadata. As identified using android.appwidget.provider

◆ AppWidgetProviderInfo data descriptor.

◆ android: resource - AppWidgetProviderInfo specified resource location.

7.3 Add metadata AppWidgetProviderInfo

AppWidgetProviderInfo App Widget is the essence of the definition, such as the minimum size of the layout, the initial layout resources, how to update the App Widget, and (optional) configuration Activity, initiated at the time of creation. AppWidgetProviderInfo objects defined in XML resource file, using the <appwidget-provider> node and stored in the project's res / xml / folder. As shown in Listing 7-2:

Copy the code
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="294dp"
    android:minHeight="72dp"
    android:updatePeriodMillis="86400000"
    android:previewImage="@drawable/preview"
    android:initialLayout="@layout/example_appwidget"
    android:configure="com.example.android.ExampleAppWidgetConfigure" 
    android:resizeMode="horizontal|vertical">
</appwidget-provider>
Copy the code

 

Listing 7-2

The following is <appwidget-provider> summary attributes, before this the best you've read the first part of the chapter Widget design:

◆ the App Widget minWidth by default value of the specified attribute and MinHeight minimum space occupied, AppWidgets default position at the Home screen, the cell in which there is a window on the basis of a specific height and width of the grid. If a minimum width or height value App Widget does not match the size of the cells, the size of the App Widget rounded up to the nearest cell size.

NOTE: To make it easier for transplantation App Widget different devices, App Widget minimum size should not exceed 4 × 4 cell

◆ minResizeWidth and minResizeHeight App Widget attribute specifies the absolute minimum size. These values ​​should be specified under size, otherwise the application will not be able to identify the components or otherwise used. In Android3.1, allows the user to resize the control of these properties, may be smaller than the default size and minheight minwidth defined properties.

◆ updateperiodmillis attribute definition, often in the App Widget framework should appwidgetprovider request a callback method to update by calling onupdate (). Actually not guarantee the accuracy of the update, we recommend updating as little or no more than once per hour, in order to save battery. You can also allow the user to adjust the configuration-some frequency, such as securities ticker, some users may want to update the 15 minutes time, some will want to update only four times a day

NOTE: If the device is asleep, while it is a time (defined updatePeriodMillis) update, the device will be awake to perform the update. If you do not update more than once per hour, this may not cause major problems on battery life. However, if you need frequent updates or you do not need to be updated, and the device is asleep, you can replace the alarm execution will not wake up the device to perform the update. To do this, set up a Intent, when your alarm AppWidgetProvider received, use AlarmManager. It is provided with a ELAPSED_REALTIME or the RTC alarm types, which upon receipt of an alarm, the device wakes. UpdatePeriodMillis then set to zero ( "0").

◆ initialLayout attribute points to the layout resource that defines the layout of the App Widget.

◆ configure the attributes defined in the Activity starts, the user add App Widget, to allow the user to configure App Widget property. This is optional.

◆ after a specified configuration previewImage property App Widget icon looks like, when you select this App Widget user can preview. If no icon, the user thinks laucher your application icon. This field corresponds android: previewImage in AndroidManifest.xml file <receiver> element. Introduced in android3.0.

◆ the introduced Android 3.0, the property specified view autoAdvanceViewId ID App Widget subview.

◆ introduced in Android 3.1, the resizeMode attribute specifies which one can adjust the rules Widget. You can use this property of the main screen Widget adjustment method, such as horizontal, vertical, or two axes. User presses a Widget, the interface displays the adjustment, and then drag the horizontal and / or vertical control key, changing the layout of the mesh size. resizemode attribute values ​​"horizontal", "vertical", and "none". Both as "horizontal | vertical".

7.4 Creating App Widget Layout

You have to define your App widget initial layout, you can define and save the XML project in res / layout / directory. You can use the following View object to design your App widget, but before you start designing your App widget, please read and understand the design principles of App widget. If you are familiar with XML layout, creating a layout App widget is simple. However, you must know the App widget layout are based RemoteViews class, it does not support all kinds of layout or view widget.
RemoteViews a layout object supports the following categories:

FrameLayout

LinearLayout

RelativeLayout

View supports the following widget:

AnalogClock

Button

Chronometer

ImageButton

ImageView

ProgressBar

TextView

ViewFlipper

ListView

GridView

StackView

AdapterViewFlipper

However, a subclass of these classes, but do not support.

1. add margins to App Widgets

widget should not normally extend to the edge of the screen, not the common view with other widget refresh, so you should increase the margins in your widget box. Since Android 4.0 onwards, the App widget provides automatic filling frame and the App widget widget between bounding boxes, so the user a better adjustment and other widget icons in home screen. TargetSdkVersion To achieve this function, you need it the application is set to 14 or higher.
Earlier versions, a layout is easy to prepare and can be custom margins at or above Android4.0 margins and no additional steps are as follows:
targetSdkVersion ◆ setup application is 14 or higher.
◆ create a layout follows, reference dimension resources, as shown in Listing 7-3:

Copy the code
<FrameLayout
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:padding="@dimen/widget_margin">
 
  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:background="@drawable/my_widget_background">
  </LinearLayout>
 
</FrameLayout>
Copy the code

 

Listing 7-3

◆ create a resource of two dimensions, providing a custom margins prior to Android 4.0 in res / values /, a / did not provide extra padding for the Android4.0widgets in RES / values-V14:
RES / values / dimens.xml:

<dimen name="widget_margin">8dp</dimen>

res/values-v14/dimens.xml:

<dimen name="widget_margin">0dp</dimen>

 

7.5 Use AppWidgetProvider class

First of all, you must realize AppWidgetProvider class declared in AndroidManifest <receiver> node inside (see chapter "7.2 Manifest.xml in the statement App Widgets").

AppWidgetProvider inherited broadcastreceiver broadcast to handle App widget is very convenient. AppWidgetProvider only receive event broadcasts and App widget-related, such as when App widget update, delete the relevant App widget, enable and disable. These broadcast events, AppWidgetProvider will call the following methods:
◆ onUpdate () 

This attribute defines the AppWidgetProviderInfo updatePeriodMillis by the time interval to make AppWidget update. When a user adds App widget, this approach is called, so it should be a basic setup, processing View events as defined, if necessary, should start provisional service. However, if you have declared Activity configuration, when a user adds App widge this method is not called, but a subsequent update call. After configuring the Activity completed, its role is to perform the first update.

◆onAppWidgetOptionsChanged()

When wodget is first adjusted to be called. You can use this callback to show or hide the contents. You can be obtained by getAppWidgetOptions () size range, it returns the Bundle, you can use the following String key, to obtain the value:

AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH- current minimum width, measured in DP

AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT- current minimum height, measured in DP

AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH- current maximum width, measured in DP

AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT- current maximum height, measured in DP

Android4.1 from the introduction of this method. Please note

◆onDeleted(Context, int[])

Every time a App Widget is called when removed from the App Widget host.

◆onEnabled(Context)

Called when App widget instance is first created. For example, if you add two instances of the same App widget, which also is called only once. If you need to open a new database or other settings, then this place is a very good example.

◆onDisabled(Context)

When the instance is called when the last App widget is removed from the App widget host using onDisabled (Context) method to clean up, such as deleting temporary database.

◆onReceive(Context, Intent)

It can be understood as a general broadcast receiving interface, a callback of each of the above method. You usually do not need to implement this method, because the default AppWidgetProvider implement filters all App widget broadcast, and call the appropriate method described above.

 

When each App widget to add a host, the most important thing is AppWidgetProvider onUpdate () callback method (unless you use a configuration of Activity). If your App widget accept any user interaction event, then the callback, you need to register event handlers. If your App widget can not create temporary files or databases, or perform other work, it needs to be clear, onUpdate () method, may be the only thing you need to define a callback method. For example, if you want to have a button on a App widget, start an Activity When you click on something, you can achieve AppWidgetProvider, as shown in Listing 7-4:

Copy the code
public class ExampleAppWidgetProvider extends AppWidgetProvider {
 
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int N = appWidgetIds.length;
 
        for (int i=0; i<N; i++) {
            int appWidgetId = appWidgetIds[i];
 
                Intent intent = new Intent(context, ExampleActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget_provider_layout);
            views.setOnClickPendingIntent(R.id.button, pendingIntent);
            appWidgetManager.updateAppWidget(appWidgetId, views);
        }
    }
}
Copy the code

 

Listing 7-4

7-4 AppWidgetProvider code listing above define only onUpdate () method, the purpose of which is to define a start PendingIntent using an Activity using setonclickpendingintent (int, pendingintent) attached to App widget button. Note that, in appWidgetIds it comprises a loop through each entry, which is an array of identity id, determine each App widget. Thus, if a user creates multiple instances App widget, and then they are updated simultaneously. However, only a updateperiodmillis schedule will manage all App widget. For example, if the update program is defined as every two hours, waiting for the first one hour after the addition of the second instance, they will use the first two periods while the second update cycle will be ignored. Readers can refer to ApiDemos \ src \ com \ example \ android \ apis \ appwidget example of.

AppWidgetProvider is a convenience class only. If you want to receive direct broadcast App widget, you can achieve onReceive (Context, Intent) BroadcastReceiver own or covering methods. You need to pay attention to the following intent: 

ACTION_APPWIDGET_UPDATE

ACTION_APPWIDGET_DELETED

ACTION_APPWIDGET_ENABLED

ACTION_APPWIDGET_DISABLED

ACTION_APPWIDGET_OPTIONS_CHANGED

7.6 create a App Widget configuration Activity

If you want a user, when he added a new App widget to configure the settings, you can create a App widget configuration Activity. The current Acitivity App widget will automatically start the host, and allows the user to configure App widget color, size and update period or set other functions at the time of creation. This configuration Activity should be declared in the Android manifest file is a standard Activity. However, it will be started by using ACTION_APPWIDGET_CONFIGURE Action App widget host, so this needs to receive this Activity Intent. As shown in Listing 7-5:

<activity android:name=".ExampleAppWidgetConfigure">
    <intent-filter>
        <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
    </intent-filter>
</activity>

 

Listing 7-5

In addition, Activity must be declared in AppWidgetProviderInfo XML file android: configure the properties (see the previous section "Adding AppWidgetProviderInfo metadata"). For example, Activity declared to be configured as shown in Listing 7-6:

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    android:configure="com.example.android.ExampleAppWidgetConfigure" 
    ... >
</appwidget-provider>

 

Listing 7-6

Note that this Activity is declared fully qualified namespace, because it is referenced from outside the package.
What you need is to start a configuration Activity. Now all you need is the actual Activity. However, when you realize Activity There are two important things to remember:

◆ call this App widget host configuration Activity, and the configuration Activity should always return a result code. This result code should include App widget ID.

◆ When creating App widget OnUpdate () method will not be called (when configuring the Activity starts, the system does not send ACTION_APPWIDGET_UPDATE broadcast).

This is the configuration Activity of responsibility, when it requests an update from the App widget is first created AppWidgetManager. However, The onUpdate () method calls a subsequent update, it is only once the first skip.

See the following code fragment, to see how the results after it returned to configure and update the App widget.

When a App widget using the configuration Activity, Activity after this configuration is responsible for updating App widget. You can update directly from AppWidgetManager by request.
1. obtained from App widget ID of the starting Intent Activity by:

Copy the code
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
    mAppWidgetId = extras.getInt (
            AppWidgetManager.EXTRA_APPWIDGET_ID, 
            AppWidgetManager.INVALID_APPWIDGET_ID);
}
Copy the code

 

2. Do your App widget configuration.
3. When the configuration is complete, get a AppWidgetManager instance by calling getInstance (context):

AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

4. RemoteViews layouts used by calling updateAppWidget (int, RemoteViews) Update App widget:

RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.example_appwidget);
appWidgetManager.updateAppWidget(mAppWidgetId, views);

5. Finally, create the intent to return, provided the results of the Activity and terminates the Activity:

Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
finish();

 

7.7 Setting a preview of the picture

Android3.0 after the introduction of previewImage property, which specifies a Appwidget thumbnail. Let's look at the code in Listing 7-7 to see how to set

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
  ...
  android:previewImage="@drawable/preview">
</appwidget-provider>

Listing 7-7

To help your Appwidget (specified in the previewImage field) to create a preview image in the Android emulator includes an application program is called "Widget Preview". To create a preview image, will have to start the application, select Appwidget your application, and you want to set the preview image, then save it and put it in the drawable resources your application.

Reproduced in: https: //www.cnblogs.com/Codenewbie/articles/2973154.html

Guess you like

Origin blog.csdn.net/weixin_34054931/article/details/93448033