Appwidget Introductory Tutorials in Android _android

Source: Internet
Author: User

What is Appwidget? Appwidget is what we usually see on the desktop of the kind of small window, the use of this small window can provide users with some convenient and efficient operation. This article intends to introduce appwidget from the following points:

1. How to create a simple appwidget
2. How to make Appwidget interact with client programs

Create a simple Appwidget

Before the introduction, let us have a look at the final results of the program operation and the project structure, so that everyone has a overall impression.

Run the result diagram:

Project Structure Chart:

First step:

Start by creating a new folder named XML under the Res folder, and then create an XML file named appwidget01 in the XML directory (as shown in the figure above). The contents of this appwidget01 are as follows:

Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<appwidget-provider
Xmlns:android= "Http://schemas.android.com/apk/res/android"
Android:minwidth = "294DP"
Android:minheight = "72DP"
Android:updateperiodmillis = "86400000"
Android:initiallayout = "@layout/appwidgetlayout"
>
</appwidget-provider>

This XML is used to describe some of the appwidget that you want to create, such as height, width, refresh interval, layout file, and so on. Just this description file is not enough, we see the appwidget can have interface elements, such as text, pictures, buttons and so on, the definition of these things need to be placed under the Layout folder. This file is the appwidgetlayout that is written in the code above.

Step Two:

Creating a new Appwidgetlayout.xml file under the Layout folder that describes Appwidget controls and layouts, and so on, is no different than the layout file of an activity we normally create, because it's just a simple demo, so it's only a single text and a button. The contents of the XML are as follows:

Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
Android:layout_width= "Fill_parent" android:layout_height= "Fill_parent" >
<textview android:id= "@+id/txtapp" android:text= "test" android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content" android:background= "#ffffff" ></TextView>
<button android:id= "@+id/btnsend" android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content" android:text= "Send" ></Button>
</LinearLayout>

Step Three:

Now that there are buttons and so on in the appwidget, there must be no processing code to handle these control events. The code is placed in a class that inherits from Appwidgetprovider, and in this case I create a new Appwidget class that inherits from Appwidgetprovider, and all subsequent control events in the Appwidget are processed in this class. Look at the contents of the class:

Copy Code code as follows:

public class Appwidget extends Appwidgetprovider
{

Private final String broadcaststring = "Com.qlf.appWidgetUpdate";

/**
* Call when a appwidget is deleted
* */
@Override
public void ondeleted (context context, int[] appwidgetids)
{
Super.ondeleted (context, appwidgetids);
}

/**
* Called when the last Appwidget is deleted
* */
@Override
public void ondisabled
{
super.ondisabled (context);
}

/**
* Appwidget instance is invoked the first time it is created
* */
@Override
public void onenabled
{
super.onenabled (context);
}

/**
* Accept Broadcast Events
* */
@Override
public void OnReceive (context context, Intent Intent)
{

Super.onreceive (context, intent);
}

/**
* is called when the specified update time is reached or when the user adds appwidget to the desktop
* */
@Override
public void OnUpdate, Appwidgetmanager Appwidgetmanager,
Int[] appwidgetids)
{


}

}

The function of each method you can see the comments above. We do not need to implement the inside method for the time being.

Fourth Step:

Define some of the necessary things to create Appwidget in Androidmanifest.xml, first look at the code:

Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<manifest xmlns:android= "Http://schemas.android.com/apk/res/android"
Package= "Com.qlf.widget" android:versioncode= "1" android:versionname= "1.0" >
<application android:icon= "@drawable/icon" android:label= "@string/app_name" >
<activity android:name= ". Mainactivity "android:label=" @string/app_name ">
<intent-filter>
<action android:name= "Android.intent.action.MAIN"/>
<category android:name= "Android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<receiver android:name= "Appwidget" >
<intent-filter>
<action android:name= "Android.appwidget.action.APPWIDGET_UPDATE" ></action>
</intent-filter>
<meta-data android:name= "Android.appwidget.provider"
Android:resource= "@xml/appwidget01"/>
</receiver>
</application>
&LT;USES-SDK android:minsdkversion= "8"/>
</manifest>

You can see that we have defined a receiver in the configuration file whose name is the class where the control code was created, and the action in the Intent-filter below is the system's own broadcast action for updating all appwidget. Then the meta-data tag is a description of the metadata we created Appwidget, the android:name= "Android.appwidget.provider" is fixed, android:resource= "@xml/ appwidget01 "Specifies the location of the descriptive information for the created Appwidget. So the program knows where to initialize these appwidget.

