AppWidget源码分析(1)---接口类
来源:互联网 发布:360优化 大师官网下载 编辑:程序博客网 时间:2024/04/27 09:02
最近项目中接触到AppWidget,相对来说这部分比较简单,所以趁着空余时间详细阅读了AppWidget的源码。这篇文章主要是从源码上分析AppWidget中API类的相关原理,相关类的简单功能介绍和实现原理。关于使用,建议看指导文档。
简述
AppWidget相关的API类(供我们应用开发者使用的类)主要有:
AppWidgetProvider:继承这个类,来提供Appwidget。
AppWidgetManager:提供了AppWidget的管理接口,比如更新,绑定AppWidget id,根据Component获取AppWidget id等等。
RemoteView:能够跨进程更新的View。
AppWidgetHost:与AppWidgt 服务交互的类,获取App widget,显示出来
AppwidgetHostView:实际上显示出来的View
他们之间的关系简略来讲如下:
AppWidget Service 是一些类的集合,是AppWidget的核心服务,在之后的文章会介绍,这篇就不介绍了。下面详细介绍每个类的功能以及实现原理。
AppWidgetProvider
这是我们在建立AppWidget的时候,需要去实现的类,它有几个重要的方法:
public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) // 当Widget的布局到新的大小的时候会被调用public void onDeleted(Context context, int[] appWidgetIds) // 当某个Widget被移除的时候回调public void onDisabled(Context context) // 当最后一个Widget被移除的时候回调public void onEnabled(Context context) // 当第一个Widget被添加的时候回调public void onRestored(Context context, int[] oldWidgetIds, int[] newWidgetIds) // 当Widget从缓存的Widget恢复时public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) //当Widget需要被提供RemoteView的时候,每次添加Widget的时候会调用public void onReceive(Context context, Intent intent) // 后面介绍
这几个方法是我们在继承AppWidgetProvider的时候,可以根据自己的需要来实现的方法。注释里面是每个方法被回调的时机。
实际上如果去查看AppWidgetProvider的源码,你会发现AppWidgetProvider是继承自BroadcastReceiver的,也就是说它是一种广播。所以它也有一个onReceive方法,这个方法我前面特意没有说明什么时候调用,其实就是收到广播的时候回调。看看onReceive方法的实现,你会发现前面的那几个方法都是在onReceiver中调用的,每一种方法都对应着一种广播Action:
public void onReceive(Context context, Intent intent) { // Protect against rogue update broadcasts (not really a security issue, // just filter bad broacasts out so subclasses are less likely to crash). String action = intent.getAction(); if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { Bundle extras = intent.getExtras(); if (extras != null) { int[] appWidgetIds = extras.getIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS); if (appWidgetIds != null && appWidgetIds.length > 0) { this.onUpdate(context, AppWidgetManager.getInstance(context), appWidgetIds); } } } else if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) { Bundle extras = intent.getExtras(); if (extras != null && extras.containsKey(AppWidgetManager.EXTRA_APPWIDGET_ID)) { final int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID); this.onDeleted(context, new int[] { appWidgetId }); } } else if (AppWidgetManager.ACTION_APPWIDGET_OPTIONS_CHANGED.equals(action)) { Bundle extras = intent.getExtras(); if (extras != null && extras.containsKey(AppWidgetManager.EXTRA_APPWIDGET_ID) && extras.containsKey(AppWidgetManager.EXTRA_APPWIDGET_OPTIONS)) { int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID); Bundle widgetExtras = extras.getBundle(AppWidgetManager.EXTRA_APPWIDGET_OPTIONS); this.onAppWidgetOptionsChanged(context, AppWidgetManager.getInstance(context), appWidgetId, widgetExtras); } } else if (AppWidgetManager.ACTION_APPWIDGET_ENABLED.equals(action)) { this.onEnabled(context); } else if (AppWidgetManager.ACTION_APPWIDGET_DISABLED.equals(action)) { this.onDisabled(context); } else if (AppWidgetManager.ACTION_APPWIDGET_RESTORED.equals(action)) { Bundle extras = intent.getExtras(); if (extras != null) { int[] oldIds = extras.getIntArray(AppWidgetManager.EXTRA_APPWIDGET_OLD_IDS); int[] newIds = extras.getIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS); if (oldIds != null && oldIds.length > 0) { this.onRestored(context, oldIds, newIds); this.onUpdate(context, AppWidgetManager.getInstance(context), newIds); } } }}
AppWidgetProvider是一个BroadcastReceiver,所以它的onUpdate, onEnabled
等方法每次被调用前,都会调用onReceive方法。我们继承AppWidgetProvider,也可以重载onReceiver方法,修改onUpdate
等方法被调用的时机,当然并不推荐这么做,破坏接口的语义会非常危险。另外一方面它是一个BroadcastReceiver,所以它就具备BroadcastReceiver的各种特性(需要说明的是AppWidgetProvider要在manifest文件中静态注册,因为系统在安装apk时需要知道应用有哪些方法桌面Widget),它能够注册自定义的ACTION,每次执行的时候是会创建一个新的AppWidgetProvider实例,Context不能绑定服务,执行时间不能超过10秒等等。
AppWidgetProvider是一个BroadcastReceiver,明白这一点其实也就是理解AppWidget实现原理了。在onUpdate中提供了AppWidgetManager参数,这个AppWidgetMananger又是什么呢?下面来介绍一下。
AppWidgetManager
名如其义,AppWidgetManager你可以理解为AppWidget的管理接口(实际上它只提供了管理AppWidget的部分接口,后面的文章会介绍真正管理AppWidget的接口,也就是AppWidget 的client)。我们可以用AppWidgetManager来更新AppWidget的内容,给AppWidget绑定id。AppWidgetManager是在实现AppWidgetProvider的时候,经常会用到的类,可以用AppWidgetManager.updateAppWidget
来更新AppWidget。如果是有AdapterView的AppWidget,可以用AppWidgetManager.notifyAppWidgetViewDataChanged
来通知Adapter的变化,用partiallyUpdateAppWidget
部分更新Widget。这几个方法是经常在AppWidgetProvider的onUpdate
方法中使用的。这几个方法的原型如下:
public void notifyAppWidgetViewDataChanged(int appWidgetId, int viewId)public void partiallyUpdateAppWidget(int appWidgetId, RemoteViews views)public void updateAppWidget(int[] appWidgetIds, RemoteViews views)
另外可以通过getAppWidgetIds
获取AppWidgetProvider组件对应的AppWidget的Id数组,我们经常通过这个方法获取所有的id,然后来更新所有的跟AppWidgetProvider相关的AppWidget。
public int[] getAppWidgetIds(ComponentName provider)
另外还有bindAppWidgetIdIfAllowed
方法和getInstalledProviders
,这两个方法主要是在Launcher应用当中使用,分配AppWidget的id,然后用bindAppWidgetIdIfAllowed
绑定AppWidgetProvider与id。用getInstalledProviders
方法获取已经插入的AppWidgetProvider,可以用来供用户选择添加到桌面。
public boolean bindAppWidgetIdIfAllowed(int appWidgetId, ComponentName provider, Bundle options)public List<AppWidgetProviderInfo> getInstalledProviders()
关于launcher可以参考aosp的源码:http://arnab.ch/blog/2013/08/how-to-write-custom-launcher-app-in-android/。我们也可以自己开发launcher应用。
RemoteView
RemoteView顾名思义就是指远程View,通过本地进程修改RemoteView,能够使这些修改通过RemoteView为载体传递到远程进程。RemoteView不仅仅在AppWidget中有使用,Notification中也是使用了RemoteView。下面简单介绍一下RemoteView的实现原理。
RemoteView继承自Parcelable,所以RemoteView本身就是可以跨进程传递的。RemoteView有个内部类叫做Action,它也是继承自Parcelable,对于不同的操作,RemoteView内部实现了不同的Action。
比如点击事件,RemoteView内部有一个SetOnClickPendingIntent,它也是继承自Action,设置点击事件就是将点击事件保存在这里面,把点击事件作为一个Action。可以看看它的源码:
private class SetOnClickPendingIntent extends Action { public SetOnClickPendingIntent(int id, PendingIntent pendingIntent) { this.viewId = id; this.pendingIntent = pendingIntent; } public SetOnClickPendingIntent(Parcel parcel) { viewId = parcel.readInt(); // We check a flag to determine if the parcel contains a PendingIntent. if (parcel.readInt() != 0) { pendingIntent = PendingIntent.readPendingIntentOrNullFromParcel(parcel); } } public void writeToParcel(Parcel dest, int flags) { dest.writeInt(TAG); dest.writeInt(viewId); // We use a flag to indicate whether the parcel contains a valid object. dest.writeInt(pendingIntent != null ? 1 : 0); if (pendingIntent != null) { pendingIntent.writeToParcel(dest, 0 /* no flags */); } } @Override public void apply(View root, ViewGroup rootParent, final OnClickHandler handler) { final View target = root.findViewById(viewId); if (target == null) return; // If the view is an AdapterView, setting a PendingIntent on click doesn't make much // sense, do they mean to set a PendingIntent template for the AdapterView's children? if (mIsWidgetCollectionChild) { Log.w(LOG_TAG, "Cannot setOnClickPendingIntent for collection item " + "(id: " + viewId + ")"); ApplicationInfo appInfo = root.getContext().getApplicationInfo(); // We let this slide for HC and ICS so as to not break compatibility. It should have // been disabled from the outset, but was left open by accident. if (appInfo != null && appInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { return; } } // If the pendingIntent is null, we clear the onClickListener OnClickListener listener = null; if (pendingIntent != null) { listener = new OnClickListener() { public void onClick(View v) { // Find target view location in screen coordinates and // fill into PendingIntent before sending. final Rect rect = getSourceBounds(v); final Intent intent = new Intent(); intent.setSourceBounds(rect); handler.onClickHandler(v, pendingIntent, intent); } }; } target.setOnClickListener(listener); }...}
其中以Parcel为参数的构造函数相当于是从Parcel当中读取内容,而writeToParcel是将Action写入到Parcel。这两个函数是用来传递Action用的。而apply方法则是将Action解析出来,设置监听(这种监听是远程监听,在onClick方法里面发送一个PendingIntent),具体实现在RemoteView的OnClickHandler中。其他的Action也是类似的。关于Parcel实现原理可以借鉴我之前写的两篇关于Bitmap传输的文章: Android4.0 Bitmap Parcel传输源码分析,Android6.0 Bitmap存储以及Parcel传输源码分析
RemoteView里面有一个mActions变量,是Action的列表。通过Parcel传递RemoteView的时候,RemoteView会将mActions里面的内容都写入到Parcel中。在readParcel的时候,使用Action的带Parcel参数的构造函数从Parcel里面读取Action,进行设置。Action其实就是一种模板方法模式。RemoteView很多设置是跟普通的View不一样的,RemoteView是一个能够跨进程设置相关内容的,如果需要设置监听函数之类的,只能设置PendingIntent。可以看看RemoteView里面的CREATOR和RemoteView对应的构造方法:
/*** Parcelable.Creator that instantiates RemoteViews objects*/public static final Parcelable.Creator<RemoteViews> CREATOR = new Parcelable.Creator<RemoteViews>() { public RemoteViews createFromParcel(Parcel parcel) { return new RemoteViews(parcel); } public RemoteViews[] newArray(int size) { return new RemoteViews[size]; }};...public RemoteViews(Parcel parcel) { this(parcel, null);}private RemoteViews(Parcel parcel, BitmapCache bitmapCache) {//实际上在构造函数中读取Parcel的内容,重新创建一个mActions int mode = parcel.readInt(); // We only store a bitmap cache in the root of the RemoteViews. if (bitmapCache == null) { mBitmapCache = new BitmapCache(parcel); } else { setBitmapCache(bitmapCache); setNotRoot(); } if (mode == MODE_NORMAL) { mApplication = parcel.readParcelable(null); mLayoutId = parcel.readInt(); mIsWidgetCollectionChild = parcel.readInt() == 1; int count = parcel.readInt(); if (count > 0) { mActions = new ArrayList<Action>(count); for (int i=0; i<count; i++) { int tag = parcel.readInt(); switch (tag) { case SetOnClickPendingIntent.TAG: mActions.add(new SetOnClickPendingIntent(parcel)); break; case SetDrawableParameters.TAG: mActions.add(new SetDrawableParameters(parcel)); break; ... default: throw new ActionException("Tag " + tag + " not found"); } } } } else { // MODE_HAS_LANDSCAPE_AND_PORTRAIT mLandscape = new RemoteViews(parcel, mBitmapCache); mPortrait = new RemoteViews(parcel, mBitmapCache); mApplication = mPortrait.mApplication; mLayoutId = mPortrait.getLayoutId(); } // setup the memory usage statistics mMemoryUsageCounter = new MemoryUsageCounter(); recalculateMemoryUsage();}
最后调用RemoteView的apply方法就在远程进程设置了相关内容了。我们AppWidget的远程进程是Launcher应用所在的进程。由AppWidgetHost管理这些。
AppWidgetHost
这个类是Android提供的供应用与AppWidget service交互的类,我们的AppWidgetProvider提供了Widget,而AppWidgetHost则是读取Widget,将它显示出来。一般在home screen中使用,也就是我们的桌面,Launcher。与之相关的还有个AppWidgetHostView,由AppWidgetHost创建,它与AppWidgetProvider对应。可以看一下AppWidgetHost的createView方法:
public final AppWidgetHostView createView(Context context, int appWidgetId, AppWidgetProviderInfo appWidget) { AppWidgetHostView view = onCreateView(context, appWidgetId, appWidget); view.setOnClickHandler(mOnClickHandler); view.setAppWidget(appWidgetId, appWidget); synchronized (mViews) { mViews.put(appWidgetId, view); } RemoteViews views; try { views = sService.getAppWidgetViews(mContextOpPackageName, appWidgetId); } catch (RemoteException e) { throw new RuntimeException("system server dead?", e); } view.updateAppWidget(views); return view;}
这个主要是在launcher应用使用,就不详细介绍了。
总结
这一篇主要是介绍AppWidget相关的一些类,分析里面的源码功能,以及实现方式。通过深入了解它的实现方式才能够更好地使用它,分析遇到的问题。下一篇将从源码角度上介绍一些方法的处理流程。
- AppWidget源码分析(1)---接口类
- AppWidget源码分析(2)---updateAppWidget过程分析.md
- Map接口源码分析
- Map接口源码分析
- launcher appwidget过程分析
- AppWidget命令分析
- java Map接口源码分析
- 源码分析-java-collection接口
- AppWidget绑定失败问题分析
- MyBatis 源码分析——SqlSession接口和Executor类
- appwidget应用小节1
- Appwidget
- AppWidget
- AppWidget
- appwidget
- Appwidget
- AppWidget
- AppWidget
- 使用SQL语句建立特殊需求的序列号
- easyui window 和dialog form提交 空值
- Gradle 自定义Task 打Jar包
- 04全栈工程师--2016-08-09
- CodeIgniter框架 CI PHP
- AppWidget源码分析(1)---接口类
- 交换两个数的值多种解法
- The resource identified by this request is only capable of generating responses with characteristics
- Android学习笔记(一):AIDL
- Android盒子功能测试
- redis之lpush、rpush、lset、lrem
- oracle的查询数据表(一)
- Java中如何使用转义转义字符?
- java挑战高并发 之(11):生产者—消费者模型(含代码)