1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.widget;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.MeasureSpec;
import com.android.internal.widget.IRemoteViewsFactory;
/**
* An adapter to a RemoteViewsService which fetches and caches RemoteViews
* to be later inflated as child views.
*/
/** @hide */
public class RemoteViewsAdapter extends BaseAdapter {
private static final String LOG_TAG = "RemoteViewsAdapter";
private Context mContext;
private Intent mIntent;
private RemoteViewsAdapterServiceConnection mServiceConnection;
private RemoteViewsCache mViewCache;
private HandlerThread mWorkerThread;
// items may be interrupted within the normally processed queues
private Handler mWorkerQueue;
private Handler mMainQueue;
// items are never dequeued from the priority queue and must run
private Handler mWorkerPriorityQueue;
private Handler mMainPriorityQueue;
/**
* An interface for the RemoteAdapter to notify other classes when adapters
* are actually connected to/disconnected from their actual services.
*/
public interface RemoteAdapterConnectionCallback {
public void onRemoteAdapterConnected();
public void onRemoteAdapterDisconnected();
}
/**
* The service connection that gets populated when the RemoteViewsService is
* bound.
*/
private class RemoteViewsAdapterServiceConnection implements ServiceConnection {
private boolean mConnected;
private IRemoteViewsFactory mRemoteViewsFactory;
private RemoteAdapterConnectionCallback mCallback;
public RemoteViewsAdapterServiceConnection(RemoteAdapterConnectionCallback callback) {
mCallback = callback;
}
public void onServiceConnected(ComponentName name, IBinder service) {
mRemoteViewsFactory = IRemoteViewsFactory.Stub.asInterface(service);
mConnected = true;
// notifyDataSetChanged should be called first, to ensure that the
// views are not updated twice
notifyDataSetChanged();
// post a new runnable to load the appropriate data, then callback
mWorkerPriorityQueue.post(new Runnable() {
@Override
public void run() {
// we need to get the viewTypeCount specifically, so just get all the
// metadata
mViewCache.requestMetaData();
// post a runnable to call the callback on the main thread
mMainPriorityQueue.post(new Runnable() {
@Override
public void run() {
if (mCallback != null)
mCallback.onRemoteAdapterConnected();
}
});
}
});
// start the background loader
mViewCache.startBackgroundLoader();
}
public void onServiceDisconnected(ComponentName name) {
mRemoteViewsFactory = null;
mConnected = false;
// clear the main/worker queues
mMainQueue.removeMessages(0);
// stop the background loader
mViewCache.stopBackgroundLoader();
if (mCallback != null)
mCallback.onRemoteAdapterDisconnected();
}
public IRemoteViewsFactory getRemoteViewsFactory() {
return mRemoteViewsFactory;
}
public boolean isConnected() {
return mConnected;
}
}
/**
* An internal cache of remote views.
*/
private class RemoteViewsCache {
private RemoteViewsInfo mViewCacheInfo;
private RemoteViewsIndexInfo[] mViewCache;
private int[] mTmpViewCacheLoadIndices;
private LinkedList<Integer> mViewCacheLoadIndices;
private boolean mBackgroundLoaderEnabled;
// if a user loading view is not provided, then we create a temporary one
// for the user using the height of the first view
private RemoteViews mUserLoadingView;
private RemoteViews mFirstView;
private int mFirstViewHeight;
// determines when the current cache window needs to be updated with new
// items (ie. when there is not enough slack)
private int mViewCacheStartPosition;
private int mViewCacheEndPosition;
private int mHalfCacheSize;
private int mCacheSlack;
private final float mCacheSlackPercentage = 0.75f;
/**
* The data structure stored at each index of the cache. Any member
* that is not invalidated persists throughout the lifetime of the cache.
*/
private class RemoteViewsIndexInfo {
FrameLayout flipper;
RemoteViews view;
long itemId;
int typeId;
RemoteViewsIndexInfo() {
invalidate();
}
void set(RemoteViews v, long id) {
view = v;
itemId = id;
if (v != null)
typeId = v.getLayoutId();
else
typeId = 0;
}
void invalidate() {
view = null;
itemId = 0;
typeId = 0;
}
final boolean isValid() {
return (view != null);
}
}
/**
* Remote adapter metadata. Useful for when we have to lock on something
* before updating the metadata.
*/
private class RemoteViewsInfo {
int count;
int viewTypeCount;
boolean hasStableIds;
Map<Integer, Integer> mTypeIdIndexMap;
RemoteViewsInfo() {
count = 0;
// by default there is at least one dummy view type
viewTypeCount = 1;
hasStableIds = true;
mTypeIdIndexMap = new HashMap<Integer, Integer>();
}
}
public RemoteViewsCache(int halfCacheSize) {
mHalfCacheSize = halfCacheSize;
mCacheSlack = Math.round(mCacheSlackPercentage * mHalfCacheSize);
mViewCacheStartPosition = 0;
mViewCacheEndPosition = -1;
mBackgroundLoaderEnabled = false;
// initialize the cache
int cacheSize = 2 * mHalfCacheSize + 1;
mViewCacheInfo = new RemoteViewsInfo();
mViewCache = new RemoteViewsIndexInfo[cacheSize];
for (int i = 0; i < mViewCache.length; ++i) {
mViewCache[i] = new RemoteViewsIndexInfo();
}
mTmpViewCacheLoadIndices = new int[cacheSize];
mViewCacheLoadIndices = new LinkedList<Integer>();
}
private final boolean contains(int position) {
return (mViewCacheStartPosition <= position) && (position <= mViewCacheEndPosition);
}
private final boolean containsAndIsValid(int position) {
if (contains(position)) {
RemoteViewsIndexInfo indexInfo = mViewCache[getCacheIndex(position)];
if (indexInfo.isValid()) {
return true;
}
}
return false;
}
private final int getCacheIndex(int position) {
// take the modulo of the position
return (mViewCache.length + (position % mViewCache.length)) % mViewCache.length;
}
public void requestMetaData() {
if (mServiceConnection.isConnected()) {
try {
IRemoteViewsFactory factory = mServiceConnection.getRemoteViewsFactory();
// get the properties/first view (so that we can use it to
// measure our dummy views)
boolean hasStableIds = factory.hasStableIds();
int viewTypeCount = factory.getViewTypeCount();
int count = factory.getCount();
RemoteViews loadingView = factory.getLoadingView();
RemoteViews firstView = null;
if ((count > 0) && (loadingView == null)) {
firstView = factory.getViewAt(0);
}
synchronized (mViewCacheInfo) {
RemoteViewsInfo info = mViewCacheInfo;
info.hasStableIds = hasStableIds;
info.viewTypeCount = viewTypeCount + 1;
info.count = count;
mUserLoadingView = loadingView;
if (firstView != null) {
mFirstView = firstView;
mFirstViewHeight = -1;
}
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
protected void updateRemoteViewsInfo(int position) {
if (mServiceConnection.isConnected()) {
IRemoteViewsFactory factory = mServiceConnection.getRemoteViewsFactory();
// load the item information
RemoteViews remoteView = null;
long itemId = 0;
try {
remoteView = factory.getViewAt(position);
itemId = factory.getItemId(position);
} catch (RemoteException e) {
e.printStackTrace();
}
synchronized (mViewCache) {
// skip if the window has moved
if (position < mViewCacheStartPosition || position > mViewCacheEndPosition)
return;
final int positionIndex = position;
final int cacheIndex = getCacheIndex(position);
mViewCache[cacheIndex].set(remoteView, itemId);
// notify the main thread when done loading
// flush pending updates
mMainQueue.post(new Runnable() {
@Override
public void run() {
// swap the loader view for this view
synchronized (mViewCache) {
if (containsAndIsValid(positionIndex)) {
RemoteViewsIndexInfo indexInfo = mViewCache[cacheIndex];
FrameLayout flipper = indexInfo.flipper;
// update the flipper
flipper.getChildAt(0).setVisibility(View.GONE);
boolean addNewView = true;
if (flipper.getChildCount() > 1) {
View v = flipper.getChildAt(1);
int typeId = ((Integer) v.getTag()).intValue();
if (typeId == indexInfo.typeId) {
// we can reapply since it is the same type
indexInfo.view.reapply(mContext, v);
v.setVisibility(View.VISIBLE);
if (v.getAnimation() != null)
v.buildDrawingCache();
addNewView = false;
} else {
flipper.removeViewAt(1);
}
}
if (addNewView) {
View v = indexInfo.view.apply(mContext, flipper);
v.setTag(new Integer(indexInfo.typeId));
flipper.addView(v);
}
}
}
}
});
}
}
}
private RemoteViewsIndexInfo requestCachedIndexInfo(final int position) {
int indicesToLoadCount = 0;
synchronized (mViewCache) {
if (containsAndIsValid(position)) {
// return the info if it exists in the window and is loaded
return mViewCache[getCacheIndex(position)];
}
// if necessary update the window and load the new information
int centerPosition = (mViewCacheEndPosition + mViewCacheStartPosition) / 2;
if ((mViewCacheEndPosition <= mViewCacheStartPosition) || (Math.abs(position - centerPosition) > mCacheSlack)) {
int newStartPosition = position - mHalfCacheSize;
int newEndPosition = position + mHalfCacheSize;
int frameSize = mHalfCacheSize / 4;
int frameCount = (int) Math.ceil(mViewCache.length / (float) frameSize);
// prune/add before the current start position
int effectiveStart = Math.max(newStartPosition, 0);
int effectiveEnd = Math.min(newEndPosition, getCount() - 1);
// invalidate items in the queue
int overlapStart = Math.max(mViewCacheStartPosition, effectiveStart);
int overlapEnd = Math.min(Math.max(mViewCacheStartPosition, mViewCacheEndPosition), effectiveEnd);
for (int i = 0; i < (frameSize * frameCount); ++i) {
int index = newStartPosition + ((i % frameSize) * frameCount + (i / frameSize));
if (index <= newEndPosition) {
if ((overlapStart <= index) && (index <= overlapEnd)) {
// load the stuff in the middle that has not already
// been loaded
if (!mViewCache[getCacheIndex(index)].isValid()) {
mTmpViewCacheLoadIndices[indicesToLoadCount++] = index;
}
} else if ((effectiveStart <= index) && (index <= effectiveEnd)) {
// invalidate and load all new effective items
mViewCache[getCacheIndex(index)].invalidate();
mTmpViewCacheLoadIndices[indicesToLoadCount++] = index;
} else {
// invalidate all other cache indices (outside the effective start/end)
// but don't load
mViewCache[getCacheIndex(index)].invalidate();
}
}
}
mViewCacheStartPosition = newStartPosition;
mViewCacheEndPosition = newEndPosition;
}
}
// post items to be loaded
int length = 0;
synchronized (mViewCacheInfo) {
length = mViewCacheInfo.count;
}
if (indicesToLoadCount > 0) {
synchronized (mViewCacheLoadIndices) {
mViewCacheLoadIndices.clear();
for (int i = 0; i < indicesToLoadCount; ++i) {
final int index = mTmpViewCacheLoadIndices[i];
if (0 <= index && index < length) {
mViewCacheLoadIndices.addLast(index);
}
}
}
}
// return null so that a dummy view can be retrieved
return null;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (mServiceConnection.isConnected()) {
// create the flipper views if necessary (we have to do this now
// for all the flippers while we have the reference to the parent)
initializeLoadingViews(parent);
// request the item from the cache (queueing it to load if not
// in the cache already)
RemoteViewsIndexInfo indexInfo = requestCachedIndexInfo(position);
// update the flipper appropriately
synchronized (mViewCache) {
int cacheIndex = getCacheIndex(position);
FrameLayout flipper = mViewCache[cacheIndex].flipper;
flipper.setVisibility(View.VISIBLE);
flipper.setAlpha(1.0f);
if (indexInfo == null) {
// hide the item view and show the loading view
flipper.getChildAt(0).setVisibility(View.VISIBLE);
for (int i = 1; i < flipper.getChildCount(); ++i) {
flipper.getChildAt(i).setVisibility(View.GONE);
}
} else {
// hide the loading view and show the item view
for (int i = 0; i < flipper.getChildCount() - 1; ++i) {
flipper.getChildAt(i).setVisibility(View.GONE);
}
flipper.getChildAt(flipper.getChildCount() - 1).setVisibility(View.VISIBLE);
}
return flipper;
}
}
return new View(mContext);
}
private void initializeLoadingViews(ViewGroup parent) {
// ensure that the cache has the appropriate initial flipper
synchronized (mViewCache) {
if (mViewCache[0].flipper == null) {
for (int i = 0; i < mViewCache.length; ++i) {
FrameLayout flipper = new FrameLayout(mContext);
if (mUserLoadingView != null) {
// use the user-specified loading view
flipper.addView(mUserLoadingView.apply(mContext, parent));
} else {
// calculate the original size of the first row for the loader view
synchronized (mViewCacheInfo) {
if (mFirstViewHeight < 0) {
View firstView = mFirstView.apply(mContext, parent);
firstView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
mFirstViewHeight = firstView.getMeasuredHeight();
}
}
// construct a new loader and add it to the flipper as the fallback
// default view
TextView textView = new TextView(mContext);
textView.setText("Loading...");
textView.setHeight(mFirstViewHeight);
textView.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
textView.setTextSize(18.0f);
textView.setTextColor(Color.argb(96, 255, 255, 255));
textView.setShadowLayer(2.0f, 0.0f, 1.0f, Color.BLACK);
flipper.addView(textView);
}
mViewCache[i].flipper = flipper;
}
}
}
}
public void startBackgroundLoader() {
// initialize the worker runnable
mBackgroundLoaderEnabled = true;
mWorkerQueue.post(new Runnable() {
@Override
public void run() {
while (mBackgroundLoaderEnabled) {
int index = -1;
synchronized (mViewCacheLoadIndices) {
if (!mViewCacheLoadIndices.isEmpty()) {
index = mViewCacheLoadIndices.removeFirst();
}
}
if (index < 0) {
// there were no items to load, so sleep for a bit
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
// otherwise, try and load the item
updateRemoteViewsInfo(index);
// sleep for a bit to allow things to catch up after the load
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
}
public void stopBackgroundLoader() {
// clear the items to be loaded
mBackgroundLoaderEnabled = false;
synchronized (mViewCacheLoadIndices) {
mViewCacheLoadIndices.clear();
}
}
public long getItemId(int position) {
synchronized (mViewCache) {
if (containsAndIsValid(position)) {
return mViewCache[getCacheIndex(position)].itemId;
}
}
return 0;
}
public int getItemViewType(int position) {
// synchronize to ensure that the type id/index map is updated synchronously
synchronized (mViewCache) {
if (containsAndIsValid(position)) {
int viewId = mViewCache[getCacheIndex(position)].typeId;
Map<Integer, Integer> typeMap = mViewCacheInfo.mTypeIdIndexMap;
// we +1 because the default dummy view get view type 0
if (typeMap.containsKey(viewId)) {
return typeMap.get(viewId);
} else {
int newIndex = typeMap.size() + 1;
typeMap.put(viewId, newIndex);
return newIndex;
}
}
}
// return the type of the default item
return 0;
}
public int getCount() {
synchronized (mViewCacheInfo) {
return mViewCacheInfo.count;
}
}
public int getViewTypeCount() {
synchronized (mViewCacheInfo) {
return mViewCacheInfo.viewTypeCount;
}
}
public boolean hasStableIds() {
synchronized (mViewCacheInfo) {
return mViewCacheInfo.hasStableIds;
}
}
public void flushCache() {
// clear the items to be loaded
synchronized (mViewCacheLoadIndices) {
mViewCacheLoadIndices.clear();
}
synchronized (mViewCache) {
// flush the internal cache and invalidate the adapter for future loads
mMainQueue.removeMessages(0);
for (int i = 0; i < mViewCache.length; ++i) {
mViewCache[i].invalidate();
}
mViewCacheStartPosition = 0;
mViewCacheEndPosition = -1;
}
}
}
public RemoteViewsAdapter(Context context, Intent intent, RemoteAdapterConnectionCallback callback) {
mContext = context;
mIntent = intent;
// initialize the worker thread
mWorkerThread = new HandlerThread("RemoteViewsCache-loader");
mWorkerThread.start();
mWorkerQueue = new Handler(mWorkerThread.getLooper());
mWorkerPriorityQueue = new Handler(mWorkerThread.getLooper());
mMainQueue = new Handler(Looper.myLooper());
mMainPriorityQueue = new Handler(Looper.myLooper());
// initialize the cache and the service connection on startup
mViewCache = new RemoteViewsCache(25);
mServiceConnection = new RemoteViewsAdapterServiceConnection(callback);
requestBindService();
}
protected void finalize() throws Throwable {
// remember to unbind from the service when finalizing
unbindService();
}
public int getCount() {
requestBindService();
return mViewCache.getCount();
}
public Object getItem(int position) {
// disallow arbitrary object to be associated with an item for the time being
return null;
}
public long getItemId(int position) {
requestBindService();
return mViewCache.getItemId(position);
}
public int getItemViewType(int position) {
requestBindService();
return mViewCache.getItemViewType(position);
}
public View getView(int position, View convertView, ViewGroup parent) {
requestBindService();
return mViewCache.getView(position, convertView, parent);
}
public int getViewTypeCount() {
requestBindService();
return mViewCache.getViewTypeCount();
}
public boolean hasStableIds() {
requestBindService();
return mViewCache.hasStableIds();
}
public boolean isEmpty() {
return getCount() <= 0;
}
public void notifyDataSetChanged() {
// flush the cache so that we can reload new items from the service
mViewCache.flushCache();
super.notifyDataSetChanged();
}
private boolean requestBindService() {
// try binding the service (which will start it if it's not already running)
if (!mServiceConnection.isConnected()) {
mContext.bindService(mIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
}
return mServiceConnection.isConnected();
}
private void unbindService() {
if (mServiceConnection.isConnected()) {
mContext.unbindService(mServiceConnection);
}
}
}
|