/
HipstaActivity.java
569 lines (455 loc) · 17.7 KB
/
HipstaActivity.java
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
package com.squeed.chromecast.hipstacaster;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.MediaRouteActionProvider;
import android.support.v7.media.MediaRouteSelector;
import android.support.v7.media.MediaRouter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.cast.ApplicationChannel;
import com.google.cast.ApplicationMetadata;
import com.google.cast.ApplicationSession;
import com.google.cast.CastContext;
import com.google.cast.CastDevice;
import com.google.cast.MediaRouteAdapter;
import com.google.cast.MediaRouteHelper;
import com.google.cast.MediaRouteStateChangeListener;
import com.google.cast.SessionError;
import com.squeed.chromecast.hipstacaster.dto.Photo;
import com.squeed.chromecast.hipstacaster.grid.BitmapImageItem;
import com.squeed.chromecast.hipstacaster.grid.GridViewAdapter;
import com.squeed.chromecast.hipstacaster.grid.ImageItem;
import com.squeed.chromecast.hipstacaster.img.Callback;
import com.squeed.chromecast.hipstacaster.img.DrawableManager;
import com.squeed.chromecast.hipstacaster.rest.LoadImageListTask;
/**
* Demonstrative Activity for the HipstaCaster Android client. Somewhat based on the Android demo tic-tac-toe game from
* https://github.com/googlecast/cast-android-tictactoe
*
* @author Erik
*
*/
public class HipstaActivity extends ActionBarActivity implements MediaRouteAdapter {
private static final String DEFAULT_SEARCH_TAG = "sarek";
private static final String TAG = HipstaActivity.class.getSimpleName();
private static final com.google.cast.Logger sLog = new com.google.cast.Logger(TAG, true);
private static final String APP_NAME = "fc91668a-cf4b-4a18-9611-f2c120d0bf07_1";
private static final String PROTOCOL = "com.squeed.chromecast.hipstacaster";
static final int IMAGES_PER_FETCH = 20;
private ApplicationSession mSession;
private SessionListener mSessionListener;
private CustomHipstaCasterStream mMessageStream;
private GridView gridView;
private GridViewAdapter customGridAdapter;
private TextView mInfoView;
private ProgressBar spinner;
private SharedPreferences preferences;
private CastContext mCastContext;
private CastDevice mSelectedDevice;
private MediaRouter mMediaRouter;
private MediaRouteSelector mMediaRouteSelector;
private MediaRouter.Callback mMediaRouterCallback;
private ArrayList<ImageItem> photoSet;
private DrawableManager drawableManager;
private boolean allowLoading = false;
private boolean isLoadingMore = false;
private int index = 0;
/** Set when an image is clicked, can be use to supply start index of slideshow */
private int offset = 0;
private int pageOffset = 0;
private int loadedInCurrentBatch = 0;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.main);
initUIComponents();
loadInitialBatch();
initMediaRouter();
}
private void loadInitialBatch() {
preferences = PreferenceManager.getDefaultSharedPreferences(HipstaActivity.this);
// This flipped check is just for the first load, to make sure the scrollistener and this load doesn't interfere with each other at startup.
if(!allowLoading) {
allowLoading = false;
isLoadingMore = true;
new LoadImageListTask(this, pageOffset, IMAGES_PER_FETCH).execute(preferences.getString("tagsPref", DEFAULT_SEARCH_TAG));
}
}
private void initUIComponents() {
drawableManager = new DrawableManager();
mInfoView = (TextView) findViewById(R.id.status);
mInfoView.setText("Loading...");
gridView = (GridView) findViewById(R.id.gridView);
gridView.setOnScrollListener(new GridViewOnScrollListener());
spinner = (ProgressBar) findViewById(R.id.myspinner);
spinner.setVisibility(View.GONE);
photoSet = new ArrayList<ImageItem>();
customGridAdapter = new GridViewAdapter(this, R.layout.row_grid, photoSet);
gridView.setAdapter(customGridAdapter);
}
private void initMediaRouter() {
mSessionListener = new SessionListener();
mMessageStream = new CustomHipstaCasterStream();
mCastContext = new CastContext(getApplicationContext());
MediaRouteHelper.registerMinimalMediaRouteProvider(mCastContext, this);
mMediaRouter = MediaRouter.getInstance(getApplicationContext());
mMediaRouteSelector = MediaRouteHelper.buildMediaRouteSelector(
MediaRouteHelper.CATEGORY_CAST, APP_NAME, null);
mMediaRouterCallback = new MediaRouterCallback();
}
/**
* Typically invoked
* @param list
*/
public void onPhotoListLoaded(List<Photo> list) {
loadedInCurrentBatch = 0;
mInfoView.setText("Loaded " + list.size() + " images definitions from Flickr");
for(Photo p : list) {
photoSet.add(new BitmapImageItem(drawableManager.drawableToBitmap(getResources().getDrawable(R.drawable.user_placeholder)), p.getOwnerName(), p.getFullsizeUrl(), p.getTitle(), p.getDescription()));
}
index = pageOffset * IMAGES_PER_FETCH;
for(Photo p : list) {
drawableManager.fetchDrawableOnThread(p.getSquareUrl(), index, new Callback() {
@Override
public void updateGridView(final Bitmap bitmap, final int position) {
runOnUiThread(new Runnable() {
@Override
public void run() {
BitmapImageItem itemAtPosition = (BitmapImageItem) gridView.getItemAtPosition(position);
itemAtPosition.setImage(bitmap);
gridView.invalidateViews();
loadedInCurrentBatch++;
if(loadedInCurrentBatch >= IMAGES_PER_FETCH) {
allowLoading = true;
loadedInCurrentBatch = 0;
}
}
});
}
});
index++;
}
gridView.setAlpha(1.0f);
}
/**
* Called when the options menu is first created.
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu, menu);
initChromeCastMenuItem(menu);
initSettingsMenuItem(menu);
initRefreshMenuItem(menu);
initSlideShowMenuItem(menu);
return true;
}
private void initChromeCastMenuItem(Menu menu) {
MenuItem mediaRouteMenuItem = menu.findItem(R.id.media_route_menu_item);
MediaRouteActionProvider mediaRouteActionProvider =
(MediaRouteActionProvider) MenuItemCompat.getActionProvider(mediaRouteMenuItem);
mediaRouteActionProvider.setRouteSelector(mMediaRouteSelector);
}
private void initSlideShowMenuItem(Menu menu) {
MenuItem slideShowMenuItem = menu.findItem(R.id.action_slideshow);
slideShowMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if(mSession != null && mSession.hasStarted() && photoSet != null && photoSet.size() > 0) {
sendPhotoSet();
Toast.makeText(HipstaActivity.this, "Starting slideshow on ChromeCast!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(HipstaActivity.this, "Please connect to cast device first.", Toast.LENGTH_SHORT).show();
}
return false;
}
});
}
private void initRefreshMenuItem(Menu menu) {
MenuItem refreshMenuItem = menu.findItem(R.id.action_refresh);
refreshMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if(gridView != null) {
((GridViewAdapter) gridView.getAdapter()).clear();
gridView.setAlpha(0.2f);
pageOffset = 0;
new LoadImageListTask(HipstaActivity.this, pageOffset, IMAGES_PER_FETCH).execute(preferences.getString("tagsPref", DEFAULT_SEARCH_TAG));
}
return false;
}
});
}
private void initSettingsMenuItem(Menu menu) {
MenuItem settingsMenuItem = menu.findItem(R.id.action_settings);
settingsMenuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
Intent settingsActivity = new Intent(getBaseContext(),
Preferences.class);
startActivity(settingsActivity);
return false;
}
});
}
/**
* Called on application start.
*/
@Override
protected void onStart() {
super.onStart();
mMediaRouter.addCallback(mMediaRouteSelector, mMediaRouterCallback,
MediaRouter.CALLBACK_FLAG_PERFORM_ACTIVE_SCAN);
}
// Currently no custom behaviour in onPause and onStop. So no overriding.
/**
* Ends any existing application session with a Chromecast device.
*/
private void endSession() {
if ((mSession != null) && (mSession.hasStarted())) {
try {
if (mSession.hasChannel()) {
// TODO perhaps notify receiever app that we're disconnecting?
}
mSession.endSession();
} catch (IOException e) {
Log.e(TAG, "Failed to end the session.", e);
} catch (IllegalStateException e) {
Log.e(TAG, "Unable to end session.", e);
} finally {
mSession = null;
}
}
}
/**
* Unregisters the media route provider and disposes the CastContext.
*/
@Override
public void onDestroy() {
Log.i(TAG, "ENTER - onDestroy");
// These two has been moved from onStop. We don't want slideshow or view photo on Chromecast to stop unless Hipstacaster app closes for real.
endSession();
mMediaRouter.removeCallback(mMediaRouterCallback);
MediaRouteHelper.unregisterMediaRouteProvider(mCastContext);
mCastContext.dispose();
mCastContext = null;
super.onDestroy();
}
/**
* Returns the screen configuration to portrait mode whenever changed.
*/
@Override
public void onConfigurationChanged(Configuration newConfig) {
Log.i(TAG, "ENTER - onConfigurationChanged");
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
private void setSelectedDevice(CastDevice device) {
mSelectedDevice = device;
if (mSelectedDevice != null) {
Log.i(TAG, "ENTER - setSelectedDevice: " + device.toString());
mSession = new ApplicationSession(mCastContext, mSelectedDevice);
mSession.setListener(mSessionListener);
try {
mSession.startSession(APP_NAME);
mInfoView.setText("Session started!");
} catch (IOException e) {
Log.e(TAG, "Failed to open a session", e);
mInfoView.setText("Failed to open a session");
}
} else {
endSession();
}
}
/**
* Called when a user selects a route.
*/
private void onRouteSelected(android.support.v7.media.MediaRouter.RouteInfo route) {
sLog.d("onRouteSelected: %s", route.getName());
MediaRouteHelper.requestCastDeviceForRoute(route);
}
/**
* Called when a user unselects a route.
*/
private void onRouteUnselected(android.support.v7.media.MediaRouter.RouteInfo route) {
sLog.d("onRouteUnselected: %s", route.getName());
setSelectedDevice(null);
}
/**
* A class which listens to session start events. On detection, it attaches the message
* stream.
*/
private class SessionListener implements ApplicationSession.Listener {
@Override
public void onSessionStarted(ApplicationMetadata appMetadata) {
Log.i(TAG, "SessionListener.onStarted");
ApplicationChannel channel = mSession.getChannel();
if (channel == null) {
Log.w(TAG, "onStarted: channel is null");
return;
}
channel.attachMessageStream(mMessageStream);
mInfoView.setText("Session started");
}
@Override
public void onSessionStartFailed(SessionError error) {
sLog.d("SessionListener.onStartFailed: %s", error);
}
@Override
public void onSessionEnded(SessionError error) {
sLog.d("SessionListener.onEnded: %s", error);
}
}
/**
* An extension of the MessageStream with some local details.
*/
private class CustomHipstaCasterStream extends HipstaCasterMessageStream {
/**
* Displays an error dialog.
*/
@Override
protected void onError(String errorMessage) {
buildAlertDialog("Error", errorMessage);
}
/**
* Displays a message that the slideshow has ended.
*/
@Override
protected void onSlideShowEnded() {
buildAlertDialog("Message from ChromeCast", "Slideshow has ended");
}
/**
* Updates the textView with the currently viewed photo from the slideshoe (n of m)
*/
@Override
protected void onCurrentSlideShowImageMessage(String message) {
mInfoView.setText(message);
}
}
/**
* An extension of the MediaRoute.Callback so we can invoke our own onRoute selected/unselected
*/
private class MediaRouterCallback extends MediaRouter.Callback {
@Override
public void onRouteSelected(MediaRouter router, android.support.v7.media.MediaRouter.RouteInfo route) {
Log.i(TAG, "onRouteSelected: " + route);
HipstaActivity.this.onRouteSelected(route);
}
@Override
public void onRouteUnselected(MediaRouter router, android.support.v7.media.MediaRouter.RouteInfo route) {
Log.i(TAG, "onRouteUnselected: " + route);
HipstaActivity.this.onRouteUnselected(route);
}
}
@Override
public void onDeviceAvailable(CastDevice device, String routeId,
MediaRouteStateChangeListener listener) {
sLog.d("onDeviceAvailable: %s (route %s)", device, routeId);
setSelectedDevice(device);
}
/**
* Sends image data for a single image to the receiver app.
* @param title
* @param url
* @param ownerName
* @param description
*/
public void openPhoto(String title, String url, String ownerName, String description) {
if(isCastSessionActive()) {
mMessageStream.openPhotoOnChromecast(title, url, ownerName, description);
}
}
/**
* Sends the current set of photos to the chromecast, including an offset index which can be used to start the slideshow
* at any position of the set.
*/
public void sendPhotoSet() {
if(isCastSessionActive() && photoSet != null && photoSet.size() > 0) {
mMessageStream.sendPhotoSetToChromecast(photoSet, offset);
}
}
private boolean isCastSessionActive() {
return mSession != null && mSession.hasChannel() && mSession.hasStarted();
}
public void showSpinner() {
isLoadingMore = true;
this.runOnUiThread(new Runnable() {
@Override
public void run() {
spinner.setVisibility(View.VISIBLE);
}
});
}
public void hideSpinner() {
isLoadingMore = false;
this.runOnUiThread(new Runnable() {
@Override
public void run() {
spinner.setVisibility(View.GONE);
}
});
}
/**
* Sets the current offset (e.g. selected image index)
*
* @param offset
*/
public void setOffset(int offset) {
this.offset = offset;
}
@Override
public void onSetVolume(double volume) {
}
@Override
public void onUpdateVolume(double delta) {
}
private void buildAlertDialog(String title, String msg) {
new AlertDialog.Builder(HipstaActivity.this)
.setTitle(title)
.setMessage(msg)
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.create()
.show();
}
private class GridViewOnScrollListener implements OnScrollListener {
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if (totalItemCount > 0 && (lastInScreen == totalItemCount) && !isLoadingMore && !(pageOffset*IMAGES_PER_FETCH > gridView.getCount()) && allowLoading) {
isLoadingMore = true;
new LoadImageListTask(HipstaActivity.this, ++pageOffset, IMAGES_PER_FETCH).execute(preferences.getString("tagsPref", DEFAULT_SEARCH_TAG));
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
}