现在的位置: 首页 > 综合 > 正文

android开发步步为营之14:App Widgets

2017年10月06日 ⁄ 综合 ⁄ 共 6383字 ⁄ 字号 评论关闭

什么是appwidget呢?中文名称是应用小插件,截个图就可以直观的认识了
长时间点击手机桌面,出现下面的页面
 
点击widgets后出现目前存在的widgets
 
我们选择一个Music看看什么效果
 
    我们发现我们的手机桌面出现了这个音乐播放器。这个就是widget,好了,我们对widget已经有了一个直观的认识,现在我们先学习一些理论知识,然后再做个试验。
        我们看到widget这个小玩意的作用是什么呢?就相当应用的快捷方式,但是它的功能比快捷方式多的多,快捷方式只是提供了一个跳转到应用的入口。但是widget就相当一个简化版的应用,比如这个Music widget,提供了选择音乐和播放音乐的简单功能。可以看出它提供了方便,从商业的角度来看叫做抢占用户的桌面。
介绍最关键的一个概念:
Usingthe AppWidgetProvider Class

You must declare your AppWidgetProvider class implementation as abroadcast receiver using the <receiver> element in the AndroidManifest (see Declaring an App Widget in theManifest above).

TheAppWidgetProviderclass extends BroadcastReceiver as a convenience class to handle the App Widgetbroadcasts. The AppWidgetProvider receives only the event broadcasts that arerelevant to the App Widget, such as when the App Widget is updated, deleted,enabled,
and disabled. When these broadcast events occur, the AppWidgetProviderreceives the following method calls:

onUpdate()
This is called to updatethe App Widget at intervals defined by the updatePeriodMillisattribute in the AppWidgetProviderInfo (see Adding theAppWidgetProviderInfo Metadata above). This method is also calledwhen the user adds the App Widget, so it should perform
the essential setup,such as define event handlers for Views and start a temporary Service,if necessary. However, if you have declared a configuration Activity, this method is not called when the user adds the App Widget, but is called for the subsequentupdates.
It is the responsibility of the configuration Activity to perform thefirst update when configuration is done. (See Creating an App WidgetConfiguration Activity below.)

onDeleted(Context, int[])
This is called every timean App Widget is deleted from the App Widget host.

onEnabled(Context)
This is called when aninstance the App Widget is created for the first time. For example, if the useradds two instances of your App Widget, this is only called the first time. Ifyou need to open a new database or perform other setup that only needs to occuronce
for all App Widget instances, then this is a good place to do it.

onDisabled(Context)
This is called when thelast instance of your App Widget is deleted from the App Widget host. This iswhere you should clean up any work done in onEnabled(Context),such as delete a temporary database.

onReceive(Context, Intent)
This is called for everybroadcast and before each of the above callback methods. You normally don'tneed to implement this method because the default AppWidgetProviderimplementation filters all App Widget broadcasts and calls the above methods asappropriate.

    简单说明一下,要创建AppWidget就必须创建这个类,其实它继承至BroadcastReceiver,所以一个AppWidget其实就是一个广播接收器,但是功能更强大,生命周期函数有onUpdate() 、onDeleted(Context, int[])
、onEnabled(Context) 、onDisabled(Context) 、onReceive(Context, Intent)
 
 
onUpdate()每次创建的时候就会触发,还有更新周期到了就会触发,或者另外定义一个configuration Activity,那么第一次的onUpdate就会在这个configuration Activity中执行,但是每次更新周期到了仍旧会执行这个方法。
onDeleted(Context, int[])每个appwidget删除的时候被触发
onEnabled(Context)创建第一时触发,比如上面那个Music AppWiget连续创建两个,创建第一个时才会触发。
onDisabled(Context)最后一个appwidget被删除时才会被触发。
onReceive(Context, Intent) 根据xml文件里面配置过滤的intentfilter,发现是需要的广播就会被触发。
      
        好了,开始我们的实验,假设我们开发一个像新浪微博那个AppWidget,这个widget左边包含一个写微博的图片按钮,右边是最热门的一条微博。
 
        第一步、创建AppWidgetProvider WeiboAppWidgetProvider.java
        /**
 *
 */