After the above four steps, I think you have been able to successfully add gadgets to the desktop, and the effect is the way we first emit.

Appwidget Interacting with programs

Earlier we simply described how to create a appwidget, but at the moment the appwidget has no interaction capabilities. Here's how Appwidget interacts with the program. The first thing to do is to introduce an object that is important in the interaction of Appwidget and the program, he is remoteviews. Because the process that the Appwidget runs and the application we create is not in a process, we cannot get instances of the control as usual with reference to the control. At this time remoteviews out, literally he means remote view, which means that we can get objects that are not in the same process through this thing, which helps us write appwidget handling events. We use code to create a remoteviews:

Copy Code code as follows:

Remoteviews remoteviews = new Remoteviews (Context.getpackagename (), r.layout.appwidgetlayout);

Remoteviews.setonclickpendingintent (R.id.btnsend, pendingintent); To bind an event to a button on a gadget

You can see that there is a strange object pendingintent, this is what to do? We know that the click event of the Binding button in a generic program is done directly in the class that implements the Onclicklistener interface. But because Appwidget is not in the process of our application, of course, he also can't access the onclick code we set in the application. And pendingintent is used to solve this problem. Pendingintent can be regarded as a special intent, if we think of intent as a letter, then pendingintent is a letter wrapped up in envelopes. The letter was "mailed" to Appwidget in Remoteviews.setonclickpendingintent (), and when the button clicked in Appwidget he knew to open the letter and execute the contents. This avoids the direct execution of local code from Appwidget. Let's look at how the pendingintent is defined:

Copy Code code as follows:

Create a Intent Object
Intent Intent = new Intent ();
Intent.setaction (broadcaststring);

This step is equivalent to writing a letter explaining what the role of this message is, where it indicates that a broadcast will be sent
Pendingintent pendingintent = pendingintent.getbroadcast (context, 0, intent, 0);

With the above introduction, we are much simpler when creating appwidget interactive applications. The rest of the work we have to do is to appwidget the method described above at the time of creation to bind the control event in Appwidget, that is, to complete the procedure in the OnUpdate method under the Appwidget class.

Copy Code code as follows:

/**
* is called when the specified update time is reached or when the user adds appwidget to the desktop
* */
@Override
public void OnUpdate, Appwidgetmanager Appwidgetmanager,
Int[] appwidgetids)
{

Create a Intent Object
Intent Intent = new Intent ();
Intent.setaction (broadcaststring);


Setting the role of pendingintent
Pendingintent pendingintent = pendingintent.getbroadcast (context, 0, intent, 0);
Remoteviews remoteviews = new Remoteviews (Context.getpackagename (), r.layout.appwidgetlayout);


Binding events
Remoteviews.setonclickpendingintent (R.id.btnsend, pendingintent);

Update Appwidget
Appwidgetmanager.updateappwidget (Appwidgetids, remoteviews);
}

With the above code we bind an event to the button button, which is used to send a broadcast to make it easier for other applications to receive and update information. This is Appwidget send a broadcast, so how can appwidget accept broadcasts from other programs? This is the function of the public void OnReceive, Intent Intent. This method will receive broadcasts from other applications, and we can update the Appwidget information by filtering the broadcast we need in the program to respond to other applications. Note that since the Appwidget run process and the application we created are not limited in a process, the updated Appwidget is also operated by Remote objects, as follows:

Copy Code code as follows:

/**
* Accept Broadcast Events
* */
@Override
public void OnReceive (context context, Intent Intent)
{
if (Intent.getaction (). Equals (broadcaststring))
{
control state in Appwidget can be set only through remote objects
Remoteviews remoteviews = new Remoteviews (Context.getpackagename (), r.layout.appwidgetlayout);

Set the text of a button to "Hihi" from a remote object
Remoteviews.settextviewtext (R.id.btnsend, "Hihi");

Obtain a Appwidget management instance for managing Appwidget for update operations
Appwidgetmanager Appwidgetmanager = appwidgetmanager.getinstance (context);

Equivalent to getting all the Appwidget created by this program
ComponentName componentname = new ComponentName (context,appwidget.class);

Update Appwidget
Appwidgetmanager.updateappwidget (ComponentName, remoteviews);
}
Super.onreceive (context, intent);
}

The summary is that the operation on the appwidget must be done with the help of the remote object. Finally look at the running picture bar:

Press before:

After Press:

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.