The Appwidget of Android-launcher development (2)

Source: Internet
Author: User

Appwidget data communication via memory sharing. Schematic diagram is as follows:


1. Create a broadcastreceiver and inherit the Appwidgetprovider.

2. Configure the following in Androidmanifest.xml: The following is the official website example <action/> is necessary.

    <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>

3. Provide a <meta-data/> tag resource XML file, define the Appwidget style properties (configuration parameters optional)

<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 "    android: widgetcategory= "Home_screen|keyguard"    android:initialkeyguardlayout= "@layout/example_keyguard" ></ Appwidget-provider>
4. Define the style of the appwidget. Define a layout file to be an arrangement file and configure it in the Intiallayout property above.

5. When the user clicks on select to add a widget. First get Appwidgetid, and open a select widget for activity

6. After selection, get Appwidgetinfo through Appwidgetid and convert to Launcherappwidgetinfo object and add to workspace.

Of course, this time includes the location of the Appwidget. Its added source code is as follows:

 private void Completeaddappwidget (Intent data, Celllayout.cellinfo cellinfo) {Bundle extras = Data.getextras ();        int appwidgetid = Extras.getint (appwidgetmanager.extra_appwidget_id,-1);        if (LOGD) log.d (TAG, "dumping extras content=" + extras.tostring ());        Appwidgetproviderinfo appwidgetinfo = Mappwidgetmanager.getappwidgetinfo (Appwidgetid); Calculate the grid spans needed to fit this widget celllayout layout = (celllayout) mworkspace.getchildat (Cellin        Fo.screen);        Int[] spans = Layout.recttocell (Appwidgetinfo.minwidth, appwidgetinfo.minheight);        Try Finding open space on Launcher screen final int[] xy = mcellcoordinates; if (!findslot (Cellinfo, XY, spans[0], spans[1])) {if (Appwidgetid! =-1) mappwidgethost.deleteappwidgetid (APPW            Idgetid);        Return }//Build Launcher-specific widget info and save to database launcherappwidgetinfo Launcherinfo = new Launc Herappwidgetinfo (Appwidgetid);        Launcherinfo.spanx = Spans[0];        Launcherinfo.spany = spans[1];                Launchermodel.additemtodatabase (This, Launcherinfo, LauncherSettings.Favorites.CONTAINER_DESKTOP,        Mworkspace.getcurrentscreen (), xy[0], xy[1], false);            if (!mrestoring) {mdesktopitems.add (launcherinfo); Perform actual inflation because we ' re live Launcherinfo.hostview = Mappwidgethost.createview (This, Appwidge            TId, Appwidgetinfo);            LauncherInfo.hostView.setAppWidget (Appwidgetid, appwidgetinfo);            LauncherInfo.hostView.setTag (Launcherinfo); Mworkspace.addincurrentscreen (Launcherinfo.hostview, xy[0], xy[1], Launcherinfo.spanx, LauncherInfo.spa        NY, isworkspacelocked ()); }    }
Summary: When we finish the first 3 steps, the system will create widgets based on the user's choice.

--Update the Appwidget interface with the following principles:



1AppWidgetManager send broadcast pass ID.

void updateprovidersforpackagelocked (String pkgname) {hashset<string> keep = new hashset<string> ();        Intent Intent = new Intent (appwidgetmanager.action_appwidget_update);        Intent.setpackage (Pkgname); list<resolveinfo> broadcastreceivers = mpackagemanager.querybroadcastreceivers (Intent, PackageManager .        Get_meta_data); Add the missing ones and collect which ones to keep int N = Broadcastreceivers = null?        0:broadcastreceivers.size ();            for (int i=0; i<n; i++) {ResolveInfo ri = broadcastreceivers.get (i);            Activityinfo ai = ri.activityinfo;            if (Ai.applicationInfo.flags & applicationinfo.flag_external_storage)! = 0) {continue; } if (Pkgname.equals (Ai.packagename)) {componentname component = new ComponentName (Ai.packagena                Me, ai.name);                Provider p = lookupproviderlocked (component); if (p= = null) {if (addproviderlocked (RI)) {keep.add (ai.name);                    }} else {Provider parsed = parseproviderinfoxml (component, RI);                        if (parsed! = null) {Keep.add (ai.name);                        Use the new appwidgetproviderinfo.                        P.info = Parsed.info;                        If It ' s enabled final int M = P.instances.size ();                            if (M > 0) {int[] appwidgetids = Getappwidgetids (p); Reschedule for the new Updateperiodmillis (don ' t worry about handling//it specially if upd Ateperiodmillis didn ' t change because we just sent//an update, and the next one would be updat                            Eperiodmillis from now).                            Cancelbroadcasts (P); RegisterforbroAdcastslocked (P, appwidgetids);                            If it ' s currently showing, call back with the new appwidgetproviderinfo.                                for (int j=0; j<m; J + +) {Appwidgetid id = p.instances.get (j);                                Id.views = null;                                        if (Id.host = null && id.host.callbacks! = null) {try {                                    Id.host.callbacks.providerChanged (Id.appwidgetid, p.info); } catch (RemoteException ex) {//It failed; Remove the callback.                                        No need to prune because//We know the this host was still referenced by this                                        Instance.                                    Id.host.callbacks = null;                   }                                }         }//Now that we have told the host, push out an update.                        Sendupdateintentlocked (P, appwidgetids); }}}}}//Prune the ones we don ' t want to keep N = MI        Nstalledproviders.size ();            for (int i=n-1; i>=0; i--) {Provider p = minstalledproviders.get (i); if (Pkgname.equals (P.info.provider.getpackagename ()) &&!keep.contains (p.info.provider.getclass            Name ())) {removeproviderlocked (I, p); }        }    }

2. User-defined Appwidgetprovider onupdate () receive data. and update the interface via the manager. (below, the official website gives 2 operation, 1 Update Interface 2. Click the widget Action)

public class Exampleappwidgetprovider extends Appwidgetprovider {public void OnUpdate (context context, appwidgetmanage        R Appwidgetmanager, int[] appwidgetids) {final int N = appwidgetids.length;            Perform this loop, procedure for each App Widget, belongs to this provider for (int i=0; i<n; i++) {            int appwidgetid = Appwidgetids[i];            Create an Intent to launch exampleactivity Intent Intent = new Intent (context, exampleactivity.class);            Pendingintent pendingintent = pendingintent.getactivity (context, 0, intent, 0); Get the layout for the App Widget and attach a On-click listener//To the button Remoteviews VI            EWS = new Remoteviews (Context.getpackagename (), r.layout.appwidget_provider_layout);            Views.setonclickpendingintent (R.id.button, pendingintent); Tell the Appwidgetmanager to perform a update on the current app widget Appwidgetmanager.upDateappwidget (Appwidgetid, views); }    }}

--Updating the App Widget from the configuration activity (change the Appwidget interface by configuring options, when Appwidget is created, first enter the activity to determine)

1. Create the activity and configure it in Androidmanifest.xml:

         <activity android:name= "org.lean.ConfigureActivity" >            <intent-filter>                <action android:name = "Android.appwidget.action.APPWIDGET_CONFIGURE"/>            </intent-filter>        </activity>
2. Add attributes in Appwidget's configuration xml:

Android:configure= "Org.lean.ConfigureActivity"

3. Operation in activity,1> modify the remote interface according to the configuration,2> jump back to the selected activity and turn it off select activity and display the Launcher interface

Package Org.lean;import Android.app.activity;import Android.appwidget.appwidgetmanager;import Android.content.intent;import Android.os.bundle;import Android.view.view;import Android.view.View.OnClickListener  Import Android.widget.edittext;import android.widget.remoteviews;/** * * * @author Lean @date: 2014-8-27 */public class Configureactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.configure_view); Findviewbyid (R.id.button1). SetOnClickListener (New Onclicklistener () {@Overridepublic void OnClick (View v) {int appwidgetid=getintent (). Getextras (). GetInt ( APPWIDGETMANAGER.EXTRA_APPWIDGET_ID,APPWIDGETMANAGER.INVALID_APPWIDGET_ID); if (appwidgetid!= APPWIDGETMANAGER.INVALID_APPWIDGET_ID) {//Modify remote interface EditText edittext= (editText) Findviewbyid (R.ID.EDITTEXT1); String Currenetstr=edittext.gettext (). toString (); Remoteviews views=new remoteviews (ConfigureActivity.this.getPackageName (), R.layout.layout_widget); Views.settextviewtext (R.ID.BTN,CURRENETSTR); Appwidgetmanager manager=appwidgetmanager.getinstance (configureactivity.this); Manager.updateappwidget ( Appwidgetid, views);//Return activityintent reintent=new Intent (); Reintent.putextra (appwidgetmanager.extra_appwidget_ Id,appwidgetid); Setresult (result_ok,reintent); Finish ();}});}}


The Appwidget of Android-launcher development (2)

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.