packagecom.figo.helloworld;
 
importjava.util.ArrayList;
importjava.util.List;
 
importandroid.app.PendingIntent;
importandroid.appwidget.AppWidgetManager;
importandroid.appwidget.AppWidgetProvider;
importandroid.content.Context;
importandroid.content.Intent;
importandroid.os.IBinder;
importandroid.widget.RemoteViews;
 
/**
 * 处理AppWidget生命周期事件,与Activity相似
 *
 * @author zzf 20120630
 *
 */
publicclass WeiboAppWidgetProvider extends AppWidgetProvider {
 
    @Override
    public void onReceive(Context context,Intent intent) {
       // TODO Auto-generated method stub
       super.onReceive(context, intent);
    }
 
    @Override
    public void onUpdate(Context context,AppWidgetManager appWidgetManager,
           int[] appWidgetIds) {
       // TODO Auto-generated method stub
       super.onUpdate(context, appWidgetManager,appWidgetIds);
       // int length = appWidgetIds.length;
       // for (int a = 0; a < length; a++) {
       // 可以设置不同intent,这里点击图片按钮后,跳转到写微博的activity
       Intent intent = new Intent(context,WriteWeiboActivity.class);
       PendingIntent pendingIntent =PendingIntent.getActivity(context, 0,
              intent, 0);
       RemoteViews remoteViews = newRemoteViews(context.getPackageName(),
              R.layout.weibo_appwidget);
       remoteViews.setOnClickPendingIntent(R.id.imgWriteWeibo,pendingIntent);
       remoteViews.setTextViewText(R.id.tvContent,"今天好开心~");
       appWidgetManager.updateAppWidget(appWidgetIds,remoteViews);
       // appWidgetManager.updateAppWidget(appWidgetIds[a],remoteViews);
       // }
 
    }
 
 
    @Override
    public void onDeleted(Context context, int[]appWidgetIds) {
       // TODO Auto-generated method stub
       super.onDeleted(context, appWidgetIds);
    }
 
    @Override
    public void onEnabled(Context context) {
       // TODO Auto-generated method stub
       super.onEnabled(context);
    }
 
    @Override
    public void onDisabled(Context context) {
       // TODO Auto-generated method stub
       super.onDisabled(context);
    }
 
    @Override
    public IBinder peekService(Context myContext,Intent service) {
       // TODO Auto-generated method stub
       return super.peekService(myContext,service);
    }
 
}
第二步、创建设置这个widget相关属性的xml文件weibo_appwidget_info.xml
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="290dp"
android:minHeight="70dp"
android:updatePeriodMillis="3600000"
android:initialLayout="@layout/weibo_appwidget"
>
</appwidget-provider>
 
第三步、设置这个widget的页面布局xml文件weibo_appwidget.xml
<?xml version="1.0"encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <ImageButton android:src="@drawable/icon"android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true"android:layout_alignParentLeft="true"android:id="@+id/imgWriteWeibo"></ImageButton>
    <TextView android:layout_width="wrap_content"android:text="TextView" android:layout_height="wrap_content"android:layout_centerVertical="true"android:layout_toRightOf="@+id/imgWriteWeibo"android:layout_marginLeft="32dp"android:id="@+id/tvContent"></TextView>
</RelativeLayout>
第四步、AndroidManifest.xml注册我们appwidget
    <receiver android:name="WeiboAppWidgetProvider">
           <intent-filter>
              <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
           </intent-filter>
           <meta-data android:name="android.appwidget.provider"android:resource="@xml/weibo_appwidget_info"/>
    </receiver>
第五步、运行效果
 
点击左边的发布按钮后
 

抱歉!评论已关闭.