code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* Copyright 2013 Google Inc.
*
* 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 com.google.android.apps.iosched.ui;
import android.content.res.Resources;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.ui.MapFragment.MarkerModel;
import com.google.android.apps.iosched.ui.widget.EllipsizedTextView;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.Marker;
import java.util.HashMap;
class MapInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {
// Common parameters
private String roomTitle;
private Marker mMarker;
//Session
private String titleCurrent, titleNext, timeNext;
private boolean inProgress;
//Sandbox
private int sandboxColor;
private int companyIcon;
private String companyList;
// Inflated views
private View mViewSandbox = null;
private View mViewSession = null;
private View mViewTitleOnly = null;
private LayoutInflater mInflater;
private Resources mResources;
private HashMap<String, MarkerModel> mMarkers;
public MapInfoWindowAdapter(LayoutInflater inflater, Resources resources,
HashMap<String, MarkerModel> markers) {
this.mInflater = inflater;
this.mResources = resources;
mMarkers = markers;
}
@Override
public View getInfoContents(Marker marker) {
// render fallback if incorrect data is set or any other type
// except for session or sandbox are rendered
if (mMarker != null && !mMarker.getTitle().equals(marker.getTitle()) &&
(MapFragment.TYPE_SESSION.equals(marker.getSnippet()) ||
MapFragment.TYPE_SANDBOX.equals(marker.getSnippet()))) {
// View will be rendered in getInfoWindow, need to return null
return null;
} else {
return renderTitleOnly(marker);
}
}
@Override
public View getInfoWindow(Marker marker) {
if (mMarker != null && mMarker.getTitle().equals(marker.getTitle())) {
final String snippet = marker.getSnippet();
if (MapFragment.TYPE_SESSION.equals(snippet)) {
return renderSession(marker);
} else if (MapFragment.TYPE_SANDBOX.equals(snippet)) {
return renderSandbox(marker);
}
}
return null;
}
private View renderTitleOnly(Marker marker) {
if (mViewTitleOnly == null) {
mViewTitleOnly = mInflater.inflate(R.layout.map_info_titleonly, null);
}
TextView title = (TextView) mViewTitleOnly.findViewById(R.id.map_info_title);
title.setText(mMarkers.get(marker.getTitle()).label);
return mViewTitleOnly;
}
private View renderSession(Marker marker) {
if (mViewSession == null) {
mViewSession = mInflater.inflate(R.layout.map_info_session, null);
}
TextView roomName = (TextView) mViewSession.findViewById(R.id.map_info_roomtitle);
roomName.setText(roomTitle);
TextView first = (TextView) mViewSession.findViewById(R.id.map_info_session_now);
TextView second = (TextView) mViewSession.findViewById(R.id.map_info_session_next);
View spacer = mViewSession.findViewById(R.id.map_info_session_spacer);
// default visibility
first.setVisibility(View.GONE);
second.setVisibility(View.GONE);
spacer.setVisibility(View.GONE);
if (inProgress) {
// A session is in progress, show its title
first.setText(Html.fromHtml(mResources.getString(R.string.map_now_playing,
titleCurrent)));
first.setVisibility(View.VISIBLE);
}
// show the next session if there is one
if (titleNext != null) {
second.setText(Html.fromHtml(mResources.getString(R.string.map_at, timeNext, titleNext)));
second.setVisibility(View.VISIBLE);
}
if(!inProgress && titleNext == null){
// No session in progress or coming up
second.setText(Html.fromHtml(mResources.getString(R.string.map_now_playing,
mResources.getString(R.string.map_infowindow_text_empty))));
second.setVisibility(View.VISIBLE);
}else if(inProgress && titleNext != null){
// Both lines are displayed, add extra padding
spacer.setVisibility(View.VISIBLE);
}
return mViewSession;
}
private View renderSandbox(Marker marker) {
if (mViewSandbox == null) {
mViewSandbox = mInflater.inflate(R.layout.map_info_sandbox, null);
}
TextView titleView = (TextView) mViewSandbox.findViewById(R.id.map_info_roomtitle);
titleView.setText(roomTitle);
ImageView iconView = (ImageView) mViewSandbox.findViewById(R.id.map_info_icon);
iconView.setImageResource(companyIcon);
View rootLayout = mViewSandbox.findViewById(R.id.map_info_top);
rootLayout.setBackgroundColor(this.sandboxColor);
// Views
EllipsizedTextView companyListView = (EllipsizedTextView) mViewSandbox.findViewById(R.id.map_info_sandbox_now);
if (this.companyList != null) {
companyListView.setText(Html.fromHtml(mResources.getString(R.string.map_now_sandbox,
companyList)));
//TODO: fix missing ellipsize
} else {
// No active companies
companyListView.setText(Html.fromHtml(mResources.getString(R.string.map_now_sandbox,
mResources.getString(R.string.map_infowindow_text_empty))));
}
return mViewSandbox;
}
public void clearData() {
this.titleCurrent = null;
this.titleNext = null;
this.inProgress = false;
this.mMarker = null;
}
public void setSessionData(Marker marker, String roomTitle, String titleCurrent,
String titleNext,
String timeNext,
boolean inProgress) {
clearData();
this.titleCurrent = titleCurrent;
this.titleNext = titleNext;
this.timeNext = timeNext;
this.inProgress = inProgress;
this.mMarker = marker;
this.roomTitle = roomTitle;
}
public void setMarker(Marker marker, String roomTitle) {
clearData();
this.mMarker = marker;
this.roomTitle = roomTitle;
}
public void setSandbox(Marker marker, String label, int color, int iconId, String companies) {
clearData();
mMarker = marker;
this.companyList = companies;
this.roomTitle = label;
this.sandboxColor = color;
this.companyIcon = iconId;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.ui;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Presentation;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.media.MediaRouter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.BaseColumns;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.CursorAdapter;
import android.text.TextUtils;
import android.view.*;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.Config;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.provider.ScheduleContract.Tracks;
import com.google.android.apps.iosched.util.SessionsHelper;
import com.google.android.apps.iosched.util.UIUtils;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerSupportFragment;
import java.util.ArrayList;
import java.util.HashMap;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* An activity that displays the session live stream video which is pulled in from YouTube. The
* UI adapts for both phone and tablet. As we want to prevent the YouTube player from restarting
* and buffering again on orientation change, we handle configuration changes manually.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class SessionLivestreamActivity extends BaseActivity implements
LoaderCallbacks<Cursor>,
YouTubePlayer.OnInitializedListener,
YouTubePlayer.PlayerStateChangeListener,
YouTubePlayer.OnFullscreenListener,
ActionBar.OnNavigationListener {
private static final String TAG = makeLogTag(SessionLivestreamActivity.class);
private static final String EXTRA_PREFIX = "com.google.android.iosched.extra.";
private static final int YOUTUBE_RECOVERY_RESULT = 1;
private static final String LOADER_SESSIONS_ARG = "futureSessions";
public static final String EXTRA_YOUTUBE_URL = EXTRA_PREFIX + "youtube_url";
public static final String EXTRA_TRACK = EXTRA_PREFIX + "track";
public static final String EXTRA_TITLE = EXTRA_PREFIX + "title";
public static final String EXTRA_ABSTRACT = EXTRA_PREFIX + "abstract";
public static final String KEYNOTE_TRACK_NAME = "Keynote";
private static final String TAG_SESSION_SUMMARY = "session_summary";
private static final String TAG_CAPTIONS = "captions";
private static final int TABNUM_SESSION_SUMMARY = 0;
private static final int TABNUM_SOCIAL_STREAM = 1;
private static final int TABNUM_LIVE_CAPTIONS = 2;
private static final String EXTRA_TAB_STATE = "tag";
private static final int STREAM_REFRESH_TIME = 5 * 60 * 1000; // 5 minutes
private boolean mIsTablet;
private boolean mIsFullscreen = false;
private boolean mLoadFromExtras = false;
private boolean mTrackPlay = true;
private TabHost mTabHost;
private TabsAdapter mTabsAdapter;
private YouTubePlayer mYouTubePlayer;
private YouTubePlayerSupportFragment mYouTubeFragment;
private LinearLayout mPlayerContainer;
private String mYouTubeVideoId;
private LinearLayout mMainLayout;
private LinearLayout mVideoLayout;
private LinearLayout mExtraLayout;
private FrameLayout mPresentationControls;
private FrameLayout mSummaryLayout;
private FrameLayout mFullscreenCaptions;
private MenuItem mCaptionsMenuItem;
private MenuItem mShareMenuItem;
private MenuItem mPresentationMenuItem;
private Runnable mShareMenuDeferredSetup;
private Runnable mSessionSummaryDeferredSetup;
private SessionShareData mSessionShareData;
private boolean mSessionsFound;
private boolean isKeynote = false;
private Handler mHandler = new Handler();
private int mYouTubeFullscreenFlags;
private LivestreamAdapter mLivestreamAdapter;
private Uri mSessionUri;
private String mSessionId;
private String mTrackName;
private MediaRouter mMediaRouter;
private YouTubePresentation mPresentation;
private MediaRouter.SimpleCallback mMediaRouterCallback;
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
protected void onCreate(Bundle savedInstanceState) {
if (UIUtils.hasICS()) {
// We can't use this mode on HC as compatible ActionBar doesn't work well with the YT
// player in full screen mode (no overlays allowed).
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_session_livestream);
mIsTablet = UIUtils.isHoneycombTablet(this);
// Set up YouTube player
mYouTubeFragment = (YouTubePlayerSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.livestream_player);
mYouTubeFragment.initialize(Config.YOUTUBE_API_KEY, this);
// Views that are common over all layouts
mMainLayout = (LinearLayout) findViewById(R.id.livestream_mainlayout);
mPresentationControls = (FrameLayout) findViewById(R.id.presentation_controls);
adjustMainLayoutForActionBar();
mPlayerContainer = (LinearLayout) findViewById(R.id.livestream_player_container);
mFullscreenCaptions = (FrameLayout) findViewById(R.id.fullscreen_captions);
final LayoutParams params = (LayoutParams) mFullscreenCaptions.getLayoutParams();
params.setMargins(0, getActionBarHeightPx(), 0, getActionBarHeightPx());
mFullscreenCaptions.setLayoutParams(params);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setOffscreenPageLimit(2);
if (!mIsTablet) {
viewPager.setPageMarginDrawable(R.drawable.grey_border_inset_lr);
}
viewPager.setPageMargin(getResources().getDimensionPixelSize(R.dimen.page_margin_width));
// Set up tabs w/ViewPager
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
mTabsAdapter = new TabsAdapter(this, mTabHost, viewPager);
if (mIsTablet) {
// Tablet UI specific views
getSupportFragmentManager().beginTransaction().add(R.id.livestream_summary,
new SessionSummaryFragment(), TAG_SESSION_SUMMARY).commit();
mVideoLayout = (LinearLayout) findViewById(R.id.livestream_videolayout);
mExtraLayout = (LinearLayout) findViewById(R.id.livestream_extralayout);
mSummaryLayout = (FrameLayout) findViewById(R.id.livestream_summary);
} else {
// Handset UI specific views
mTabsAdapter.addTab(
getString(R.string.session_livestream_info),
new SessionSummaryFragment(),
TABNUM_SESSION_SUMMARY);
}
mTabsAdapter.addTab(getString(R.string.title_stream), new SocialStreamFragment(),
TABNUM_SOCIAL_STREAM);
mTabsAdapter.addTab(getString(R.string.session_livestream_captions),
new SessionLiveCaptionsFragment(), TABNUM_LIVE_CAPTIONS);
if (savedInstanceState != null) {
mTabHost.setCurrentTabByTag(savedInstanceState.getString(EXTRA_TAB_STATE));
}
// Reload all other data in this activity
reloadFromIntent(getIntent());
// Update layout based on current configuration
updateLayout(getResources().getConfiguration());
// Set up action bar
if (!mLoadFromExtras) {
// Start sessions query to populate action bar navigation spinner
getSupportLoaderManager().initLoader(SessionsQuery._TOKEN, null, this);
// Set up action bar
mLivestreamAdapter = new LivestreamAdapter(getSupportActionBar().getThemedContext());
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(mLivestreamAdapter, this);
actionBar.setDisplayShowTitleEnabled(false);
}
// Media Router and Presentation set up
if (UIUtils.hasJellyBeanMR1()) {
mMediaRouterCallback = new MediaRouter.SimpleCallback() {
@Override
public void onRouteSelected(MediaRouter router, int type,
MediaRouter.RouteInfo info) {
LOGD(TAG, "onRouteSelected: type=" + type + ", info=" + info);
updatePresentation();
}
@Override
public void onRouteUnselected(MediaRouter router, int type,
MediaRouter.RouteInfo info) {
LOGD(TAG, "onRouteUnselected: type=" + type + ", info=" + info);
updatePresentation();
}
@Override
public void onRoutePresentationDisplayChanged(MediaRouter router,
MediaRouter.RouteInfo info) {
LOGD(TAG, "onRoutePresentationDisplayChanged: info=" + info);
updatePresentation();
}
};
mMediaRouter = (MediaRouter) getSystemService(Context.MEDIA_ROUTER_SERVICE);
final ImageButton playPauseButton = (ImageButton) findViewById(R.id.play_pause_button);
playPauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mYouTubePlayer != null) {
if (mYouTubePlayer.isPlaying()) {
mYouTubePlayer.pause();
playPauseButton.setImageResource(R.drawable.ic_livestream_play);
} else {
mYouTubePlayer.play();
playPauseButton.setImageResource(R.drawable.ic_livestream_pause);
}
}
}
});
updatePresentation();
}
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
protected void onResume() {
super.onResume();
if (mSessionSummaryDeferredSetup != null) {
mSessionSummaryDeferredSetup.run();
mSessionSummaryDeferredSetup = null;
}
mHandler.postDelayed(mStreamRefreshRunnable, STREAM_REFRESH_TIME);
if (UIUtils.hasJellyBeanMR1()) {
mMediaRouter.addCallback(MediaRouter.ROUTE_TYPE_LIVE_VIDEO, mMediaRouterCallback);
}
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
protected void onPause() {
super.onPause();
mHandler.removeCallbacks(mStreamRefreshRunnable);
if (UIUtils.hasJellyBeanMR1()) {
mMediaRouter.removeCallback(mMediaRouterCallback);
}
}
@Override
public void onStop() {
super.onStop();
// Dismiss the presentation when the activity is not visible
if (mPresentation != null) {
LOGD(TAG, "Dismissing presentation because the activity is no longer visible.");
mPresentation.dismiss();
mPresentation = null;
}
}
/**
* Reloads all data in the activity and fragments from a given intent
* @param intent The intent to load from
*/
private void reloadFromIntent(Intent intent) {
final String youtubeUrl = intent.getStringExtra(EXTRA_YOUTUBE_URL);
// Check if youtube url is set as an extra first
if (youtubeUrl != null) {
mLoadFromExtras = true;
String trackName = intent.getStringExtra(EXTRA_TRACK);
String actionBarTitle;
if (trackName == null) {
actionBarTitle = getString(R.string.session_livestream_title);
} else {
isKeynote = KEYNOTE_TRACK_NAME.equals(trackName);
actionBarTitle = trackName + " - " + getString(R.string.session_livestream_title);
}
getSupportActionBar().setTitle(actionBarTitle);
updateSessionViews(youtubeUrl, intent.getStringExtra(EXTRA_TITLE),
intent.getStringExtra(EXTRA_ABSTRACT),
UIUtils.CONFERENCE_HASHTAG, trackName);
} else {
// Otherwise load from session uri
reloadFromUri(intent.getData());
}
}
/**
* Reloads all data in the activity and fragments from a given uri
* @param newUri The session uri to load from
*/
private void reloadFromUri(Uri newUri) {
mSessionUri = newUri;
if (mSessionUri != null && mSessionUri.getPathSegments().size() >= 2) {
mSessionId = Sessions.getSessionId(mSessionUri);
getSupportLoaderManager().restartLoader(SessionSummaryQuery._TOKEN, null, this);
} else {
// No session uri, get out
mSessionUri = null;
finish();
}
}
/**
* Helper method to start this activity using only extras (rather than session uri).
* @param context The package context
* @param youtubeUrl The youtube url or video id to load
* @param track The track title (appears as part of action bar title), can be null
* @param title The title to show in the session info fragment, can be null
* @param sessionAbstract The session abstract to show in the session info fragment, can be null
*/
public static void startFromExtras(Context context, String youtubeUrl, String track,
String title, String sessionAbstract) {
if (youtubeUrl == null) {
return;
}
final Intent i = new Intent();
i.setClass(context, SessionLivestreamActivity.class);
i.putExtra(EXTRA_YOUTUBE_URL, youtubeUrl);
i.putExtra(EXTRA_TRACK, track);
i.putExtra(EXTRA_TITLE, title);
i.putExtra(EXTRA_ABSTRACT, sessionAbstract);
context.startActivity(i);
}
/**
* Start a keynote live stream from extras. This sets the track name correctly so captions
* will be correctly displayed.
*
* This will play the video given in youtubeUrl, however if a number ranging from 1-99 is
* passed in this param instead it will be parsed and used to lookup a youtube ID from a
* google spreadsheet using the param as the spreadsheet row number.
*/
public static void startKeynoteFromExtras(Context context, String youtubeUrl, String title,
String sessionAbstract) {
startFromExtras(context, youtubeUrl, KEYNOTE_TRACK_NAME, title, sessionAbstract);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mTabHost != null) {
outState.putString(EXTRA_TAB_STATE, mTabHost.getCurrentTabTag());
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.session_livestream, menu);
mCaptionsMenuItem = menu.findItem(R.id.menu_captions);
mPresentationMenuItem = menu.findItem(R.id.menu_presentation);
mPresentationMenuItem.setVisible(mPresentation != null);
updatePresentationMenuItem(mPresentation != null);
mShareMenuItem = menu.findItem(R.id.menu_share);
if (mShareMenuDeferredSetup != null) {
mShareMenuDeferredSetup.run();
}
if (!mIsTablet && Configuration.ORIENTATION_LANDSCAPE ==
getResources().getConfiguration().orientation) {
mCaptionsMenuItem.setVisible(true);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_captions:
if (mIsFullscreen) {
if (mFullscreenCaptions.getVisibility() == View.GONE) {
mFullscreenCaptions.setVisibility(View.VISIBLE);
SessionLiveCaptionsFragment captionsFragment;
captionsFragment = (SessionLiveCaptionsFragment)
getSupportFragmentManager().findFragmentByTag(TAG_CAPTIONS);
if (captionsFragment == null) {
captionsFragment = new SessionLiveCaptionsFragment();
captionsFragment.setDarkTheme(true);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.fullscreen_captions, captionsFragment, TAG_CAPTIONS);
ft.commit();
}
captionsFragment.setTrackName(mTrackName);
return true;
}
}
mFullscreenCaptions.setVisibility(View.GONE);
break;
case R.id.menu_share:
if (mSessionShareData != null) {
new SessionsHelper(this).shareSession(this,
R.string.share_livestream_template,
mSessionShareData.title,
mSessionShareData.hashtag,
mSessionShareData.sessionUrl);
return true;
}
break;
case R.id.menu_presentation:
if (mPresentation != null) {
mPresentation.dismiss();
} else {
updatePresentation();
}
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
// Need to handle configuration changes so as not to interrupt YT player and require
// buffering again
updateLayout(newConfig);
super.onConfigurationChanged(newConfig);
}
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
final Cursor cursor = (Cursor) mLivestreamAdapter.getItem(itemPosition);
String trackName = cursor.getString(SessionsQuery.TRACK_NAME);
int trackColor = cursor.getInt(SessionsQuery.TRACK_COLOR);
setActionBarTrackIcon(trackName, trackColor);
final String sessionId = cursor.getString(SessionsQuery.SESSION_ID);
if (sessionId != null) {
reloadFromUri(Sessions.buildSessionUri(sessionId));
return true;
}
return false;
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
switch (id) {
case SessionSummaryQuery._TOKEN:
return new CursorLoader(this, Sessions.buildWithTracksUri(mSessionId),
SessionSummaryQuery.PROJECTION, null, null, null);
case SessionsQuery._TOKEN:
boolean futureSessions = false;
if (args != null) {
futureSessions = args.getBoolean(LOADER_SESSIONS_ARG, false);
}
final long currentTime = UIUtils.getCurrentTime(this);
String selection = Sessions.LIVESTREAM_SELECTION + " and ";
String[] selectionArgs;
if (!futureSessions) {
selection += Sessions.AT_TIME_SELECTION;
selectionArgs = Sessions.buildAtTimeSelectionArgs(currentTime);
} else {
selection += Sessions.UPCOMING_SELECTION;
selectionArgs = Sessions.buildUpcomingSelectionArgs(currentTime);
}
return new CursorLoader(this, Sessions.buildWithTracksUri(),
SessionsQuery.PROJECTION, selection, selectionArgs, null);
}
return null;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
switch (loader.getId()) {
case SessionSummaryQuery._TOKEN:
loadSession(data);
break;
case SessionsQuery._TOKEN:
mLivestreamAdapter.swapCursor(data);
if (data != null && data.getCount() > 0) {
mSessionsFound = true;
final int selected = locateSelectedItem(data);
getSupportActionBar().setSelectedNavigationItem(selected);
} else if (mSessionsFound) {
mSessionsFound = false;
final Bundle bundle = new Bundle();
bundle.putBoolean(LOADER_SESSIONS_ARG, true);
getSupportLoaderManager().restartLoader(SessionsQuery._TOKEN, bundle, this);
} else {
finish();
}
break;
}
}
/**
* Locates which item should be selected in the action bar drop-down spinner based on the
* current active session uri
* @param data The data
* @return The row num of the item that should be selected or 0 if not found
*/
private int locateSelectedItem(Cursor data) {
int selected = 0;
if (data != null && (mSessionId != null || mTrackName != null)) {
final boolean findNextSessionByTrack = mTrackName != null;
while (data.moveToNext()) {
if (findNextSessionByTrack) {
if (mTrackName.equals(data.getString(SessionsQuery.TRACK_NAME))) {
selected = data.getPosition();
mTrackName = null;
break;
}
} else {
if (mSessionId.equals(data.getString(SessionsQuery.SESSION_ID))) {
selected = data.getPosition();
}
}
}
}
return selected;
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
switch (loader.getId()) {
case SessionsQuery._TOKEN:
mLivestreamAdapter.swapCursor(null);
break;
}
}
@Override
public void onFullscreen(boolean fullscreen) {
layoutFullscreenVideo(fullscreen);
}
@Override
public void onLoading() {
}
@Override
public void onLoaded(String s) {
}
@Override
public void onAdStarted() {
}
@Override
public void onVideoStarted() {
}
@Override
public void onVideoEnded() {
}
@Override
public void onError(YouTubePlayer.ErrorReason errorReason) {
Toast.makeText(this, R.string.session_livestream_error_playback, Toast.LENGTH_LONG).show();
LOGE(TAG, errorReason.toString());
}
private void loadSession(Cursor data) {
if (data != null && data.moveToFirst()) {
mTrackName = data.getString(SessionSummaryQuery.TRACK_NAME);
if (TextUtils.isEmpty(mTrackName)) {
mTrackName = KEYNOTE_TRACK_NAME;
isKeynote = true;
}
final long currentTime = UIUtils.getCurrentTime(this);
if (currentTime > data.getLong(SessionSummaryQuery.BLOCK_END)) {
getSupportLoaderManager().restartLoader(SessionsQuery._TOKEN, null, this);
return;
}
updateTagStreamFragment(data.getString(SessionSummaryQuery.HASHTAGS));
updateSessionViews(
data.getString(SessionSummaryQuery.LIVESTREAM_URL),
data.getString(SessionSummaryQuery.TITLE),
data.getString(SessionSummaryQuery.ABSTRACT),
data.getString(SessionSummaryQuery.HASHTAGS), mTrackName);
}
}
/**
* Updates views that rely on session data from explicit strings.
*/
private void updateSessionViews(final String youtubeUrl, final String title,
final String sessionAbstract, final String hashTag, final String trackName) {
if (youtubeUrl == null) {
// Get out, nothing to do here
finish();
return;
}
mTrackName = trackName;
String youtubeVideoId = youtubeUrl;
if (youtubeUrl.startsWith("http")) {
final Uri youTubeUri = Uri.parse(youtubeUrl);
youtubeVideoId = youTubeUri.getQueryParameter("v");
}
// Play the video
playVideo(youtubeVideoId);
if (mTrackPlay) {
EasyTracker.getTracker().sendView("Live Streaming: " + title);
LOGD("Tracker", "Live Streaming: " + title);
}
final String newYoutubeUrl = Config.YOUTUBE_SHARE_URL_PREFIX + youtubeVideoId;
mSessionShareData = new SessionShareData(title, hashTag, newYoutubeUrl);
mShareMenuDeferredSetup = new Runnable() {
@Override
public void run() {
new SessionsHelper(SessionLivestreamActivity.this)
.tryConfigureShareMenuItem(mShareMenuItem,
R.string.share_livestream_template,
title, hashTag, newYoutubeUrl);
}
};
if (mShareMenuItem != null) {
mShareMenuDeferredSetup.run();
mShareMenuDeferredSetup = null;
}
mSessionSummaryDeferredSetup = new Runnable() {
@Override
public void run() {
updateSessionSummaryFragment(title, sessionAbstract);
updateSessionLiveCaptionsFragment(trackName);
}
};
if (!mLoadFromExtras) {
mSessionSummaryDeferredSetup.run();
mSessionSummaryDeferredSetup = null;
}
}
private void updateSessionSummaryFragment(String title, String sessionAbstract) {
SessionSummaryFragment sessionSummaryFragment = null;
if (mIsTablet) {
sessionSummaryFragment = (SessionSummaryFragment)
getSupportFragmentManager().findFragmentByTag(TAG_SESSION_SUMMARY);
} else {
if (mTabsAdapter.mFragments.containsKey(TABNUM_SESSION_SUMMARY)) {
sessionSummaryFragment = (SessionSummaryFragment)
mTabsAdapter.mFragments.get(TABNUM_SESSION_SUMMARY);
}
}
if (sessionSummaryFragment != null) {
sessionSummaryFragment.setSessionSummaryInfo(
isKeynote ? getString(R.string.session_livestream_keynote_title, title) : title,
(isKeynote && TextUtils.isEmpty(sessionAbstract)) ?
getString(R.string.session_livestream_keynote_desc)
: sessionAbstract);
}
}
private Runnable mStreamRefreshRunnable = new Runnable() {
@Override
public void run() {
if (mTabsAdapter != null && mTabsAdapter.mFragments != null &&
mTabsAdapter.mFragments.containsKey(TABNUM_SOCIAL_STREAM)) {
final SocialStreamFragment socialStreamFragment =
(SocialStreamFragment) mTabsAdapter.mFragments.get(TABNUM_SOCIAL_STREAM);
socialStreamFragment.refresh();
}
mHandler.postDelayed(mStreamRefreshRunnable, STREAM_REFRESH_TIME);
}
};
private void updateTagStreamFragment(String trackHashTag) {
String hashTags = UIUtils.CONFERENCE_HASHTAG;
if (!TextUtils.isEmpty(trackHashTag)) {
hashTags += " " + trackHashTag;
}
if (mTabsAdapter.mFragments.containsKey(TABNUM_SOCIAL_STREAM)) {
final SocialStreamFragment socialStreamFragment =
(SocialStreamFragment) mTabsAdapter.mFragments.get(TABNUM_SOCIAL_STREAM);
socialStreamFragment.refresh(hashTags);
}
}
private void updateSessionLiveCaptionsFragment(String trackName) {
if (mTabsAdapter.mFragments.containsKey(TABNUM_LIVE_CAPTIONS)) {
final SessionLiveCaptionsFragment captionsFragment = (SessionLiveCaptionsFragment)
mTabsAdapter.mFragments.get(TABNUM_LIVE_CAPTIONS);
captionsFragment.setTrackName(trackName);
}
}
private void playVideo(String videoId) {
if ((TextUtils.isEmpty(mYouTubeVideoId) || !mYouTubeVideoId.equals(videoId))
&& !TextUtils.isEmpty(videoId)) {
mYouTubeVideoId = videoId;
if (mYouTubePlayer != null) {
mYouTubePlayer.loadVideo(mYouTubeVideoId);
}
mTrackPlay = true;
if (mSessionShareData != null) {
mSessionShareData.sessionUrl = Config.YOUTUBE_SHARE_URL_PREFIX + mYouTubeVideoId;
}
}
}
@Override
public Intent getParentActivityIntent() {
if (mLoadFromExtras || isKeynote || mSessionUri == null) {
return new Intent(this, HomeActivity.class);
} else {
return new Intent(Intent.ACTION_VIEW, mSessionUri);
}
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer youTubePlayer, boolean wasRestored) {
// Set up YouTube player
mYouTubePlayer = youTubePlayer;
mYouTubePlayer.setPlayerStateChangeListener(this);
mYouTubePlayer.setFullscreen(mIsFullscreen);
mYouTubePlayer.setOnFullscreenListener(this);
// YouTube player flags: use a custom full screen layout; let the YouTube player control
// the system UI (hiding navigation controls, ActionBar etc); and let the YouTube player
// handle the orientation state of the activity.
mYouTubeFullscreenFlags = YouTubePlayer.FULLSCREEN_FLAG_CUSTOM_LAYOUT |
YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI |
YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION;
// On smaller screen devices always switch to full screen in landscape mode
if (!mIsTablet) {
mYouTubeFullscreenFlags |= YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE;
}
// Apply full screen flags
setFullscreenFlags();
// If a presentation display is available, set YouTube player style to minimal
if (mPresentation != null) {
mYouTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);
}
// Load the requested video
if (!TextUtils.isEmpty(mYouTubeVideoId)) {
mYouTubePlayer.loadVideo(mYouTubeVideoId);
}
updatePresentation();
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult result) {
LOGE(TAG, result.toString());
if (result.isUserRecoverableError()) {
result.getErrorDialog(this, YOUTUBE_RECOVERY_RESULT).show();
} else {
String errorMessage =
getString(R.string.session_livestream_error_init, result.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == YOUTUBE_RECOVERY_RESULT) {
if (mYouTubeFragment != null) {
mYouTubeFragment.initialize(Config.YOUTUBE_API_KEY, this);
}
}
}
/**
* Updates the layout based on the provided configuration
*/
private void updateLayout(Configuration config) {
if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (mIsTablet) {
layoutTabletForLandscape();
} else {
layoutPhoneForLandscape();
}
} else {
if (mIsTablet) {
layoutTabletForPortrait();
} else {
layoutPhoneForPortrait();
}
}
}
private void layoutPhoneForLandscape() {
layoutFullscreenVideo(true);
}
private void layoutPhoneForPortrait() {
layoutFullscreenVideo(false);
if (mTabsAdapter.mFragments.containsKey(TABNUM_SESSION_SUMMARY)) {
((SessionSummaryFragment)
mTabsAdapter.mFragments.get(TABNUM_SESSION_SUMMARY)).updateViews();
}
}
private void layoutTabletForLandscape() {
mMainLayout.setOrientation(LinearLayout.HORIZONTAL);
final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams();
videoLayoutParams.height = LayoutParams.MATCH_PARENT;
videoLayoutParams.width = 0;
videoLayoutParams.weight = 1;
mVideoLayout.setLayoutParams(videoLayoutParams);
final LayoutParams extraLayoutParams = (LayoutParams) mExtraLayout.getLayoutParams();
extraLayoutParams.height = LayoutParams.MATCH_PARENT;
extraLayoutParams.width = 0;
extraLayoutParams.weight = 1;
mExtraLayout.setLayoutParams(extraLayoutParams);
}
private void layoutTabletForPortrait() {
mMainLayout.setOrientation(LinearLayout.VERTICAL);
final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams();
videoLayoutParams.width = LayoutParams.MATCH_PARENT;
if (mLoadFromExtras) {
// Loading from extras, let the top fragment wrap_content
videoLayoutParams.height = LayoutParams.WRAP_CONTENT;
videoLayoutParams.weight = 0;
} else {
// Otherwise the session description will be longer, give it some space
videoLayoutParams.height = 0;
videoLayoutParams.weight = 7;
}
mVideoLayout.setLayoutParams(videoLayoutParams);
final LayoutParams extraLayoutParams = (LayoutParams) mExtraLayout.getLayoutParams();
extraLayoutParams.width = LayoutParams.MATCH_PARENT;
extraLayoutParams.height = 0;
extraLayoutParams.weight = 5;
mExtraLayout.setLayoutParams(extraLayoutParams);
}
private void layoutFullscreenVideo(boolean fullscreen) {
if (mIsFullscreen != fullscreen) {
mIsFullscreen = fullscreen;
if (mIsTablet) {
// Tablet specific full screen layout
layoutTabletFullscreen(fullscreen);
} else {
// Phone specific full screen layout
layoutPhoneFullscreen(fullscreen);
}
// Full screen layout changes for all form factors
final LayoutParams params = (LayoutParams) mPlayerContainer.getLayoutParams();
if (fullscreen) {
if (mCaptionsMenuItem != null) {
mCaptionsMenuItem.setVisible(true);
}
params.height = LayoutParams.MATCH_PARENT;
mMainLayout.setPadding(0, 0, 0, 0);
} else {
getSupportActionBar().show();
if (mCaptionsMenuItem != null) {
mCaptionsMenuItem.setVisible(false);
}
mFullscreenCaptions.setVisibility(View.GONE);
params.height = LayoutParams.WRAP_CONTENT;
adjustMainLayoutForActionBar();
}
View youTubePlayerView = mYouTubeFragment.getView();
if (youTubePlayerView != null) {
ViewGroup.LayoutParams playerParams = mYouTubeFragment.getView().getLayoutParams();
playerParams.height = fullscreen ? LayoutParams.MATCH_PARENT
: LayoutParams.WRAP_CONTENT;
youTubePlayerView.setLayoutParams(playerParams);
}
mPlayerContainer.setLayoutParams(params);
}
}
private void adjustMainLayoutForActionBar() {
if (UIUtils.hasICS()) {
// On ICS+ we use FEATURE_ACTION_BAR_OVERLAY so full screen mode doesn't need to
// re-adjust layouts when hiding action bar. To account for this we add action bar
// height pack to the padding when not in full screen mode.
mMainLayout.setPadding(0, getActionBarHeightPx(), 0, 0);
}
}
/**
* Adjusts tablet layouts for full screen video.
*
* @param fullscreen True to layout in full screen, false to switch to regular layout
*/
private void layoutTabletFullscreen(boolean fullscreen) {
if (fullscreen) {
mExtraLayout.setVisibility(View.GONE);
mSummaryLayout.setVisibility(View.GONE);
mVideoLayout.setPadding(0, 0, 0, 0);
final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams();
videoLayoutParams.setMargins(0, 0, 0, 0);
mVideoLayout.setLayoutParams(videoLayoutParams);
} else {
final int padding =
getResources().getDimensionPixelSize(R.dimen.multipane_half_padding);
mExtraLayout.setVisibility(View.VISIBLE);
mSummaryLayout.setVisibility(View.VISIBLE);
mVideoLayout.setBackgroundResource(R.drawable.grey_frame_on_white);
final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams();
videoLayoutParams.setMargins(padding, padding, padding, padding);
mVideoLayout.setLayoutParams(videoLayoutParams);
}
}
/**
* Adjusts phone layouts for full screen video.
*/
private void layoutPhoneFullscreen(boolean fullscreen) {
if (fullscreen) {
mTabHost.setVisibility(View.GONE);
if (mYouTubePlayer != null) {
mYouTubePlayer.setFullscreen(true);
}
} else {
mTabHost.setVisibility(View.VISIBLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
private int getActionBarHeightPx() {
int[] attrs = new int[] { android.R.attr.actionBarSize };
return (int) getTheme().obtainStyledAttributes(attrs).getDimension(0, 0f);
}
/**
* Adapter that backs the action bar drop-down spinner.
*/
private class LivestreamAdapter extends CursorAdapter {
LayoutInflater mLayoutInflater;
public LivestreamAdapter(Context context) {
super(context, null, 0);
if (UIUtils.hasICS()) {
mLayoutInflater = (LayoutInflater) getSupportActionBar().getThemedContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
} else {
mLayoutInflater =
(LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
}
}
@Override
public Object getItem(int position) {
mCursor.moveToPosition(position);
return mCursor;
}
@Override
public View newDropDownView(Context context, Cursor cursor, ViewGroup parent) {
// Inflate view that appears in the drop-down spinner views
return mLayoutInflater.inflate(
R.layout.spinner_item_session_livestream, parent, false);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// Inflate view that appears in the selected spinner
return mLayoutInflater.inflate(android.R.layout.simple_spinner_item,
parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Bind view that appears in the selected spinner or in the drop-down
final TextView titleView = (TextView) view.findViewById(android.R.id.text1);
final TextView subTitleView = (TextView) view.findViewById(android.R.id.text2);
String trackName = cursor.getString(SessionsQuery.TRACK_NAME);
if (TextUtils.isEmpty(trackName)) {
trackName = getString(R.string.app_name);
} else {
trackName = getString(R.string.session_livestream_track_title, trackName);
}
String sessionTitle = cursor.getString(SessionsQuery.TITLE);
if (subTitleView != null) { // Drop-down view
titleView.setText(trackName);
subTitleView.setText(sessionTitle);
} else { // Selected view
titleView.setText(getString(R.string.session_livestream_title) + ": " + trackName);
}
}
}
/**
* Adapter that backs the ViewPager tabs on the phone UI.
*/
private static class TabsAdapter extends FragmentPagerAdapter
implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
private final FragmentActivity mContext;
private final TabHost mTabHost;
private final ViewPager mViewPager;
public final HashMap<Integer, Fragment> mFragments;
private final ArrayList<Integer> mTabNums;
private int tabCount = 0;
static class DummyTabFactory implements TabHost.TabContentFactory {
private final Context mContext;
public DummyTabFactory(Context context) {
mContext = context;
}
@Override
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
@SuppressLint("UseSparseArrays")
public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) {
super(activity.getSupportFragmentManager());
mFragments = new HashMap<Integer, Fragment>(3);
mContext = activity;
mTabHost = tabHost;
mViewPager = pager;
mTabHost.setOnTabChangedListener(this);
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
mTabNums = new ArrayList<Integer>(3);
}
public void addTab(String tabTitle, Fragment newFragment, int tabId) {
ViewGroup tabWidget = (ViewGroup) mTabHost.findViewById(android.R.id.tabs);
TextView tabIndicatorView = (TextView) mContext.getLayoutInflater().inflate(
R.layout.tab_indicator_color, tabWidget, false);
tabIndicatorView.setText(tabTitle);
final TabHost.TabSpec tabSpec = mTabHost.newTabSpec(String.valueOf(tabCount++));
tabSpec.setIndicator(tabIndicatorView);
tabSpec.setContent(new DummyTabFactory(mContext));
mTabHost.addTab(tabSpec);
mFragments.put(tabId, newFragment);
mTabNums.add(tabId);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mFragments.size();
}
@Override
public Fragment getItem(int position) {
return mFragments.get(mTabNums.get(position));
}
@Override
public void onTabChanged(String tabId) {
int position = mTabHost.getCurrentTab();
mViewPager.setCurrentItem(position);
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
// Unfortunately when TabHost changes the current tab, it kindly also takes care of
// putting focus on it when not in touch mode. The jerk. This hack tries to prevent
// this from pulling focus out of our ViewPager.
TabWidget widget = mTabHost.getTabWidget();
int oldFocusability = widget.getDescendantFocusability();
widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
mTabHost.setCurrentTab(position);
widget.setDescendantFocusability(oldFocusability);
}
@Override
public void onPageScrollStateChanged(int state) {
}
}
/**
* Simple fragment that inflates a session summary layout that displays session title and
* abstract.
*/
public static class SessionSummaryFragment extends Fragment {
private TextView mTitleView;
private TextView mAbstractView;
private String mTitle;
private String mAbstract;
public SessionSummaryFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_session_summary, null);
mTitleView = (TextView) view.findViewById(R.id.session_title);
mAbstractView = (TextView) view.findViewById(R.id.session_abstract);
updateViews();
return view;
}
public void setSessionSummaryInfo(String sessionTitle, String sessionAbstract) {
mTitle = sessionTitle;
mAbstract = sessionAbstract;
updateViews();
}
public void updateViews() {
if (mTitleView != null && mAbstractView != null) {
mTitleView.setText(mTitle);
if (!TextUtils.isEmpty(mAbstract)) {
mAbstractView.setVisibility(View.VISIBLE);
mAbstractView.setText(mAbstract);
} else {
mAbstractView.setVisibility(View.GONE);
}
}
}
}
/**
* Simple fragment that shows the live captions.
*/
public static class SessionLiveCaptionsFragment extends Fragment {
private static final String CAPTIONS_DARK_THEME_URL_PARAM = "&theme=dark";
private FrameLayout mContainer;
private WebView mWebView;
private TextView mNoCaptionsTextView;
private boolean mDarkTheme = false;
private String mSessionTrack;
public SessionLiveCaptionsFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_session_captions, null);
mContainer = (FrameLayout) view.findViewById(R.id.session_caption_container);
if (!UIUtils.isTablet(getActivity())) {
mContainer.setBackgroundColor(Color.WHITE);
}
mNoCaptionsTextView = (TextView) view.findViewById(android.R.id.empty);
mWebView = (WebView) view.findViewById(R.id.session_caption_area);
mWebView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
// Disable text selection in WebView (doesn't work well with the YT player
// triggering full screen chrome after a timeout)
return true;
}
});
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode, String description,
String failingUrl) {
showNoCaptionsAvailable();
}
});
updateViews();
return view;
}
public void setTrackName(String sessionTrack) {
mSessionTrack = sessionTrack;
updateViews();
}
public void setDarkTheme(boolean dark) {
mDarkTheme = dark;
}
@SuppressLint("SetJavaScriptEnabled")
public void updateViews() {
if (mWebView != null && !TextUtils.isEmpty(mSessionTrack)) {
if (mDarkTheme) {
mWebView.setBackgroundColor(Color.BLACK);
mContainer.setBackgroundColor(Color.BLACK);
mNoCaptionsTextView.setTextColor(Color.WHITE);
} else {
mWebView.setBackgroundColor(Color.WHITE);
mContainer.setBackgroundResource(R.drawable.grey_frame_on_white);
}
String captionsUrl;
final String trackLowerCase = mSessionTrack.toLowerCase();
if (mSessionTrack.equals(KEYNOTE_TRACK_NAME)||
trackLowerCase.equals(Config.PRIMARY_LIVESTREAM_TRACK)) {
// if keynote or primary track, use primary captions url
captionsUrl = Config.PRIMARY_LIVESTREAM_CAPTIONS_URL;
} else if (trackLowerCase.equals(Config.SECONDARY_LIVESTREAM_TRACK)) {
// else if secondary track use secondary captions url
captionsUrl = Config.SECONDARY_LIVESTREAM_CAPTIONS_URL;
} else {
// otherwise we don't have captions
captionsUrl = null;
}
if (captionsUrl != null) {
if (mDarkTheme) {
captionsUrl += CAPTIONS_DARK_THEME_URL_PARAM;
}
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(captionsUrl);
mNoCaptionsTextView.setVisibility(View.GONE);
mWebView.setVisibility(View.VISIBLE);
} else {
showNoCaptionsAvailable();
}
}
}
private void showNoCaptionsAvailable() {
mWebView.setVisibility(View.GONE);
mNoCaptionsTextView.setVisibility(View.VISIBLE);
}
}
/*
* Presentation and Media Router methods and classes. This allows use of an externally
* connected display to show video content full screen while still showing the regular views
* on the primary device display.
*/
/**
* Updates the presentation display. If a suitable external display is attached. The video
* will be displayed on that screen instead. If not, the video will be displayed normally.
*/
private void updatePresentation() {
updatePresentation(false);
}
/**
* Updates the presentation display. If a suitable external display is attached. The video
* will be displayed on that screen instead. If not, the video will be displayed normally.
* @param forceDismiss If true, the external display will be dismissed even if it is still
* available. This is useful for if the user wants to explicitly toggle
* the external display off even if it's still connected. Setting this to
* false will adjust the display based on if a suitable external display
* is available or not.
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void updatePresentation(boolean forceDismiss) {
if (!UIUtils.hasJellyBeanMR1()) {
return;
}
// Get the current route and its presentation display
MediaRouter.RouteInfo route =
mMediaRouter.getSelectedRoute(MediaRouter.ROUTE_TYPE_LIVE_VIDEO);
Display presentationDisplay = route != null ? route.getPresentationDisplay() : null;
// Dismiss the current presentation if the display has changed
if (mPresentation != null &&
(mPresentation.getDisplay() != presentationDisplay || forceDismiss)) {
hidePresentation();
}
// Show a new presentation if needed.
if (mPresentation == null && presentationDisplay != null && !forceDismiss) {
showPresentation(presentationDisplay);
}
// Show/hide toggle presentation action item
if (mPresentationMenuItem != null) {
mPresentationMenuItem.setVisible(presentationDisplay != null);
}
}
/**
* Shows the Presentation on the designated Display. Some UI components are also updated:
* a play/pause button is displayed where the video would normally be; the YouTube player style
* is updated to MINIMAL (more suitable for an external display); and an action item is updated
* to indicate the external display is being used.
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void showPresentation(Display presentationDisplay) {
LOGD(TAG, "Showing video presentation on display: " + presentationDisplay);
if (mIsFullscreen) {
if (!mIsTablet) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
if (mYouTubePlayer != null) {
mYouTubePlayer.setFullscreen(false);
}
}
View presentationView = mYouTubeFragment.getView();
((ViewGroup) presentationView.getParent()).removeView(presentationView);
mPresentation = new YouTubePresentation(this, presentationDisplay, presentationView);
mPresentation.setOnDismissListener(mOnDismissListener);
try {
mPresentation.show();
mPresentationControls.setVisibility(View.VISIBLE);
updatePresentationMenuItem(true);
if (mYouTubePlayer != null) {
mYouTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);
mYouTubePlayer.play();
setFullscreenFlags(true);
}
} catch (WindowManager.InvalidDisplayException e) {
LOGE(TAG, "Couldn't show presentation! Display was removed in the meantime.", e);
hidePresentation();
}
}
/**
* Hides the Presentation. Some UI components are also updated:
* the video view is returned to its normal place on the primary display; the YouTube player
* style is updated to the default; and an action item is updated to indicate the external
* display is no longer in use.
*/
private void hidePresentation() {
LOGD(TAG, "Hiding video presentation");
View presentationView = mPresentation.getYouTubeFragmentView();
((ViewGroup) presentationView.getParent()).removeView(presentationView);
mPlayerContainer.addView(presentationView);
mPresentationControls.setVisibility(View.GONE);
updatePresentationMenuItem(false);
mPresentation.dismiss();
mPresentation = null;
if (mYouTubePlayer != null) {
mYouTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
mYouTubePlayer.play();
setFullscreenFlags(false);
}
}
/**
* Updates the presentation action item. Toggles the icon between two drawables to indicate
* if the external display is currently being used or not.
*
* @param enabled If the external display is enabled or not.
*/
private void updatePresentationMenuItem(boolean enabled) {
if (mPresentationMenuItem != null) {
mPresentationMenuItem.setIcon(
enabled ?
R.drawable.ic_media_route_on_holo_light :
R.drawable.ic_media_route_off_holo_light);
}
}
/**
* Applies YouTube player full screen flags. Calls through to
* {@link #setFullscreenFlags(boolean)}.
*/
private void setFullscreenFlags() {
setFullscreenFlags(true);
}
/**
* Applies YouTube player full screen flags plus forces portrait orientation on small screens
* when presentation (secondary display) is enabled (as the full screen layout won't have
* anything to display when an external display is connected).
*
* @param usePresentationMode Whether or not to use presentation mode. This is used when an
* external display is connected and the user toggles between
* presentation mode.
*/
private void setFullscreenFlags(boolean usePresentationMode) {
if (mYouTubePlayer != null) {
if (usePresentationMode && mPresentation != null && !mIsTablet) {
mYouTubePlayer.setFullscreenControlFlags(0);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
mYouTubePlayer.setFullscreenControlFlags(mYouTubeFullscreenFlags);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}
}
/**
* Listens for when the Presentation (which is a type of Dialog) is dismissed.
*/
private final DialogInterface.OnDismissListener mOnDismissListener =
new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
if (dialog == mPresentation) {
LOGD(TAG, "Presentation was dismissed.");
updatePresentation(true);
}
}
};
/**
* The main subclass of Presentation that is used to show content on an externally connected
* display. There is no way to add a {@link android.app.Fragment}, and therefore a
* YouTubePlayerFragment to a {@link android.app.Presentation} (which is just a subclass of
* {@link android.app.Dialog}) so instead we pass in a View directly which is the extracted
* YouTubePlayerView from the {@link SessionLivestreamActivity} YouTubePlayerFragment. Not
* ideal and fairly hacky but there aren't any better alternatives unfortunately.
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private final static class YouTubePresentation extends Presentation {
private View mYouTubeFragmentView;
public YouTubePresentation(Context context, Display display, View presentationView) {
super(context, display);
mYouTubeFragmentView = presentationView;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(mYouTubeFragmentView);
}
public View getYouTubeFragmentView() {
return mYouTubeFragmentView;
}
}
private static class SessionShareData {
String title;
String hashtag;
String sessionUrl;
public SessionShareData(String title, String hashTag, String url) {
this.title = title;
hashtag = hashTag;
sessionUrl = url;
}
}
/**
* Single session query
*/
public interface SessionSummaryQuery {
final static int _TOKEN = 0;
final static String[] PROJECTION = {
ScheduleContract.Sessions.SESSION_ID,
ScheduleContract.Sessions.SESSION_TITLE,
ScheduleContract.Sessions.SESSION_ABSTRACT,
ScheduleContract.Sessions.SESSION_HASHTAGS,
ScheduleContract.Sessions.SESSION_LIVESTREAM_URL,
Tracks.TRACK_NAME,
ScheduleContract.Blocks.BLOCK_START,
ScheduleContract.Blocks.BLOCK_END,
};
final static int ID = 0;
final static int TITLE = 1;
final static int ABSTRACT = 2;
final static int HASHTAGS = 3;
final static int LIVESTREAM_URL = 4;
final static int TRACK_NAME = 5;
final static int BLOCK_START= 6;
final static int BLOCK_END = 7;
}
/**
* List of sessions query
*/
public interface SessionsQuery {
final static int _TOKEN = 1;
final static String[] PROJECTION = {
BaseColumns._ID,
Sessions.SESSION_ID,
Sessions.SESSION_TITLE,
Tracks.TRACK_NAME,
Tracks.TRACK_COLOR,
ScheduleContract.Blocks.BLOCK_START,
ScheduleContract.Blocks.BLOCK_END,
};
final static int _ID = 0;
final static int SESSION_ID = 1;
final static int TITLE = 2;
final static int TRACK_NAME = 3;
final static int TRACK_COLOR = 4;
final static int BLOCK_START= 5;
final static int BLOCK_END = 6;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.ui;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.provider.BaseColumns;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.view.ActionMode;
import android.text.Spannable;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.*;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.PrefUtils;
import com.google.android.apps.iosched.util.SessionsHelper;
import com.google.android.apps.iosched.util.UIUtils;
import java.util.ArrayList;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.*;
import static com.google.android.apps.iosched.util.UIUtils.buildStyledSnippet;
import static com.google.android.apps.iosched.util.UIUtils.formatSessionSubtitle;
/**
* A {@link ListFragment} showing a list of sessions.
*/
public class SessionsFragment extends ListFragment implements
LoaderManager.LoaderCallbacks<Cursor>,
MultiSelectionUtil.MultiChoiceModeListener {
private static final String TAG = makeLogTag(SessionsFragment.class);
private static final String STATE_SELECTED_ID = "selectedId";
private CursorAdapter mAdapter;
private String mSelectedSessionId;
private MenuItem mStarredMenuItem;
private MenuItem mMapMenuItem;
private MenuItem mShareMenuItem;
private MenuItem mSocialStreamMenuItem;
private int mSessionQueryToken;
private Handler mHandler = new Handler();
private MultiSelectionUtil.Controller mMultiSelectionController;
// instance state while view is destroyed but fragment is alive
private Bundle mViewDestroyedInstanceState;
public interface Callbacks {
/** Return true to select (activate) the session in the list, false otherwise. */
public boolean onSessionSelected(String sessionId);
}
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public boolean onSessionSelected(String sessionId) {
return true;
}
};
private Callbacks mCallbacks = sDummyCallbacks;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mSelectedSessionId = savedInstanceState.getString(STATE_SELECTED_ID);
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// As of support library r12, calling initLoader for a fragment in a FragmentPagerAdapter
// in the fragment's onCreate may cause the same LoaderManager to be dealt to multiple
// fragments because their mIndex is -1 (haven't been added to the activity yet). Thus,
// we call reloadFromArguments (which calls restartLoader/initLoader) in onActivityCreated.
reloadFromArguments(getArguments());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list_with_empty_container_inset,
container, false);
TextView emptyView = new TextView(getActivity(), null, R.attr.emptyText);
emptyView.setText(UIUtils.shouldShowLiveSessionsOnly(getActivity())
? R.string.empty_live_streamed_sessions
: R.string.empty_sessions);
((ViewGroup) rootView.findViewById(android.R.id.empty)).addView(emptyView);
mMultiSelectionController = MultiSelectionUtil.attachMultiSelectionController(
(ListView) rootView.findViewById(android.R.id.list),
(ActionBarActivity) getActivity(),
this);
if (savedInstanceState == null && isMenuVisible()) {
savedInstanceState = mViewDestroyedInstanceState;
}
mMultiSelectionController.tryRestoreInstanceState(savedInstanceState);
return rootView;
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (mMultiSelectionController != null) {
mMultiSelectionController.finish();
}
mMultiSelectionController = null;
}
void reloadFromArguments(Bundle arguments) {
// Teardown from previous arguments
setListAdapter(null);
// Load new arguments
final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments);
Uri sessionsUri = intent.getData();
if (sessionsUri == null) {
sessionsUri = ScheduleContract.Sessions.CONTENT_URI;
}
if (!ScheduleContract.Sessions.isSearchUri(sessionsUri)) {
mAdapter = new SessionsAdapter(getActivity());
mSessionQueryToken = SessionsQuery._TOKEN;
} else {
mAdapter = new SearchAdapter(getActivity());
mSessionQueryToken = SearchQuery._TOKEN;
}
setListAdapter(mAdapter);
// Force start background query to load sessions
getLoaderManager().restartLoader(mSessionQueryToken, arguments, this);
}
public void setSelectedSessionId(String id) {
mSelectedSessionId = id;
if (mAdapter != null) {
mAdapter.notifyDataSetChanged();
}
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setBackgroundColor(Color.WHITE);
final ListView listView = getListView();
listView.setSelector(android.R.color.transparent);
listView.setCacheColorHint(Color.WHITE);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof Callbacks)) {
throw new ClassCastException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
activity.getContentResolver().registerContentObserver(
ScheduleContract.Sessions.CONTENT_URI, true, mObserver);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity);
sp.registerOnSharedPreferenceChangeListener(mPrefChangeListener);
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = sDummyCallbacks;
getActivity().getContentResolver().unregisterContentObserver(mObserver);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
sp.unregisterOnSharedPreferenceChangeListener(mPrefChangeListener);
}
@Override
public void onResume() {
super.onResume();
mHandler.post(mRefreshSessionsRunnable);
}
@Override
public void onPause() {
super.onPause();
mHandler.removeCallbacks(mRefreshSessionsRunnable);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mSelectedSessionId != null) {
outState.putString(STATE_SELECTED_ID, mSelectedSessionId);
}
if (mMultiSelectionController != null) {
mMultiSelectionController.saveInstanceState(outState);
}
}
@Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if (mMultiSelectionController == null) {
return;
}
// Hide the action mode when the fragment becomes invisible
if (!menuVisible) {
Bundle bundle = new Bundle();
if (mMultiSelectionController.saveInstanceState(bundle)) {
mViewDestroyedInstanceState = bundle;
mMultiSelectionController.finish();
}
} else if (mViewDestroyedInstanceState != null) {
mMultiSelectionController.tryRestoreInstanceState(mViewDestroyedInstanceState);
mViewDestroyedInstanceState = null;
}
}
/** {@inheritDoc} */
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
final Cursor cursor = (Cursor) mAdapter.getItem(position);
String sessionId = cursor.getString(cursor.getColumnIndex(
ScheduleContract.Sessions.SESSION_ID));
if (mCallbacks.onSessionSelected(sessionId)) {
mSelectedSessionId = sessionId;
mAdapter.notifyDataSetChanged();
}
}
// LoaderCallbacks interface
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle data) {
final Intent intent = BaseActivity.fragmentArgumentsToIntent(data);
Uri sessionsUri = intent.getData();
if (sessionsUri == null) {
sessionsUri = ScheduleContract.Sessions.CONTENT_URI;
}
Loader<Cursor> loader = null;
String liveStreamedOnlySelection = UIUtils.shouldShowLiveSessionsOnly(getActivity())
? "IFNULL(" + ScheduleContract.Sessions.SESSION_LIVESTREAM_URL + ",'')!=''"
: null;
if (id == SessionsQuery._TOKEN) {
loader = new CursorLoader(getActivity(), sessionsUri, SessionsQuery.PROJECTION,
liveStreamedOnlySelection, null, ScheduleContract.Sessions.DEFAULT_SORT);
} else if (id == SearchQuery._TOKEN) {
loader = new CursorLoader(getActivity(), sessionsUri, SearchQuery.PROJECTION,
liveStreamedOnlySelection, null, ScheduleContract.Sessions.DEFAULT_SORT);
}
return loader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (getActivity() == null) {
return;
}
int token = loader.getId();
if (token == SessionsQuery._TOKEN || token == SearchQuery._TOKEN) {
mAdapter.changeCursor(cursor);
Bundle arguments = getArguments();
if (arguments != null && arguments.containsKey("_uri")) {
String uri = arguments.get("_uri").toString();
if(uri != null && uri.contains("blocks")) {
String title = arguments.getString(Intent.EXTRA_TITLE);
if (title == null) {
title = (String) this.getActivity().getTitle();
}
EasyTracker.getTracker().sendView("Session Block: " + title);
LOGD("Tracker", "Session Block: " + title);
}
}
} else {
LOGD(TAG, "Query complete, Not Actionable: " + token);
cursor.close();
}
mMultiSelectionController.tryRestoreInstanceState();
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
private List<Integer> getCheckedSessionPositions() {
List<Integer> checkedSessionPositions = new ArrayList<Integer>();
ListView listView = getListView();
if (listView == null) {
return checkedSessionPositions;
}
SparseBooleanArray checkedPositionsBool = listView.getCheckedItemPositions();
for (int i = 0; i < checkedPositionsBool.size(); i++) {
if (checkedPositionsBool.valueAt(i)) {
checkedSessionPositions.add(checkedPositionsBool.keyAt(i));
}
}
return checkedSessionPositions;
}
// MultiChoiceModeListener interface
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
List<Integer> checkedSessionPositions = getCheckedSessionPositions();
SessionsHelper helper = new SessionsHelper(getActivity());
mode.finish();
switch (item.getItemId()) {
case R.id.menu_map: {
// multiple selection not supported
int position = checkedSessionPositions.get(0);
Cursor cursor = (Cursor) mAdapter.getItem(position);
String roomId = cursor.getString(SessionsQuery.ROOM_ID);
helper.startMapActivity(roomId);
String title = cursor.getString(SessionsQuery.TITLE);
EasyTracker.getTracker().sendEvent(
"Session", "Mapped", title, 0L);
LOGV(TAG, "Starred: " + title);
return true;
}
case R.id.menu_star: {
// multiple selection supported
boolean starred = false;
int numChanged = 0;
for (int position : checkedSessionPositions) {
Cursor cursor = (Cursor) mAdapter.getItem(position);
String title = cursor.getString(SessionsQuery.TITLE);
String sessionId = cursor.getString(SessionsQuery.SESSION_ID);
Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId);
starred = cursor.getInt(SessionsQuery.STARRED) == 0;
helper.setSessionStarred(sessionUri, starred, title);
++numChanged;
EasyTracker.getTracker().sendEvent(
"Session", starred ? "Starred" : "Unstarred", title, 0L);
LOGV(TAG, "Starred: " + title);
}
Toast.makeText(
getActivity(),
getResources().getQuantityString(starred
? R.plurals.toast_added_to_schedule
: R.plurals.toast_removed_from_schedule, numChanged, numChanged),
Toast.LENGTH_SHORT).show();
setSelectedSessionStarred(starred);
return true;
}
case R.id.menu_share: {
// multiple selection not supported
int position = checkedSessionPositions.get(0);
// On ICS+ devices, we normally won't reach this as ShareActionProvider will handle
// sharing.
Cursor cursor = (Cursor) mAdapter.getItem(position);
new SessionsHelper(getActivity()).shareSession(getActivity(),
R.string.share_template,
cursor.getString(SessionsQuery.TITLE),
cursor.getString(SessionsQuery.HASHTAGS),
cursor.getString(SessionsQuery.URL));
return true;
}
case R.id.menu_social_stream:
// multiple selection not supported
int position = checkedSessionPositions.get(0);
Cursor cursor = (Cursor) mAdapter.getItem(position);
String hashtags = cursor.getString(SessionsQuery.HASHTAGS);
helper.startSocialStream(hashtags);
return true;
default:
LOGW(TAG, "CAB unknown selection=" + item.getItemId());
return false;
}
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.sessions_context, menu);
mStarredMenuItem = menu.findItem(R.id.menu_star);
mMapMenuItem = menu.findItem(R.id.menu_map);
mShareMenuItem = menu.findItem(R.id.menu_share);
mSocialStreamMenuItem = menu.findItem(R.id.menu_social_stream);
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
@Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
List<Integer> checkedSessionPositions = getCheckedSessionPositions();
int numSelectedSessions = checkedSessionPositions.size();
mode.setTitle(getResources().getQuantityString(
R.plurals.title_selected_sessions,
numSelectedSessions, numSelectedSessions));
if (numSelectedSessions == 1) {
// activate all the menu items
mMapMenuItem.setVisible(true);
mShareMenuItem.setVisible(true);
mStarredMenuItem.setVisible(true);
position = checkedSessionPositions.get(0);
Cursor cursor = (Cursor) mAdapter.getItem(position);
boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0;
String hashtags = cursor.getString(SessionsQuery.HASHTAGS);
mSocialStreamMenuItem.setVisible(!TextUtils.isEmpty(hashtags));
setSelectedSessionStarred(starred);
} else {
mMapMenuItem.setVisible(false);
mShareMenuItem.setVisible(false);
mSocialStreamMenuItem.setVisible(false);
boolean allStarred = true;
boolean allUnstarred = true;
for (int pos : checkedSessionPositions) {
Cursor cursor = (Cursor) mAdapter.getItem(pos);
boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0;
allStarred = allStarred && starred;
allUnstarred = allUnstarred && !starred;
}
if (allStarred) {
setSelectedSessionStarred(true);
mStarredMenuItem.setVisible(true);
} else if (allUnstarred) {
setSelectedSessionStarred(false);
mStarredMenuItem.setVisible(true);
} else {
mStarredMenuItem.setVisible(false);
}
}
}
private void setSelectedSessionStarred(boolean starred) {
mStarredMenuItem.setTitle(starred
? R.string.description_remove_schedule
: R.string.description_add_schedule);
mStarredMenuItem.setIcon(starred
? R.drawable.ic_action_remove_schedule
: R.drawable.ic_action_add_schedule);
}
private final Runnable mRefreshSessionsRunnable = new Runnable() {
public void run() {
if (mAdapter != null) {
// This is used to refresh session title colors.
mAdapter.notifyDataSetChanged();
}
// Check again on the next quarter hour, with some padding to
// account for network
// time differences.
long nextQuarterHour = (SystemClock.uptimeMillis() / 900000 + 1) * 900000 + 5000;
mHandler.postAtTime(mRefreshSessionsRunnable, nextQuarterHour);
}
};
private final SharedPreferences.OnSharedPreferenceChangeListener mPrefChangeListener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
if (isAdded() && mAdapter != null) {
if (PrefUtils.PREF_LOCAL_TIMES.equals(key)) {
PrefUtils.isUsingLocalTime(getActivity(), true); // force update
mAdapter.notifyDataSetInvalidated();
} else if (PrefUtils.PREF_ATTENDEE_AT_VENUE.equals(key)) {
PrefUtils.isAttendeeAtVenue(getActivity(), true); // force update
mAdapter.notifyDataSetInvalidated();
}
}
}
};
private final ContentObserver mObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange) {
if (!isAdded()) {
return;
}
Loader<Cursor> loader = getLoaderManager().getLoader(mSessionQueryToken);
if (loader != null) {
loader.forceLoad();
}
}
};
/**
* {@link CursorAdapter} that renders a {@link SessionsQuery}.
*/
private class SessionsAdapter extends CursorAdapter {
StringBuilder mBuffer = new StringBuilder();
public SessionsAdapter(Context context) {
super(context, null, 0);
}
/** {@inheritDoc} */
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return getActivity().getLayoutInflater().inflate(R.layout.list_item_session, parent,
false);
}
/** {@inheritDoc} */
@Override
public void bindView(View view, Context context, Cursor cursor) {
String sessionId = cursor.getString(SessionsQuery.SESSION_ID);
if (sessionId == null) {
return;
}
UIUtils.setActivatedCompat(view, sessionId.equals(mSelectedSessionId));
final TextView titleView = (TextView) view.findViewById(R.id.session_title);
final TextView subtitleView = (TextView) view.findViewById(R.id.session_subtitle);
final String sessionTitle = cursor.getString(SessionsQuery.TITLE);
titleView.setText(sessionTitle);
// Format time block this session occupies
final long blockStart = cursor.getLong(SessionsQuery.BLOCK_START);
final long blockEnd = cursor.getLong(SessionsQuery.BLOCK_END);
final String roomName = cursor.getString(SessionsQuery.ROOM_NAME);
final String subtitle = formatSessionSubtitle(
sessionTitle, blockStart, blockEnd, roomName, mBuffer, context);
final boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0;
view.findViewById(R.id.indicator_in_schedule).setVisibility(
starred ? View.VISIBLE : View.INVISIBLE);
final boolean hasLivestream = !TextUtils.isEmpty(
cursor.getString(SessionsQuery.LIVESTREAM_URL));
// Show past/present/future and livestream status for this block.
UIUtils.updateTimeAndLivestreamBlockUI(context,
blockStart, blockEnd, hasLivestream,
titleView, subtitleView, subtitle);
}
}
/**
* {@link CursorAdapter} that renders a {@link SearchQuery}.
*/
private class SearchAdapter extends CursorAdapter {
public SearchAdapter(Context context) {
super(context, null, 0);
}
/** {@inheritDoc} */
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return getActivity().getLayoutInflater().inflate(R.layout.list_item_session, parent,
false);
}
/** {@inheritDoc} */
@Override
public void bindView(View view, Context context, Cursor cursor) {
UIUtils.setActivatedCompat(view, cursor.getString(SessionsQuery.SESSION_ID)
.equals(mSelectedSessionId));
((TextView) view.findViewById(R.id.session_title)).setText(cursor
.getString(SearchQuery.TITLE));
final String snippet = cursor.getString(SearchQuery.SEARCH_SNIPPET);
final Spannable styledSnippet = buildStyledSnippet(snippet);
((TextView) view.findViewById(R.id.session_subtitle)).setText(styledSnippet);
final boolean starred = cursor.getInt(SearchQuery.STARRED) != 0;
view.findViewById(R.id.indicator_in_schedule).setVisibility(
starred ? View.VISIBLE : View.INVISIBLE);
}
}
/**
* {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions}
* query parameters.
*/
private interface SessionsQuery {
int _TOKEN = 0x1;
String[] PROJECTION = {
BaseColumns._ID,
ScheduleContract.Sessions.SESSION_ID,
ScheduleContract.Sessions.SESSION_TITLE,
ScheduleContract.Sessions.SESSION_STARRED,
ScheduleContract.Blocks.BLOCK_START,
ScheduleContract.Blocks.BLOCK_END,
ScheduleContract.Rooms.ROOM_NAME,
ScheduleContract.Rooms.ROOM_ID,
ScheduleContract.Sessions.SESSION_HASHTAGS,
ScheduleContract.Sessions.SESSION_URL,
ScheduleContract.Sessions.SESSION_LIVESTREAM_URL,
};
int _ID = 0;
int SESSION_ID = 1;
int TITLE = 2;
int STARRED = 3;
int BLOCK_START = 4;
int BLOCK_END = 5;
int ROOM_NAME = 6;
int ROOM_ID = 7;
int HASHTAGS = 8;
int URL = 9;
int LIVESTREAM_URL = 10;
}
/**
* {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions}
* search query parameters.
*/
private interface SearchQuery {
int _TOKEN = 0x3;
String[] PROJECTION = {
BaseColumns._ID,
ScheduleContract.Sessions.SESSION_ID,
ScheduleContract.Sessions.SESSION_TITLE,
ScheduleContract.Sessions.SESSION_STARRED,
ScheduleContract.Sessions.SEARCH_SNIPPET,
};
int _ID = 0;
int SESSION_ID = 1;
int TITLE = 2;
int STARRED = 3;
int SEARCH_SNIPPET = 4;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.ui;
import com.google.android.apps.iosched.R;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
/**
* A {@link BaseActivity} that simply contains a single fragment. The intent used to invoke this
* activity is forwarded to the fragment as arguments during fragment instantiation. Derived
* activities should only need to implement {@link SimpleSinglePaneActivity#onCreatePane()}.
*/
public abstract class SimpleSinglePaneActivity extends BaseActivity {
private Fragment mFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentViewResId());
if (getIntent().hasExtra(Intent.EXTRA_TITLE)) {
setTitle(getIntent().getStringExtra(Intent.EXTRA_TITLE));
}
final String customTitle = getIntent().getStringExtra(Intent.EXTRA_TITLE);
setTitle(customTitle != null ? customTitle : getTitle());
if (savedInstanceState == null) {
mFragment = onCreatePane();
mFragment.setArguments(intentToFragmentArguments(getIntent()));
getSupportFragmentManager().beginTransaction()
.add(R.id.root_container, mFragment, "single_pane")
.commit();
} else {
mFragment = getSupportFragmentManager().findFragmentByTag("single_pane");
}
}
protected int getContentViewResId() {
return R.layout.activity_singlepane_empty;
}
/**
* Called in <code>onCreate</code> when the fragment constituting this activity is needed.
* The returned fragment's arguments will be set to the intent used to invoke this activity.
*/
protected abstract Fragment onCreatePane();
public Fragment getFragment() {
return mFragment;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.ui;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.UIUtils;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* A {@link ListFragment} showing a list of sandbox comapnies.
*/
public class SandboxFragment extends ListFragment implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = makeLogTag(SandboxFragment.class);
private static final String STATE_SELECTED_ID = "selectedId";
private Uri mSandboxUri;
private CursorAdapter mAdapter;
private String mSelectedCompanyId;
public interface Callbacks {
/** Return true to select (activate) the company in the list, false otherwise. */
public boolean onCompanySelected(String companyId);
}
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public boolean onCompanySelected(String companyId) {
return true;
}
};
private Callbacks mCallbacks = sDummyCallbacks;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mSelectedCompanyId = savedInstanceState.getString(STATE_SELECTED_ID);
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// As of support library r12, calling initLoader for a fragment in a FragmentPagerAdapter
// in the fragment's onCreate may cause the same LoaderManager to be dealt to multiple
// fragments because their mIndex is -1 (haven't been added to the activity yet). Thus,
// we call reloadFromArguments (which calls restartLoader/initLoader) in onActivityCreated.
reloadFromArguments(getArguments());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list_with_empty_container_inset,
container, false);
TextView emptyView = new TextView(getActivity(), null, R.attr.emptyText);
emptyView.setText(R.string.empty_sandbox);
((ViewGroup) rootView.findViewById(android.R.id.empty)).addView(emptyView);
return rootView;
}
void reloadFromArguments(Bundle arguments) {
// Teardown from previous arguments
setListAdapter(null);
// Load new arguments
final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments);
mSandboxUri = intent.getData();
if (mSandboxUri == null) {
mSandboxUri = ScheduleContract.Sandbox.CONTENT_URI;
}
final int sandboxQueryToken;
mAdapter = new SandboxAdapter(getActivity());
sandboxQueryToken = SandboxQuery._TOKEN;
setListAdapter(mAdapter);
// Start background query to load sandbox
getLoaderManager().initLoader(sandboxQueryToken, null, this);
}
public void setSelectedCompanyId(String id) {
mSelectedCompanyId = id;
if (mAdapter != null) {
mAdapter.notifyDataSetChanged();
}
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.setBackgroundColor(Color.WHITE);
final ListView listView = getListView();
listView.setSelector(android.R.color.transparent);
listView.setCacheColorHint(Color.WHITE);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof Callbacks)) {
throw new ClassCastException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = sDummyCallbacks;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mSelectedCompanyId != null) {
outState.putString(STATE_SELECTED_ID, mSelectedCompanyId);
}
}
/** {@inheritDoc} */
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
final Cursor cursor = (Cursor) mAdapter.getItem(position);
String companyId = cursor.getString(SandboxQuery.COMPANY_ID);
if (mCallbacks.onCompanySelected(companyId)) {
mSelectedCompanyId = companyId;
mAdapter.notifyDataSetChanged();
}
}
/**
* {@link CursorAdapter} that renders a {@link com.google.android.apps.iosched.ui.SandboxFragment.SandboxQuery}.
*/
private class SandboxAdapter extends CursorAdapter {
public SandboxAdapter(Context context) {
super(context, null, 0);
}
/** {@inheritDoc} */
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return getActivity().getLayoutInflater().inflate(R.layout.list_item_sandbox,
parent, false);
}
/** {@inheritDoc} */
@Override
public void bindView(View view, Context context, Cursor cursor) {
UIUtils.setActivatedCompat(view, cursor.getString(SandboxQuery.COMPANY_ID)
.equals(mSelectedCompanyId));
((TextView) view.findViewById(R.id.company_name)).setText(
cursor.getString(SandboxQuery.NAME));
}
}
/**
* {@link com.google.android.apps.iosched.provider.ScheduleContract.Sandbox}
* query parameters.
*/
private interface SandboxQuery {
int _TOKEN = 0x1;
String[] PROJECTION = {
BaseColumns._ID,
ScheduleContract.Sandbox.COMPANY_ID,
ScheduleContract.Sandbox.COMPANY_NAME,
};
int _ID = 0;
int COMPANY_ID = 1;
int NAME = 2;
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle data) {
return new CursorLoader(getActivity(), mSandboxUri, SandboxQuery.PROJECTION, null, null,
ScheduleContract.Sandbox.DEFAULT_SORT);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (getActivity() == null) {
return;
}
int token = loader.getId();
if (token == SandboxQuery._TOKEN) {
mAdapter.changeCursor(cursor);
} else {
cursor.close();
}
}
@Override
public void onLoaderReset(Loader<Cursor> cursor) {
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.ui;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.util.Pair;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.service.SessionAlarmService;
import com.google.android.apps.iosched.ui.widget.ObservableScrollView;
import com.google.android.apps.iosched.util.*;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.plus.PlusClient;
import com.google.android.gms.plus.PlusOneButton;
import java.util.ArrayList;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* A fragment that shows detail information for a session, including session title, abstract,
* time information, speaker photos and bios, etc.
*/
public class SessionDetailFragment extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor>,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
ObservableScrollView.Callbacks {
private static final String TAG = makeLogTag(SessionDetailFragment.class);
// Set this boolean extra to true to show a variable height header
public static final String EXTRA_VARIABLE_HEIGHT_HEADER =
"com.google.android.iosched.extra.VARIABLE_HEIGHT_HEADER";
private Handler mHandler = new Handler();
private String mSessionId;
private Uri mSessionUri;
private long mSessionBlockStart;
private long mSessionBlockEnd;
private String mTitleString;
private String mHashtags;
private String mUrl;
private String mRoomId;
private boolean mStarred;
private boolean mInitStarred;
private MenuItem mStarMenuItem;
private MenuItem mSocialStreamMenuItem;
private MenuItem mShareMenuItem;
private ViewGroup mRootView;
private TextView mTitle;
private TextView mSubtitle;
private PlusClient mPlusClient;
private PlusOneButton mPlusOneButton;
private ObservableScrollView mScrollView;
private CheckableLinearLayout mAddScheduleButton;
private View mAddSchedulePlaceholderView;
private TextView mAbstract;
private TextView mRequirements;
private boolean mSessionCursor = false;
private boolean mSpeakersCursor = false;
private boolean mHasSummaryContent = false;
private boolean mVariableHeightHeader = false;
private ImageLoader mImageLoader;
private List<Runnable> mDeferredUiOperations = new ArrayList<Runnable>();
private StringBuilder mBuffer = new StringBuilder();
private Rect mBufferRect = new Rect();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String chosenAccountName = AccountUtils.getChosenAccountName(getActivity());
mPlusClient = new PlusClient.Builder(getActivity(), this, this)
.clearScopes()
.setAccountName(chosenAccountName)
.build();
final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments());
mSessionUri = intent.getData();
if (mSessionUri == null) {
return;
}
mSessionId = ScheduleContract.Sessions.getSessionId(mSessionUri);
mVariableHeightHeader = intent.getBooleanExtra(EXTRA_VARIABLE_HEIGHT_HEADER, false);
LoaderManager manager = getLoaderManager();
manager.restartLoader(SessionsQuery._TOKEN, null, this);
manager.restartLoader(SpeakersQuery._TOKEN, null, this);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_session_detail, null);
mTitle = (TextView) mRootView.findViewById(R.id.session_title);
mSubtitle = (TextView) mRootView.findViewById(R.id.session_subtitle);
// Larger target triggers plus one button
mPlusOneButton = (PlusOneButton) mRootView.findViewById(R.id.plus_one_button);
View headerView = mRootView.findViewById(R.id.header_session);
FractionalTouchDelegate.setupDelegate(headerView, mPlusOneButton,
new RectF(0.6f, 0f, 1f, 1.0f));
mAbstract = (TextView) mRootView.findViewById(R.id.session_abstract);
mRequirements = (TextView) mRootView.findViewById(R.id.session_requirements);
mAddScheduleButton = (CheckableLinearLayout)
mRootView.findViewById(R.id.add_schedule_button);
mAddScheduleButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
setSessionStarred(!mStarred, true);
}
});
mAddScheduleButton.setVisibility(View.GONE);
if (mVariableHeightHeader) {
ViewGroup.LayoutParams layoutParams = headerView.getLayoutParams();
layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
headerView.setLayoutParams(layoutParams);
}
setupCustomScrolling(mRootView);
return mRootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getActivity() instanceof ImageLoader.ImageLoaderProvider) {
mImageLoader = ((ImageLoader.ImageLoaderProvider) getActivity()).getImageLoaderInstance();
}
}
private void setupCustomScrolling(View rootView) {
mAddSchedulePlaceholderView = rootView.findViewById(
R.id.add_to_schedule_button_placeholder);
if (mAddSchedulePlaceholderView == null) {
mAddScheduleButton.setVisibility(View.VISIBLE);
return;
}
mScrollView = (ObservableScrollView) rootView.findViewById(R.id.scroll_view);
mScrollView.setCallbacks(this);
ViewTreeObserver vto = mScrollView.getViewTreeObserver();
if (vto.isAlive()) {
vto.addOnGlobalLayoutListener(mGlobalLayoutListener);
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (mScrollView == null) {
return;
}
ViewTreeObserver vto = mScrollView.getViewTreeObserver();
if (vto.isAlive()) {
vto.removeGlobalOnLayoutListener(mGlobalLayoutListener);
}
}
private ViewTreeObserver.OnGlobalLayoutListener mGlobalLayoutListener
= new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
onScrollChanged();
mAddScheduleButton.setVisibility(View.VISIBLE);
}
};
@Override
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void onScrollChanged() {
float newTop = Math.max(mAddSchedulePlaceholderView.getTop(), mScrollView.getScrollY());
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams)
mAddScheduleButton.getLayoutParams();
if (UIUtils.hasICS()) {
mAddScheduleButton.setTranslationY(newTop);
} else {
lp.gravity = Gravity.TOP | Gravity.START; // needed for earlier platform versions
lp.topMargin = (int) newTop;
mScrollView.requestLayout();
}
mScrollView.getGlobalVisibleRect(mBufferRect);
int parentLeft = mBufferRect.left;
int parentRight = mBufferRect.right;
if (mAddSchedulePlaceholderView.getGlobalVisibleRect(mBufferRect)) {
lp.leftMargin = mBufferRect.left - parentLeft;
lp.rightMargin = parentRight - mBufferRect.right;
}
mAddScheduleButton.setLayoutParams(lp);
}
@Override
public void onResume() {
super.onResume();
updatePlusOneButton();
}
@Override
public void onStart() {
super.onStart();
mPlusClient.connect();
}
@Override
public void onStop() {
super.onStop();
mPlusClient.disconnect();
if (mInitStarred != mStarred) {
if (mStarred && UIUtils.getCurrentTime(getActivity()) < mSessionBlockStart) {
setupNotification();
}
}
}
@Override
public void onConnected(Bundle connectionHint) {
updatePlusOneButton();
}
@Override
public void onDisconnected() {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Don't show an error just for the +1 button. Google Play services errors
// should be caught at a higher level in the app
}
private void setupNotification() {
// Schedule an alarm that fires a system notification when expires.
final Context context = getActivity();
Intent scheduleIntent = new Intent(
SessionAlarmService.ACTION_SCHEDULE_STARRED_BLOCK,
null, context, SessionAlarmService.class);
scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, mSessionBlockStart);
scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, mSessionBlockEnd);
context.startService(scheduleIntent);
}
/**
* Handle {@link SessionsQuery} {@link Cursor}.
*/
private void onSessionQueryComplete(Cursor cursor) {
mSessionCursor = true;
if (!cursor.moveToFirst()) {
if (isAdded()) {
// TODO: Remove this in favor of a callbacks interface that the activity
// can implement.
getActivity().finish();
}
return;
}
mTitleString = cursor.getString(SessionsQuery.TITLE);
// Format time block this session occupies
mSessionBlockStart = cursor.getLong(SessionsQuery.BLOCK_START);
mSessionBlockEnd = cursor.getLong(SessionsQuery.BLOCK_END);
String roomName = cursor.getString(SessionsQuery.ROOM_NAME);
final String subtitle = UIUtils.formatSessionSubtitle(
mTitleString, mSessionBlockStart, mSessionBlockEnd, roomName, mBuffer,
getActivity());
mTitle.setText(mTitleString);
mUrl = cursor.getString(SessionsQuery.URL);
if (TextUtils.isEmpty(mUrl)) {
mUrl = "";
}
mHashtags = cursor.getString(SessionsQuery.HASHTAGS);
if (!TextUtils.isEmpty(mHashtags)) {
enableSocialStreamMenuItemDeferred();
}
mRoomId = cursor.getString(SessionsQuery.ROOM_ID);
setupShareMenuItemDeferred();
showStarredDeferred(mInitStarred = (cursor.getInt(SessionsQuery.STARRED) != 0), false);
final String sessionAbstract = cursor.getString(SessionsQuery.ABSTRACT);
if (!TextUtils.isEmpty(sessionAbstract)) {
UIUtils.setTextMaybeHtml(mAbstract, sessionAbstract);
mAbstract.setVisibility(View.VISIBLE);
mHasSummaryContent = true;
} else {
mAbstract.setVisibility(View.GONE);
}
updatePlusOneButton();
final View requirementsBlock = mRootView.findViewById(R.id.session_requirements_block);
final String sessionRequirements = cursor.getString(SessionsQuery.REQUIREMENTS);
if (!TextUtils.isEmpty(sessionRequirements)) {
UIUtils.setTextMaybeHtml(mRequirements, sessionRequirements);
requirementsBlock.setVisibility(View.VISIBLE);
mHasSummaryContent = true;
} else {
requirementsBlock.setVisibility(View.GONE);
}
// Show empty message when all data is loaded, and nothing to show
if (mSpeakersCursor && !mHasSummaryContent) {
mRootView.findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
}
// Compile list of links (I/O live link, submit feedback, and normal links)
ViewGroup linkContainer = (ViewGroup) mRootView.findViewById(R.id.links_container);
linkContainer.removeAllViews();
final Context context = mRootView.getContext();
List<Pair<Integer, Intent>> links = new ArrayList<Pair<Integer, Intent>>();
final boolean hasLivestream = !TextUtils.isEmpty(
cursor.getString(SessionsQuery.LIVESTREAM_URL));
long currentTimeMillis = UIUtils.getCurrentTime(context);
if (UIUtils.hasHoneycomb() // Needs Honeycomb+ for the live stream
&& hasLivestream
&& currentTimeMillis > mSessionBlockStart
&& currentTimeMillis <= mSessionBlockEnd) {
links.add(new Pair<Integer, Intent>(
R.string.session_link_livestream,
new Intent(Intent.ACTION_VIEW, mSessionUri)
.setClass(context, SessionLivestreamActivity.class)));
}
// Add session feedback link
links.add(new Pair<Integer, Intent>(
R.string.session_feedback_submitlink,
new Intent(Intent.ACTION_VIEW, mSessionUri, getActivity(), SessionFeedbackActivity.class)
));
for (int i = 0; i < SessionsQuery.LINKS_INDICES.length; i++) {
final String linkUrl = cursor.getString(SessionsQuery.LINKS_INDICES[i]);
if (TextUtils.isEmpty(linkUrl)) {
continue;
}
links.add(new Pair<Integer, Intent>(
SessionsQuery.LINKS_TITLES[i],
new Intent(Intent.ACTION_VIEW, Uri.parse(linkUrl))
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET)
));
}
// Render links
if (links.size() > 0) {
LayoutInflater inflater = LayoutInflater.from(context);
int columns = context.getResources().getInteger(R.integer.links_columns);
LinearLayout currentLinkRowView = null;
for (int i = 0; i < links.size(); i++) {
final Pair<Integer, Intent> link = links.get(i);
// Create link view
TextView linkView = (TextView) inflater.inflate(R.layout.list_item_session_link,
linkContainer, false);
linkView.setText(getString(link.first));
linkView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fireLinkEvent(link.first);
try {
startActivity(link.second);
} catch (ActivityNotFoundException ignored) {
}
}
});
// Place it inside a container
if (columns == 1) {
linkContainer.addView(linkView);
} else {
// create a new link row
if (i % columns == 0) {
currentLinkRowView = (LinearLayout) inflater.inflate(
R.layout.include_link_row, linkContainer, false);
currentLinkRowView.setWeightSum(columns);
linkContainer.addView(currentLinkRowView);
}
((LinearLayout.LayoutParams) linkView.getLayoutParams()).width = 0;
((LinearLayout.LayoutParams) linkView.getLayoutParams()).weight = 1;
currentLinkRowView.addView(linkView);
}
}
mRootView.findViewById(R.id.session_links_header).setVisibility(View.VISIBLE);
mRootView.findViewById(R.id.links_container).setVisibility(View.VISIBLE);
} else {
mRootView.findViewById(R.id.session_links_header).setVisibility(View.GONE);
mRootView.findViewById(R.id.links_container).setVisibility(View.GONE);
}
// Show past/present/future and livestream status for this block.
UIUtils.updateTimeAndLivestreamBlockUI(context,
mSessionBlockStart, mSessionBlockEnd, hasLivestream,
null, mSubtitle, subtitle);
EasyTracker.getTracker().sendView("Session: " + mTitleString);
LOGD("Tracker", "Session: " + mTitleString);
}
private void updatePlusOneButton() {
if (mPlusOneButton == null) {
return;
}
if (mPlusClient.isConnected() && !TextUtils.isEmpty(mUrl)) {
mPlusOneButton.initialize(mPlusClient, mUrl, null);
mPlusOneButton.setVisibility(View.VISIBLE);
} else {
mPlusOneButton.setVisibility(View.GONE);
}
}
private void enableSocialStreamMenuItemDeferred() {
mDeferredUiOperations.add(new Runnable() {
@Override
public void run() {
mSocialStreamMenuItem.setVisible(true);
}
});
tryExecuteDeferredUiOperations();
}
private void showStarredDeferred(final boolean starred, final boolean allowAnimate) {
mDeferredUiOperations.add(new Runnable() {
@Override
public void run() {
showStarred(starred, allowAnimate);
}
});
tryExecuteDeferredUiOperations();
}
private void showStarred(boolean starred, boolean allowAnimate) {
mStarMenuItem.setTitle(starred
? R.string.description_remove_schedule
: R.string.description_add_schedule);
mStarMenuItem.setIcon(starred
? R.drawable.ic_action_remove_schedule
: R.drawable.ic_action_add_schedule);
mStarred = starred;
mAddScheduleButton.setChecked(mStarred);
ImageView iconView = (ImageView) mAddScheduleButton.findViewById(R.id.add_schedule_icon);
setOrAnimateIconTo(iconView, starred
? R.drawable.add_schedule_button_icon_checked
: R.drawable.add_schedule_button_icon_unchecked,
allowAnimate && starred);
TextView textView = (TextView) mAddScheduleButton.findViewById(R.id.add_schedule_text);
textView.setText(starred
? R.string.remove_from_schedule
: R.string.add_to_schedule);
mAddScheduleButton.setContentDescription(getString(starred
? R.string.remove_from_schedule_desc
: R.string.add_to_schedule_desc));
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void setOrAnimateIconTo(final ImageView imageView, final int imageResId,
boolean animate) {
if (UIUtils.hasICS() && imageView.getTag() != null) {
if (imageView.getTag() instanceof Animator) {
Animator anim = (Animator) imageView.getTag();
anim.end();
imageView.setAlpha(1f);
}
}
animate = animate && UIUtils.hasICS();
if (animate) {
int duration = getResources().getInteger(android.R.integer.config_shortAnimTime);
Animator outAnimator = ObjectAnimator.ofFloat(imageView, View.ALPHA, 0f);
outAnimator.setDuration(duration / 2);
outAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
imageView.setImageResource(imageResId);
}
});
AnimatorSet inAnimator = new AnimatorSet();
outAnimator.setDuration(duration);
inAnimator.playTogether(
ObjectAnimator.ofFloat(imageView, View.ALPHA, 1f),
ObjectAnimator.ofFloat(imageView, View.SCALE_X, 0f, 1f),
ObjectAnimator.ofFloat(imageView, View.SCALE_Y, 0f, 1f)
);
AnimatorSet set = new AnimatorSet();
set.playSequentially(outAnimator, inAnimator);
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
imageView.setTag(null);
}
});
imageView.setTag(set);
set.start();
} else {
mHandler.post(new Runnable() {
@Override
public void run() {
imageView.setImageResource(imageResId);
}
});
}
}
private void setupShareMenuItemDeferred() {
mDeferredUiOperations.add(new Runnable() {
@Override
public void run() {
new SessionsHelper(getActivity()).tryConfigureShareMenuItem(mShareMenuItem,
R.string.share_template, mTitleString, mHashtags, mUrl);
}
});
tryExecuteDeferredUiOperations();
}
private void tryExecuteDeferredUiOperations() {
if (mStarMenuItem != null && mSocialStreamMenuItem != null) {
for (Runnable r : mDeferredUiOperations) {
r.run();
}
mDeferredUiOperations.clear();
}
}
private void onSpeakersQueryComplete(Cursor cursor) {
mSpeakersCursor = true;
final ViewGroup speakersGroup = (ViewGroup)
mRootView.findViewById(R.id.session_speakers_block);
// Remove all existing speakers (everything but first child, which is the header)
for (int i = speakersGroup.getChildCount() - 1; i >= 1; i--) {
speakersGroup.removeViewAt(i);
}
final LayoutInflater inflater = getActivity().getLayoutInflater();
boolean hasSpeakers = false;
while (cursor.moveToNext()) {
final String speakerName = cursor.getString(SpeakersQuery.SPEAKER_NAME);
if (TextUtils.isEmpty(speakerName)) {
continue;
}
final String speakerImageUrl = cursor.getString(SpeakersQuery.SPEAKER_IMAGE_URL);
final String speakerCompany = cursor.getString(SpeakersQuery.SPEAKER_COMPANY);
final String speakerUrl = cursor.getString(SpeakersQuery.SPEAKER_URL);
final String speakerAbstract = cursor.getString(SpeakersQuery.SPEAKER_ABSTRACT);
String speakerHeader = speakerName;
if (!TextUtils.isEmpty(speakerCompany)) {
speakerHeader += ", " + speakerCompany;
}
final View speakerView = inflater
.inflate(R.layout.speaker_detail, speakersGroup, false);
final TextView speakerHeaderView = (TextView) speakerView
.findViewById(R.id.speaker_header);
final ImageView speakerImageView = (ImageView) speakerView
.findViewById(R.id.speaker_image);
final TextView speakerAbstractView = (TextView) speakerView
.findViewById(R.id.speaker_abstract);
if (!TextUtils.isEmpty(speakerImageUrl) && mImageLoader != null) {
mImageLoader.get(UIUtils.getConferenceImageUrl(speakerImageUrl), speakerImageView);
}
speakerHeaderView.setText(speakerHeader);
speakerImageView.setContentDescription(
getString(R.string.speaker_googleplus_profile, speakerHeader));
UIUtils.setTextMaybeHtml(speakerAbstractView, speakerAbstract);
if (!TextUtils.isEmpty(speakerUrl)) {
speakerImageView.setEnabled(true);
speakerImageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent speakerProfileIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(speakerUrl));
speakerProfileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
UIUtils.preferPackageForIntent(getActivity(), speakerProfileIntent,
UIUtils.GOOGLE_PLUS_PACKAGE_NAME);
startActivity(speakerProfileIntent);
}
});
} else {
speakerImageView.setEnabled(false);
speakerImageView.setOnClickListener(null);
}
speakersGroup.addView(speakerView);
hasSpeakers = true;
mHasSummaryContent = true;
}
speakersGroup.setVisibility(hasSpeakers ? View.VISIBLE : View.GONE);
// Show empty message when all data is loaded, and nothing to show
if (mSessionCursor && !mHasSummaryContent) {
mRootView.findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.session_detail, menu);
mStarMenuItem = menu.findItem(R.id.menu_star);
mStarMenuItem.setVisible(false); // functionality taken care of by button
mSocialStreamMenuItem = menu.findItem(R.id.menu_social_stream);
mShareMenuItem = menu.findItem(R.id.menu_share);
tryExecuteDeferredUiOperations();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
SessionsHelper helper = new SessionsHelper(getActivity());
switch (item.getItemId()) {
case R.id.menu_map:
EasyTracker.getTracker().sendEvent(
"Session", "Map", mTitleString, 0L);
LOGD("Tracker", "Map: " + mTitleString);
helper.startMapActivity(mRoomId);
return true;
case R.id.menu_star:
setSessionStarred(!mStarred, true);
return true;
case R.id.menu_share:
// On ICS+ devices, we normally won't reach this as ShareActionProvider will handle
// sharing.
helper.shareSession(getActivity(), R.string.share_template, mTitleString,
mHashtags, mUrl);
return true;
case R.id.menu_social_stream:
EasyTracker.getTracker().sendEvent(
"Session", "Stream", mTitleString, 0L);
LOGD("Tracker", "Stream: " + mTitleString);
helper.startSocialStream(mHashtags);
return true;
}
return false;
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
}
@Override
public void onDestroyOptionsMenu() {
}
/*
* Event structure:
* Category -> "Session Details"
* Action -> Link Text
* Label -> Session's Title
* Value -> 0.
*/
void fireLinkEvent(int actionId) {
EasyTracker.getTracker().sendEvent("Session", getString(actionId), mTitleString, 0L);
LOGD("Tracker", getString(actionId) + ": " + mTitleString);
}
void setSessionStarred(boolean star, boolean allowAnimate) {
SessionsHelper helper = new SessionsHelper(getActivity());
showStarred(star, allowAnimate);
helper.setSessionStarred(mSessionUri, star, mTitleString);
EasyTracker.getTracker().sendEvent(
"Session", star ? "Starred" : "Unstarred", mTitleString, 0L);
LOGD("Tracker", (star ? "Starred: " : "Unstarred: ") + mTitleString);
}
/**
* {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} query parameters.
*/
private interface SessionsQuery {
int _TOKEN = 0x1;
String[] PROJECTION = {
ScheduleContract.Blocks.BLOCK_START,
ScheduleContract.Blocks.BLOCK_END,
ScheduleContract.Sessions.SESSION_LEVEL,
ScheduleContract.Sessions.SESSION_TITLE,
ScheduleContract.Sessions.SESSION_ABSTRACT,
ScheduleContract.Sessions.SESSION_REQUIREMENTS,
ScheduleContract.Sessions.SESSION_STARRED,
ScheduleContract.Sessions.SESSION_HASHTAGS,
ScheduleContract.Sessions.SESSION_URL,
ScheduleContract.Sessions.SESSION_YOUTUBE_URL,
ScheduleContract.Sessions.SESSION_PDF_URL,
ScheduleContract.Sessions.SESSION_NOTES_URL,
ScheduleContract.Sessions.SESSION_LIVESTREAM_URL,
ScheduleContract.Sessions.SESSION_MODERATOR_URL,
ScheduleContract.Sessions.ROOM_ID,
ScheduleContract.Rooms.ROOM_NAME,
};
int BLOCK_START = 0;
int BLOCK_END = 1;
int LEVEL = 2;
int TITLE = 3;
int ABSTRACT = 4;
int REQUIREMENTS = 5;
int STARRED = 6;
int HASHTAGS = 7;
int URL = 8;
int YOUTUBE_URL = 9;
int PDF_URL = 10;
int NOTES_URL = 11;
int LIVESTREAM_URL = 12;
int MODERATOR_URL = 13;
int ROOM_ID = 14;
int ROOM_NAME = 15;
int[] LINKS_INDICES = {
URL,
YOUTUBE_URL,
MODERATOR_URL,
PDF_URL,
NOTES_URL,
};
int[] LINKS_TITLES = {
R.string.session_link_main,
R.string.session_link_youtube,
R.string.session_link_moderator,
R.string.session_link_pdf,
R.string.session_link_notes,
};
}
private interface SpeakersQuery {
int _TOKEN = 0x3;
String[] PROJECTION = {
ScheduleContract.Speakers.SPEAKER_NAME,
ScheduleContract.Speakers.SPEAKER_IMAGE_URL,
ScheduleContract.Speakers.SPEAKER_COMPANY,
ScheduleContract.Speakers.SPEAKER_ABSTRACT,
ScheduleContract.Speakers.SPEAKER_URL,
};
int SPEAKER_NAME = 0;
int SPEAKER_IMAGE_URL = 1;
int SPEAKER_COMPANY = 2;
int SPEAKER_ABSTRACT = 3;
int SPEAKER_URL = 4;
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle data) {
CursorLoader loader = null;
if (id == SessionsQuery._TOKEN){
loader = new CursorLoader(getActivity(), mSessionUri, SessionsQuery.PROJECTION, null,
null, null);
} else if (id == SpeakersQuery._TOKEN && mSessionUri != null){
Uri speakersUri = ScheduleContract.Sessions.buildSpeakersDirUri(mSessionId);
loader = new CursorLoader(getActivity(), speakersUri, SpeakersQuery.PROJECTION, null,
null, null);
}
return loader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (!isAdded()) {
return;
}
if (loader.getId() == SessionsQuery._TOKEN) {
onSessionQueryComplete(cursor);
} else if (loader.getId() == SpeakersQuery._TOKEN) {
onSpeakersQueryComplete(cursor);
} else {
cursor.close();
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.ui;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.ShareCompat;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.*;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.Config;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.util.ImageLoader;
import com.google.android.apps.iosched.util.NetUtils;
import com.google.android.apps.iosched.util.UIUtils;
import com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.plus.Plus;
import com.google.api.services.plus.model.Activity;
import com.google.api.services.plus.model.ActivityFeed;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* A fragment that renders Google+ search results for a given query, provided as the
* {@link SocialStreamFragment#EXTRA_QUERY} extra in the fragment arguments. If no
* search query is provided, the conference hashtag is used as the default query.
*/
public class SocialStreamFragment extends ListFragment implements
AbsListView.OnScrollListener,
LoaderManager.LoaderCallbacks<List<Activity>> {
private static final String TAG = makeLogTag(SocialStreamFragment.class);
public static final String EXTRA_QUERY = "com.google.android.apps.iosched.extra.QUERY";
public static final String EXTRA_ADD_VERTICAL_MARGINS
= "com.google.android.apps.iosched.extra.ADD_VERTICAL_MARGINS";
private static final String STATE_POSITION = "position";
private static final String STATE_TOP = "top";
private static final long MAX_RESULTS_PER_REQUEST = 20;
private static final String PLUS_RESULT_FIELDS =
"nextPageToken,items(id,annotation,updated,url,verb,actor(displayName,image)," +
"object(actor/displayName,attachments(displayName,image/url,objectType," +
"thumbnails(image/url,url),url),content,plusoners/totalItems,replies/totalItems," +
"resharers/totalItems))";
private static final int STREAM_LOADER_ID = 0;
private String mSearchString;
private List<Activity> mStream = new ArrayList<Activity>();
private StreamAdapter mStreamAdapter = new StreamAdapter();
private int mListViewStatePosition;
private int mListViewStateTop;
private ImageLoader mImageLoader;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments());
// mSearchString can be populated before onCreate() by called refresh(String)
if (TextUtils.isEmpty(mSearchString)) {
mSearchString = intent.getStringExtra(EXTRA_QUERY);
}
if (TextUtils.isEmpty(mSearchString)) {
mSearchString = UIUtils.CONFERENCE_HASHTAG;
}
if (!mSearchString.startsWith("#")) {
mSearchString = "#" + mSearchString;
}
mImageLoader =
PlusStreamRowViewBinder.getPlusStreamImageLoader(getActivity(), getResources());
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
mListViewStatePosition = savedInstanceState.getInt(STATE_POSITION, -1);
mListViewStateTop = savedInstanceState.getInt(STATE_TOP, 0);
} else {
mListViewStatePosition = -1;
mListViewStateTop = 0;
}
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setEmptyText(getString(R.string.empty_social_stream));
// In support library r8, calling initLoader for a fragment in a FragmentPagerAdapter
// in the fragment's onCreate may cause the same LoaderManager to be dealt to multiple
// fragments because their mIndex is -1 (haven't been added to the activity yet). Thus,
// we do this in onActivityCreated.
getLoaderManager().initLoader(STREAM_LOADER_ID, null, this);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final ListView listView = getListView();
if (!UIUtils.isTablet(getActivity())) {
view.setBackgroundColor(getResources().getColor(R.color.plus_stream_spacer_color));
}
if (getArguments() != null
&& getArguments().getBoolean(EXTRA_ADD_VERTICAL_MARGINS, false)) {
int verticalMargin = getResources().getDimensionPixelSize(
R.dimen.plus_stream_padding_vertical);
if (verticalMargin > 0) {
listView.setClipToPadding(false);
listView.setPadding(0, verticalMargin, 0, verticalMargin);
}
}
listView.setOnScrollListener(this);
listView.setDrawSelectorOnTop(true);
listView.setDivider(getResources().getDrawable(android.R.color.transparent));
listView.setDividerHeight(getResources()
.getDimensionPixelSize(R.dimen.page_margin_width));
TypedValue v = new TypedValue();
getActivity().getTheme().resolveAttribute(R.attr.activatableItemBackground, v, true);
listView.setSelector(v.resourceId);
setListAdapter(mStreamAdapter);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.social_stream, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_compose:
Intent intent = ShareCompat.IntentBuilder.from(getActivity())
.setType("text/plain")
.setText(mSearchString + "\n\n")
.getIntent();
UIUtils.preferPackageForIntent(getActivity(), intent,
UIUtils.GOOGLE_PLUS_PACKAGE_NAME);
startActivity(intent);
EasyTracker.getTracker().sendEvent("Home Screen Dashboard", "Click", "Post to G+", 0L);
LOGD("Tracker", "Home Screen Dashboard: Click, post to g+");
return true;
}
return false;
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
}
@Override
public void onDestroyOptionsMenu() {
}
@Override
public void onSaveInstanceState(Bundle outState) {
if (isAdded()) {
View v = getListView().getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
outState.putInt(STATE_POSITION, getListView().getFirstVisiblePosition());
outState.putInt(STATE_TOP, top);
}
super.onSaveInstanceState(outState);
}
public void refresh(String newQuery) {
mSearchString = newQuery;
refresh(true);
}
public void refresh() {
refresh(false);
}
public void refresh(boolean forceRefresh) {
if (isStreamLoading() && !forceRefresh) {
return;
}
// clear current items
mStream.clear();
mStreamAdapter.notifyDataSetInvalidated();
if (isAdded()) {
Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID);
((StreamLoader) loader).init(mSearchString);
}
loadMoreResults();
}
public void loadMoreResults() {
if (isAdded()) {
Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID);
if (loader != null) {
loader.forceLoad();
}
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
Activity activity = mStream.get(position);
Intent postDetailIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(activity.getUrl()));
postDetailIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
UIUtils.preferPackageForIntent(getActivity(), postDetailIntent,
UIUtils.GOOGLE_PLUS_PACKAGE_NAME);
startActivity(postDetailIntent);
}
@Override
public void onScrollStateChanged(AbsListView listView, int scrollState) {
// Pause disk cache access to ensure smoother scrolling
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
mImageLoader.stopProcessingQueue();
} else {
mImageLoader.startProcessingQueue();
}
}
@Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
if (!isStreamLoading()
&& streamHasMoreResults()
&& visibleItemCount != 0
&& firstVisibleItem + visibleItemCount >= totalItemCount - 1) {
loadMoreResults();
}
}
@Override
public Loader<List<Activity>> onCreateLoader(int id, Bundle args) {
return new StreamLoader(getActivity(), mSearchString);
}
@Override
public void onLoadFinished(Loader<List<Activity>> listLoader, List<Activity> activities) {
if (activities != null) {
mStream = activities;
}
mStreamAdapter.notifyDataSetChanged();
if (mListViewStatePosition != -1 && isAdded()) {
getListView().setSelectionFromTop(mListViewStatePosition, mListViewStateTop);
mListViewStatePosition = -1;
}
}
@Override
public void onLoaderReset(Loader<List<Activity>> listLoader) {
}
private boolean isStreamLoading() {
if (isAdded()) {
final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID);
if (loader != null) {
return ((StreamLoader) loader).isLoading();
}
}
return true;
}
private boolean streamHasMoreResults() {
if (isAdded()) {
final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID);
if (loader != null) {
return ((StreamLoader) loader).hasMoreResults();
}
}
return false;
}
private boolean streamHasError() {
if (isAdded()) {
final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID);
if (loader != null) {
return ((StreamLoader) loader).hasError();
}
}
return false;
}
private static class StreamLoader extends AsyncTaskLoader<List<Activity>> {
List<Activity> mActivities;
private String mSearchString;
private String mNextPageToken;
private boolean mIsLoading;
private boolean mHasError;
public StreamLoader(Context context, String searchString) {
super(context);
init(searchString);
}
private void init(String searchString) {
mSearchString = searchString;
mHasError = false;
mNextPageToken = null;
mIsLoading = true;
mActivities = null;
}
@Override
public List<Activity> loadInBackground() {
mIsLoading = true;
// Set up the HTTP transport and JSON factory
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new GsonFactory();
// Set up the main Google+ class
Plus plus = new Plus.Builder(httpTransport, jsonFactory, null)
.setApplicationName(NetUtils.getUserAgent(getContext()))
.setGoogleClientRequestInitializer(
new CommonGoogleClientRequestInitializer(Config.API_KEY))
.build();
ActivityFeed activities = null;
try {
activities = plus.activities().search(mSearchString)
.setPageToken(mNextPageToken)
.setOrderBy("recent")
.setMaxResults(MAX_RESULTS_PER_REQUEST)
.setFields(PLUS_RESULT_FIELDS)
.execute();
mHasError = false;
mNextPageToken = activities.getNextPageToken();
} catch (IOException e) {
e.printStackTrace();
mHasError = true;
mNextPageToken = null;
}
return (activities != null) ? activities.getItems() : null;
}
@Override
public void deliverResult(List<Activity> activities) {
mIsLoading = false;
if (activities != null) {
if (mActivities == null) {
mActivities = activities;
} else {
mActivities.addAll(activities);
}
}
if (isStarted()) {
// Need to return new ArrayList for some reason or onLoadFinished() is not called
super.deliverResult(mActivities == null ?
null : new ArrayList<Activity>(mActivities));
}
}
@Override
protected void onStartLoading() {
if (mActivities != null) {
// If we already have results and are starting up, deliver what we already have.
deliverResult(null);
} else {
forceLoad();
}
}
@Override
protected void onStopLoading() {
mIsLoading = false;
cancelLoad();
}
@Override
protected void onReset() {
super.onReset();
onStopLoading();
mActivities = null;
}
public boolean isLoading() {
return mIsLoading;
}
public boolean hasMoreResults() {
return mNextPageToken != null;
}
public boolean hasError() {
return mHasError;
}
public void setSearchString(String searchString) {
mSearchString = searchString;
}
public void refresh() {
reset();
startLoading();
}
}
private class StreamAdapter extends BaseAdapter {
private static final int VIEW_TYPE_ACTIVITY = 0;
private static final int VIEW_TYPE_LOADING = 1;
@Override
public boolean areAllItemsEnabled() {
return false;
}
@Override
public boolean isEnabled(int position) {
return getItemViewType(position) == VIEW_TYPE_ACTIVITY;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public int getCount() {
return mStream.size() + (
// show the status list row if...
((isStreamLoading() && mStream.size() == 0) // ...this is the first load
|| streamHasMoreResults() // ...or there's another page
|| streamHasError()) // ...or there's an error
? 1 : 0);
}
@Override
public int getItemViewType(int position) {
return (position >= mStream.size())
? VIEW_TYPE_LOADING
: VIEW_TYPE_ACTIVITY;
}
@Override
public Object getItem(int position) {
return (getItemViewType(position) == VIEW_TYPE_ACTIVITY)
? mStream.get(position)
: null;
}
@Override
public long getItemId(int position) {
// TODO: better unique ID heuristic
return (getItemViewType(position) == VIEW_TYPE_ACTIVITY)
? mStream.get(position).getId().hashCode()
: -1;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (getItemViewType(position) == VIEW_TYPE_LOADING) {
if (convertView == null) {
convertView = getLayoutInflater(null).inflate(
R.layout.list_item_stream_status, parent, false);
}
if (streamHasError()) {
convertView.findViewById(android.R.id.progress).setVisibility(View.GONE);
((TextView) convertView.findViewById(android.R.id.text1)).setText(
R.string.stream_error);
} else {
convertView.findViewById(android.R.id.progress).setVisibility(View.VISIBLE);
((TextView) convertView.findViewById(android.R.id.text1)).setText(
R.string.loading);
}
return convertView;
} else {
Activity activity = (Activity) getItem(position);
if (convertView == null) {
convertView = getLayoutInflater(null).inflate(
R.layout.list_item_stream_activity, parent, false);
}
PlusStreamRowViewBinder.bindActivityView(convertView, activity, mImageLoader,
false);
return convertView;
}
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.ui;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
/**
* A retained, non-UI helper fragment that loads track information such as name, color, etc.
*/
public class TrackInfoHelperFragment extends ListFragment implements
LoaderManager.LoaderCallbacks<Cursor> {
/**
* The track URI for which to load data.
*/
private static final String ARG_TRACK = "com.google.android.iosched.extra.TRACK";
private Uri mTrackUri;
// To be loaded
private String mTrackId;
private TrackInfo mInfo = new TrackInfo();
private Handler mHandler = new Handler();
public interface Callbacks {
public void onTrackInfoAvailable(String trackId, TrackInfo info);
}
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public void onTrackInfoAvailable(String trackId, TrackInfo info) {
}
};
private Callbacks mCallbacks = sDummyCallbacks;
public static TrackInfoHelperFragment newFromSessionUri(Uri sessionUri) {
return newFromTrackUri(ScheduleContract.Sessions.buildTracksDirUri(
ScheduleContract.Sessions.getSessionId(sessionUri)));
}
public static TrackInfoHelperFragment newFromTrackUri(Uri trackUri) {
TrackInfoHelperFragment f = new TrackInfoHelperFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_TRACK, trackUri);
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
mTrackUri = getArguments().getParcelable(ARG_TRACK);
if (ScheduleContract.Tracks.ALL_TRACK_ID.equals(
ScheduleContract.Tracks.getTrackId(mTrackUri))) {
mTrackId = ScheduleContract.Tracks.ALL_TRACK_ID;
mInfo.name = getString(R.string.all_tracks);
mInfo.color = 0;
mInfo.meta = ScheduleContract.Tracks.TRACK_META_NONE;
mInfo.level = 1;
mInfo.hashtag = "";
mCallbacks.onTrackInfoAvailable(mTrackId, mInfo);
} else {
getLoaderManager().initLoader(0, null, this);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof Callbacks)) {
throw new ClassCastException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
if (mTrackId != null) {
mHandler.post(new Runnable() {
@Override
public void run() {
mCallbacks.onTrackInfoAvailable(mTrackId, mInfo);
}
});
}
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = sDummyCallbacks;
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle data) {
return new CursorLoader(getActivity(), mTrackUri, TracksQuery.PROJECTION, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
try {
if (!cursor.moveToFirst()) {
return;
}
mTrackId = cursor.getString(TracksQuery.TRACK_ID);
mInfo.name = cursor.getString(TracksQuery.TRACK_NAME);
mInfo.color = cursor.getInt(TracksQuery.TRACK_COLOR);
mInfo.trackAbstract = cursor.getString(TracksQuery.TRACK_ABSTRACT);
mInfo.level = cursor.getInt(TracksQuery.TRACK_LEVEL);
mInfo.meta = cursor.getInt(TracksQuery.TRACK_META);
mInfo.hashtag = cursor.getString(TracksQuery.TRACK_HASHTAG);
// Wrapping in a Handler.post allows users of this helper to commit fragment
// transactions in the callback.
new Handler().post(new Runnable() {
@Override
public void run() {
mCallbacks.onTrackInfoAvailable(mTrackId, mInfo);
}
});
} finally {
cursor.close();
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
/**
* {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks} query parameters.
*/
private interface TracksQuery {
String[] PROJECTION = {
ScheduleContract.Tracks.TRACK_ID,
ScheduleContract.Tracks.TRACK_NAME,
ScheduleContract.Tracks.TRACK_COLOR,
ScheduleContract.Tracks.TRACK_ABSTRACT,
ScheduleContract.Tracks.TRACK_LEVEL,
ScheduleContract.Tracks.TRACK_META,
ScheduleContract.Tracks.TRACK_HASHTAG,
};
int TRACK_ID = 0;
int TRACK_NAME = 1;
int TRACK_COLOR = 2;
int TRACK_ABSTRACT = 3;
int TRACK_LEVEL = 4;
int TRACK_META = 5;
int TRACK_HASHTAG = 6;
}
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* 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 com.google.android.apps.iosched.ui;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.ImageLoader;
import com.google.android.apps.iosched.util.UIUtils;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.plus.model.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* A fragment that shows announcements.
*/
public class AnnouncementsFragment extends ListFragment implements
AbsListView.OnScrollListener, LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = makeLogTag(AnnouncementsFragment.class);
public static final String EXTRA_ADD_VERTICAL_MARGINS
= "com.google.android.apps.iosched.extra.ADD_VERTICAL_MARGINS";
private static final String STATE_POSITION = "position";
private static final String STATE_TOP = "top";
private Cursor mCursor;
private StreamAdapter mStreamAdapter;
private int mListViewStatePosition;
private int mListViewStateTop;
private ImageLoader mImageLoader;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mImageLoader =
PlusStreamRowViewBinder.getPlusStreamImageLoader(getActivity(), getResources());
mCursor = null;
mStreamAdapter = new StreamAdapter(getActivity());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
mListViewStatePosition = savedInstanceState.getInt(STATE_POSITION, -1);
mListViewStateTop = savedInstanceState.getInt(STATE_TOP, 0);
} else {
mListViewStatePosition = -1;
mListViewStateTop = 0;
}
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setEmptyText(getString(R.string.empty_announcements));
getLoaderManager().initLoader(0, null, this);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final ListView listView = getListView();
if (!UIUtils.isTablet(getActivity())) {
view.setBackgroundColor(getResources().getColor(R.color.plus_stream_spacer_color));
}
if (getArguments() != null
&& getArguments().getBoolean(EXTRA_ADD_VERTICAL_MARGINS, false)) {
int verticalMargin = getResources().getDimensionPixelSize(
R.dimen.plus_stream_padding_vertical);
if (verticalMargin > 0) {
listView.setClipToPadding(false);
listView.setPadding(0, verticalMargin, 0, verticalMargin);
}
}
listView.setOnScrollListener(this);
listView.setDrawSelectorOnTop(true);
listView.setDivider(getResources().getDrawable(android.R.color.transparent));
listView.setDividerHeight(getResources()
.getDimensionPixelSize(R.dimen.page_margin_width));
TypedValue v = new TypedValue();
getActivity().getTheme().resolveAttribute(R.attr.activatableItemBackground, v, true);
listView.setSelector(v.resourceId);
setListAdapter(mStreamAdapter);
}
@Override
public void onSaveInstanceState(Bundle outState) {
if (isAdded()) {
View v = getListView().getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
outState.putInt(STATE_POSITION, getListView().getFirstVisiblePosition());
outState.putInt(STATE_TOP, top);
}
super.onSaveInstanceState(outState);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
if (mCursor == null) {
return;
}
mCursor.moveToPosition(position);
String url = mCursor.getString(AnnouncementsQuery.ANNOUNCEMENT_URL);
Intent postDetailIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
postDetailIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
UIUtils.preferPackageForIntent(getActivity(), postDetailIntent,
UIUtils.GOOGLE_PLUS_PACKAGE_NAME);
startActivity(postDetailIntent);
}
@Override
public void onScrollStateChanged(AbsListView listView, int scrollState) {
// Pause disk cache access to ensure smoother scrolling
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
mImageLoader.stopProcessingQueue();
} else {
mImageLoader.startProcessingQueue();
}
}
@Override
public void onScroll(AbsListView absListView, int i, int i2, int i3) {
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getActivity(), ScheduleContract.Announcements.CONTENT_URI,
AnnouncementsQuery.PROJECTION, null, null,
ScheduleContract.Announcements.DEFAULT_SORT);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
mCursor = cursor;
mStreamAdapter.changeCursor(mCursor);
mStreamAdapter.notifyDataSetChanged();
if (mListViewStatePosition != -1 && isAdded()) {
getListView().setSelectionFromTop(mListViewStatePosition, mListViewStateTop);
mListViewStatePosition = -1;
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
private class StreamAdapter extends CursorAdapter {
private JsonFactory mFactory = new GsonFactory();
private Map<Long, Activity> mActivityCache = new HashMap<Long, Activity>();
public StreamAdapter(Context context) {
super(context, null, 0);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup container) {
return LayoutInflater.from(getActivity()).inflate(
R.layout.list_item_stream_activity, container, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
long id = cursor.getLong(AnnouncementsQuery._ID);
String activityJson = cursor.getString(AnnouncementsQuery.ANNOUNCEMENT_ACTIVITY_JSON);
Activity activity = mActivityCache.get(id);
// TODO: this should be async
if (activity == null) {
try {
activity = mFactory.fromString(activityJson, Activity.class);
} catch (IOException e) {
LOGE(TAG, "Couldn't parse activity JSON: " + activityJson, e);
}
mActivityCache.put(id, activity);
}
PlusStreamRowViewBinder.bindActivityView(view, activity, mImageLoader, true);
}
}
private interface AnnouncementsQuery {
String[] PROJECTION = {
ScheduleContract.Announcements._ID,
ScheduleContract.Announcements.ANNOUNCEMENT_ACTIVITY_JSON,
ScheduleContract.Announcements.ANNOUNCEMENT_URL,
};
int _ID = 0;
int ANNOUNCEMENT_ACTIVITY_JSON = 1;
int ANNOUNCEMENT_URL = 2;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.ui;
import android.accounts.Account;
import android.annotation.TargetApi;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SyncStatusObserver;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SearchView;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.Config;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.gcm.ServerUtilities;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.sync.SyncHelper;
import com.google.android.apps.iosched.util.*;
import com.google.android.gcm.GCMRegistrar;
import com.google.android.gms.auth.GoogleAuthUtil;
import static com.google.android.apps.iosched.util.LogUtils.*;
public class HomeActivity extends BaseActivity implements
ActionBar.TabListener,
ViewPager.OnPageChangeListener {
private static final String TAG = makeLogTag(HomeActivity.class);
public static final String EXTRA_DEFAULT_TAB
= "com.google.android.apps.iosched.extra.DEFAULT_TAB";
public static final String TAB_EXPLORE = "explore";
private Object mSyncObserverHandle;
private SocialStreamFragment mSocialStreamFragment;
private ViewPager mViewPager;
private Menu mOptionsMenu;
private AsyncTask<Void, Void, Void> mGCMRegisterTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (isFinishing()) {
return;
}
UIUtils.enableDisableActivitiesByFormFactor(this);
setContentView(R.layout.activity_home);
FragmentManager fm = getSupportFragmentManager();
mViewPager = (ViewPager) findViewById(R.id.pager);
String homeScreenLabel;
if (mViewPager != null) {
// Phone setup
mViewPager.setAdapter(new HomePagerAdapter(getSupportFragmentManager()));
mViewPager.setOnPageChangeListener(this);
mViewPager.setPageMarginDrawable(R.drawable.grey_border_inset_lr);
mViewPager.setPageMargin(getResources()
.getDimensionPixelSize(R.dimen.page_margin_width));
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab()
.setText(R.string.title_my_schedule)
.setTabListener(this));
actionBar.addTab(actionBar.newTab()
.setText(R.string.title_explore)
.setTabListener(this));
actionBar.addTab(actionBar.newTab()
.setText(R.string.title_stream)
.setTabListener(this));
setHasTabs();
if (getIntent() != null
&& TAB_EXPLORE.equals(getIntent().getStringExtra(EXTRA_DEFAULT_TAB))
&& savedInstanceState == null) {
mViewPager.setCurrentItem(1);
}
homeScreenLabel = getString(R.string.title_my_schedule);
} else {
mSocialStreamFragment = (SocialStreamFragment) fm.findFragmentById(R.id.fragment_stream);
homeScreenLabel = "Home";
}
getSupportActionBar().setHomeButtonEnabled(false);
EasyTracker.getTracker().sendView(homeScreenLabel);
LOGD("Tracker", homeScreenLabel);
// Sync data on load
if (savedInstanceState == null) {
registerGCMClient();
}
}
private void registerGCMClient() {
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
final String regId = GCMRegistrar.getRegistrationId(this);
if (TextUtils.isEmpty(regId)) {
// Automatically registers application on startup.
GCMRegistrar.register(this, Config.GCM_SENDER_ID);
} else {
// Device is already registered on GCM, needs to check if it is
// registered on our server as well.
if (ServerUtilities.isRegisteredOnServer(this)) {
// Skips registration.
LOGI(TAG, "Already registered on the C2DM server");
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
mGCMRegisterTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
boolean registered = ServerUtilities.register(HomeActivity.this, regId);
// At this point all attempts to register with the app
// server failed, so we need to unregister the device
// from GCM - the app will try to register again when
// it is restarted. Note that GCM will send an
// unregistered callback upon completion, but
// GCMIntentService.onUnregistered() will ignore it.
if (!registered) {
GCMRegistrar.unregister(HomeActivity.this);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
mGCMRegisterTask = null;
}
};
mGCMRegisterTask.execute(null, null, null);
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mGCMRegisterTask != null) {
mGCMRegisterTask.cancel(true);
}
try {
GCMRegistrar.onDestroy(this);
} catch (Exception e) {
LOGW(TAG, "C2DM unregistration error", e);
}
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int position) {
getSupportActionBar().setSelectedNavigationItem(position);
int titleId = -1;
switch (position) {
case 0:
titleId = R.string.title_my_schedule;
break;
case 1:
titleId = R.string.title_explore;
break;
case 2:
titleId = R.string.title_stream;
break;
}
String title = getString(titleId);
EasyTracker.getTracker().sendView(title);
LOGD("Tracker", title);
}
@Override
public void onPageScrollStateChanged(int i) {
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Since the pager fragments don't have known tags or IDs, the only way to persist the
// reference is to use putFragment/getFragment. Remember, we're not persisting the exact
// Fragment instance. This mechanism simply gives us a way to persist access to the
// 'current' fragment instance for the given fragment (which changes across orientation
// changes).
//
// The outcome of all this is that the "Refresh" menu button refreshes the stream across
// orientation changes.
if (mSocialStreamFragment != null) {
getSupportFragmentManager().putFragment(outState, "stream_fragment",
mSocialStreamFragment);
}
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (mSocialStreamFragment == null) {
mSocialStreamFragment = (SocialStreamFragment) getSupportFragmentManager()
.getFragment(savedInstanceState, "stream_fragment");
}
}
private class HomePagerAdapter extends FragmentPagerAdapter {
public HomePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ScheduleFragment();
case 1:
return new ExploreFragment();
case 2:
return (mSocialStreamFragment = new SocialStreamFragment());
}
return null;
}
@Override
public int getCount() {
return 3;
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
mOptionsMenu = menu;
getMenuInflater().inflate(R.menu.home, menu);
MenuItem searchItem = menu.findItem(R.id.menu_search);
if (searchItem != null && UIUtils.hasHoneycomb()) {
SearchView searchView = (SearchView) searchItem.getActionView();
if (searchView != null) {
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setQueryRefinementEnabled(true);
}
}
MenuItem wifiItem = menu.findItem(R.id.menu_wifi);
if (!PrefUtils.isAttendeeAtVenue(this) ||
(WiFiUtils.isWiFiEnabled(this) && WiFiUtils.isWiFiApConfigured(this))) {
wifiItem.setVisible(false);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_refresh:
triggerRefresh();
return true;
case R.id.menu_search:
if (!UIUtils.hasHoneycomb()) {
startSearch(null, false, Bundle.EMPTY, false);
return true;
}
break;
case R.id.menu_about:
HelpUtils.showAbout(this);
return true;
case R.id.menu_wifi:
WiFiUtils.showWiFiDialog(this);
return true;
case R.id.menu_settings:
startActivity(new Intent(this, SettingsActivity.class));
return true;
case R.id.menu_sign_out:
AccountUtils.signOut(this);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private void triggerRefresh() {
SyncHelper.requestManualSync(AccountUtils.getChosenAccount(this));
if (mSocialStreamFragment != null) {
mSocialStreamFragment.refresh();
}
}
@Override
protected void onPause() {
super.onPause();
if (mSyncObserverHandle != null) {
ContentResolver.removeStatusChangeListener(mSyncObserverHandle);
mSyncObserverHandle = null;
}
}
@Override
protected void onResume() {
super.onResume();
mSyncStatusObserver.onStatusChanged(0);
// Watch for sync state changes
final int mask = ContentResolver.SYNC_OBSERVER_TYPE_PENDING |
ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE;
mSyncObserverHandle = ContentResolver.addStatusChangeListener(mask, mSyncStatusObserver);
// Set up conference WiFi AP if requested by user.
WiFiUtils.installWiFiIfRequested(this);
// Refresh options menu. Menu item visibility could be altered by user preferences.
supportInvalidateOptionsMenu();
}
void setRefreshActionButtonState(boolean refreshing) {
if (mOptionsMenu == null) {
return;
}
final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_refresh);
if (refreshItem != null) {
if (refreshing) {
MenuItemCompat.setActionView(refreshItem, R.layout.actionbar_indeterminate_progress);
} else {
MenuItemCompat.setActionView(refreshItem, null);
}
}
}
private SyncStatusObserver mSyncStatusObserver = new SyncStatusObserver() {
@Override
public void onStatusChanged(int which) {
runOnUiThread(new Runnable() {
@Override
public void run() {
String accountName = AccountUtils.getChosenAccountName(HomeActivity.this);
if (TextUtils.isEmpty(accountName)) {
setRefreshActionButtonState(false);
return;
}
Account account = new Account(accountName, GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
boolean syncActive = ContentResolver.isSyncActive(
account, ScheduleContract.CONTENT_AUTHORITY);
boolean syncPending = ContentResolver.isSyncPending(
account, ScheduleContract.CONTENT_AUTHORITY);
setRefreshActionButtonState(syncActive || syncPending);
}
});
}
};
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.ui;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.HomeActivity;
import com.google.android.apps.iosched.ui.SessionFeedbackFragment;
import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity;
import com.google.android.apps.iosched.ui.TrackInfo;
import com.google.android.apps.iosched.ui.TrackInfoHelperFragment;
import com.google.android.apps.iosched.util.BeamUtils;
public class SessionFeedbackActivity extends SimpleSinglePaneActivity implements
TrackInfoHelperFragment.Callbacks {
private String mSessionId = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
Uri sessionUri = getIntent().getData();
BeamUtils.setBeamSessionUri(this, sessionUri);
getSupportFragmentManager().beginTransaction()
.add(TrackInfoHelperFragment.newFromSessionUri(sessionUri),
"track_info")
.commit();
}
mSessionId = ScheduleContract.Sessions.getSessionId(getIntent().getData());
}
@Override
protected int getContentViewResId() {
return R.layout.activity_letterboxed_when_large;
}
@Override
protected Fragment onCreatePane() {
return new SessionFeedbackFragment();
}
@Override
public Intent getParentActivityIntent() {
// Up to this session's track details, or Home if no track is available
if (mSessionId != null) {
return new Intent(Intent.ACTION_VIEW,
ScheduleContract.Sessions.buildSessionUri(mSessionId));
} else {
return new Intent(this, HomeActivity.class);
}
}
@Override
public void onTrackInfoAvailable(String trackId, TrackInfo track) {
setTitle(track.name);
setActionBarTrackIcon(track.name, track.color);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.ui;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Rect;
import android.provider.BaseColumns;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.CursorAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.BitmapCache;
import com.google.android.apps.iosched.util.UIUtils;
/**
* A {@link android.widget.CursorAdapter} that renders a {@link TracksQuery}.
*/
public class TracksAdapter extends CursorAdapter {
private static final int ALL_ITEM_ID = Integer.MAX_VALUE;
private static final int LEVEL_2_SECTION_HEADER_ITEM_ID = ALL_ITEM_ID - 1;
private Activity mActivity;
private boolean mHasAllItem;
private int mFirstLevel2CursorPosition = -1;
private BitmapCache mBitmapCache;
private boolean mIsDropDown;
public TracksAdapter(FragmentActivity activity, boolean isDropDown) {
super(activity, null, 0);
mActivity = activity;
mIsDropDown = isDropDown;
// Fetch track icon size in pixels.
int trackIconSize =
activity.getResources().getDimensionPixelSize(R.dimen.track_icon_source_size);
// Cache size is total pixels by 4 bytes (as format is ARGB_8888) by 20 (max icons to hold
// in the cache) converted to KB.
int cacheSize = trackIconSize * trackIconSize * 4 * 20 / 1024;
// Create a BitmapCache to hold the track icons.
mBitmapCache = BitmapCache.getInstance(activity.getSupportFragmentManager(),
UIUtils.TRACK_ICONS_TAG, cacheSize);
}
@Override
public void changeCursor(Cursor cursor) {
updateSpecialItemPositions(cursor);
super.changeCursor(cursor);
}
@Override
public Cursor swapCursor(Cursor newCursor) {
updateSpecialItemPositions(newCursor);
return super.swapCursor(newCursor);
}
public void setHasAllItem(boolean hasAllItem) {
mHasAllItem = hasAllItem;
updateSpecialItemPositions(getCursor());
}
private void updateSpecialItemPositions(Cursor cursor) {
mFirstLevel2CursorPosition = -1;
if (cursor != null && !cursor.isClosed()) {
cursor.moveToFirst();
while (cursor.moveToNext()) {
if (cursor.getInt(TracksQuery.TRACK_LEVEL) == 2) {
mFirstLevel2CursorPosition = cursor.getPosition();
break;
}
}
}
}
public boolean isAllTracksItem(int position) {
return mHasAllItem && position == 0;
}
public boolean isLevel2Header(int position) {
return mFirstLevel2CursorPosition >= 0
&& position - (mHasAllItem ? 1 : 0) == mFirstLevel2CursorPosition;
}
public int adapterPositionToCursorPosition(int position) {
position -= (mHasAllItem ? 1 : 0);
if (mFirstLevel2CursorPosition >= 0 && position > mFirstLevel2CursorPosition) {
--position;
}
return position;
}
@Override
public int getCount() {
int superCount = super.getCount();
if (superCount == 0) {
return 0;
}
return superCount
+ (mFirstLevel2CursorPosition >= 0 ? 1 : 0)
+ (mHasAllItem ? 1 : 0);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (isAllTracksItem(position)) {
if (convertView == null) {
convertView = mActivity.getLayoutInflater().inflate(
R.layout.list_item_track, parent, false);
}
// Custom binding for the first item
((TextView) convertView.findViewById(android.R.id.text1)).setText(
"(" + mActivity.getResources().getString(R.string.all_tracks) + ")");
convertView.findViewById(android.R.id.icon1).setVisibility(View.INVISIBLE);
return convertView;
} else if (isLevel2Header(position)) {
TextView view = (TextView) convertView;
if (view == null) {
view = (TextView) mActivity.getLayoutInflater().inflate(
R.layout.list_item_track_header, parent, false);
if (mIsDropDown) {
Rect r = new Rect(view.getPaddingLeft(), view.getPaddingTop(),
view.getPaddingRight(), view.getPaddingBottom());
view.setBackgroundResource(R.drawable.track_header_bottom_border);
view.setPadding(r.left, r.top, r.right, r.bottom);
}
}
view.setText(R.string.other_tracks);
return view;
}
return super.getView(adapterPositionToCursorPosition(position), convertView, parent);
}
@Override
public Object getItem(int position) {
if (isAllTracksItem(position) || isLevel2Header(position)) {
return null;
}
return super.getItem(adapterPositionToCursorPosition(position));
}
@Override
public long getItemId(int position) {
if (isAllTracksItem(position)) {
return ALL_ITEM_ID;
} else if (isLevel2Header(position)) {
return LEVEL_2_SECTION_HEADER_ITEM_ID;
}
return super.getItemId(adapterPositionToCursorPosition(position));
}
@Override
public boolean areAllItemsEnabled() {
return false;
}
@Override
public boolean isEnabled(int position) {
return position < (mHasAllItem ? 1 : 0)
|| !isLevel2Header(position)
&& super.isEnabled(adapterPositionToCursorPosition(position));
}
@Override
public int getViewTypeCount() {
// Add an item type for the "All" item and section header.
return super.getViewTypeCount() + 2;
}
@Override
public int getItemViewType(int position) {
if (isAllTracksItem(position)) {
return getViewTypeCount() - 1;
} else if (isLevel2Header(position)) {
return getViewTypeCount() - 2;
}
return super.getItemViewType(adapterPositionToCursorPosition(position));
}
/** {@inheritDoc} */
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return mActivity.getLayoutInflater().inflate(R.layout.list_item_track, parent,
false);
}
/** {@inheritDoc} */
@Override
public void bindView(View view, Context context, Cursor cursor) {
String trackName = cursor.getString(TracksQuery.TRACK_NAME);
final TextView textView = (TextView) view.findViewById(android.R.id.text1);
textView.setText(trackName);
// Assign track color and icon to visible block
final ImageView iconView = (ImageView) view.findViewById(android.R.id.icon1);
new UIUtils.TrackIconViewAsyncTask(iconView, trackName,
cursor.getInt(TracksQuery.TRACK_COLOR), mBitmapCache).execute(context);
}
/** {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks} query parameters. */
public interface TracksQuery {
int _TOKEN = 0x1;
String[] PROJECTION = {
BaseColumns._ID,
ScheduleContract.Tracks.TRACK_ID,
ScheduleContract.Tracks.TRACK_NAME,
ScheduleContract.Tracks.TRACK_ABSTRACT,
ScheduleContract.Tracks.TRACK_COLOR,
ScheduleContract.Tracks.TRACK_LEVEL,
ScheduleContract.Tracks.TRACK_META,
};
String[] PROJECTION_WITH_SESSIONS_COUNT = {
BaseColumns._ID,
ScheduleContract.Tracks.TRACK_ID,
ScheduleContract.Tracks.TRACK_NAME,
ScheduleContract.Tracks.TRACK_ABSTRACT,
ScheduleContract.Tracks.TRACK_COLOR,
ScheduleContract.Tracks.TRACK_LEVEL,
ScheduleContract.Tracks.TRACK_META,
ScheduleContract.Tracks.SESSIONS_COUNT,
};
String[] PROJECTION_WITH_OFFICE_HOURS_COUNT = {
BaseColumns._ID,
ScheduleContract.Tracks.TRACK_ID,
ScheduleContract.Tracks.TRACK_NAME,
ScheduleContract.Tracks.TRACK_ABSTRACT,
ScheduleContract.Tracks.TRACK_COLOR,
ScheduleContract.Tracks.TRACK_LEVEL,
ScheduleContract.Tracks.TRACK_META,
ScheduleContract.Tracks.OFFICE_HOURS_COUNT,
};
String[] PROJECTION_WITH_SANDBOX_COUNT = {
BaseColumns._ID,
ScheduleContract.Tracks.TRACK_ID,
ScheduleContract.Tracks.TRACK_NAME,
ScheduleContract.Tracks.TRACK_ABSTRACT,
ScheduleContract.Tracks.TRACK_COLOR,
ScheduleContract.Tracks.TRACK_LEVEL,
ScheduleContract.Tracks.TRACK_META,
ScheduleContract.Tracks.SANDBOX_COUNT,
};
int _ID = 0;
int TRACK_ID = 1;
int TRACK_NAME = 2;
int TRACK_ABSTRACT = 3;
int TRACK_COLOR = 4;
int TRACK_LEVEL = 5;
int TRACK_META = 6;
}
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* 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 com.google.android.apps.iosched.ui.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;
/**
* A custom ScrollView that can accept a scroll listener.
*/
public class ObservableScrollView extends ScrollView {
private Callbacks mCallbacks;
public ObservableScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (mCallbacks != null) {
mCallbacks.onScrollChanged();
}
}
@Override
public int computeVerticalScrollRange() {
return super.computeVerticalScrollRange();
}
public void setCallbacks(Callbacks listener) {
mCallbacks = listener;
}
public static interface Callbacks {
public void onScrollChanged();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.ui.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Checkable;
import android.widget.FrameLayout;
public class CheckableFrameLayout extends FrameLayout implements Checkable {
private boolean mChecked;
public CheckableFrameLayout(Context context) {
super(context);
}
public CheckableFrameLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CheckableFrameLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
private static final int[] CheckedStateSet = {
android.R.attr.state_checked
};
@Override
public boolean isChecked() {
return mChecked;
}
@Override
public void setChecked(boolean checked) {
mChecked = checked;
refreshDrawableState();
}
@Override
public void toggle() {
setChecked(!mChecked);
}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked()) {
mergeDrawableStates(drawableState, CheckedStateSet);
}
return drawableState;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.ui.widget;
import com.google.android.apps.iosched.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.widget.ImageView;
/**
* An {@link android.widget.ImageView} that draws its contents inside a mask and draws a border
* drawable on top. This is useful for applying a beveled look to image contents, but is also
* flexible enough for use with other desired aesthetics.
*/
public class BezelImageView extends ImageView {
private Paint mBlackPaint;
private Paint mMaskedPaint;
private Rect mBounds;
private RectF mBoundsF;
private Drawable mBorderDrawable;
private Drawable mMaskDrawable;
private ColorMatrixColorFilter mDesaturateColorFilter;
private boolean mDesaturateOnPress = false;
private boolean mCacheValid = false;
private Bitmap mCacheBitmap;
private int mCachedWidth;
private int mCachedHeight;
public BezelImageView(Context context) {
this(context, null);
}
public BezelImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BezelImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Attribute initialization
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BezelImageView,
defStyle, 0);
mMaskDrawable = a.getDrawable(R.styleable.BezelImageView_maskDrawable);
if (mMaskDrawable != null) {
mMaskDrawable.setCallback(this);
}
mBorderDrawable = a.getDrawable(R.styleable.BezelImageView_borderDrawable);
if (mBorderDrawable != null) {
mBorderDrawable.setCallback(this);
}
mDesaturateOnPress = a.getBoolean(R.styleable.BezelImageView_desaturateOnPress,
mDesaturateOnPress);
a.recycle();
// Other initialization
mBlackPaint = new Paint();
mBlackPaint.setColor(0xff000000);
mMaskedPaint = new Paint();
mMaskedPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
// Always want a cache allocated.
mCacheBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
if (mDesaturateOnPress) {
// Create a desaturate color filter for pressed state.
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
mDesaturateColorFilter = new ColorMatrixColorFilter(cm);
}
}
@Override
protected boolean setFrame(int l, int t, int r, int b) {
final boolean changed = super.setFrame(l, t, r, b);
mBounds = new Rect(0, 0, r - l, b - t);
mBoundsF = new RectF(mBounds);
if (mBorderDrawable != null) {
mBorderDrawable.setBounds(mBounds);
}
if (mMaskDrawable != null) {
mMaskDrawable.setBounds(mBounds);
}
if (changed) {
mCacheValid = false;
}
return changed;
}
@Override
protected void onDraw(Canvas canvas) {
if (mBounds == null) {
return;
}
int width = mBounds.width();
int height = mBounds.height();
if (width == 0 || height == 0) {
return;
}
if (!mCacheValid || width != mCachedWidth || height != mCachedHeight) {
// Need to redraw the cache
if (width == mCachedWidth && height == mCachedHeight) {
// Have a correct-sized bitmap cache already allocated. Just erase it.
mCacheBitmap.eraseColor(0);
} else {
// Allocate a new bitmap with the correct dimensions.
mCacheBitmap.recycle();
//noinspection AndroidLintDrawAllocation
mCacheBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mCachedWidth = width;
mCachedHeight = height;
}
Canvas cacheCanvas = new Canvas(mCacheBitmap);
if (mMaskDrawable != null) {
int sc = cacheCanvas.save();
mMaskDrawable.draw(cacheCanvas);
mMaskedPaint.setColorFilter((mDesaturateOnPress && isPressed())
? mDesaturateColorFilter : null);
cacheCanvas.saveLayer(mBoundsF, mMaskedPaint,
Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG);
super.onDraw(cacheCanvas);
cacheCanvas.restoreToCount(sc);
} else if (mDesaturateOnPress && isPressed()) {
int sc = cacheCanvas.save();
cacheCanvas.drawRect(0, 0, mCachedWidth, mCachedHeight, mBlackPaint);
mMaskedPaint.setColorFilter(mDesaturateColorFilter);
cacheCanvas.saveLayer(mBoundsF, mMaskedPaint,
Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG);
super.onDraw(cacheCanvas);
cacheCanvas.restoreToCount(sc);
} else {
super.onDraw(cacheCanvas);
}
if (mBorderDrawable != null) {
mBorderDrawable.draw(cacheCanvas);
}
}
// Draw from cache
canvas.drawBitmap(mCacheBitmap, mBounds.left, mBounds.top, null);
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
if (mBorderDrawable != null && mBorderDrawable.isStateful()) {
mBorderDrawable.setState(getDrawableState());
}
if (mMaskDrawable != null && mMaskDrawable.isStateful()) {
mMaskDrawable.setState(getDrawableState());
}
if (isDuplicateParentStateEnabled()) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
@Override
public void invalidateDrawable(Drawable who) {
if (who == mBorderDrawable || who == mMaskDrawable) {
invalidate();
} else {
super.invalidateDrawable(who);
}
}
@Override
protected boolean verifyDrawable(Drawable who) {
return who == mBorderDrawable || who == mMaskDrawable || super.verifyDrawable(who);
}
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* 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 com.google.android.apps.iosched.ui.widget;
import com.google.android.apps.iosched.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* A simple {@link TextView} subclass that uses {@link TextUtils#ellipsize(CharSequence,
* android.text.TextPaint, float, android.text.TextUtils.TruncateAt, boolean,
* android.text.TextUtils.EllipsizeCallback)} to truncate the displayed text. This is used in
* {@link com.google.android.apps.iosched.ui.PlusStreamRowViewBinder} when displaying G+ post text
* which is converted from HTML to a {@link android.text.SpannableString} and sometimes causes
* issues for the built-in TextView ellipsize function.
*/
public class EllipsizedTextView extends TextView {
private static final int MAX_ELLIPSIZE_LINES = 100;
private int mMaxLines;
public EllipsizedTextView(Context context) {
this(context, null, 0);
}
public EllipsizedTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public EllipsizedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Attribute initialization
final TypedArray a = context.obtainStyledAttributes(attrs, new int[]{
android.R.attr.maxLines
}, defStyle, 0);
mMaxLines = a.getInteger(0, 1);
a.recycle();
}
@Override
public void setText(CharSequence text, BufferType type) {
CharSequence newText = getWidth() == 0 || mMaxLines > MAX_ELLIPSIZE_LINES ? text :
TextUtils.ellipsize(text, getPaint(), getWidth() * mMaxLines,
TextUtils.TruncateAt.END, false, null);
super.setText(newText, type);
}
@Override
protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
super.onSizeChanged(width, height, oldWidth, oldHeight);
if (width > 0 && oldWidth != width) {
setText(getText());
}
}
@Override
public void setMaxLines(int maxlines) {
super.setMaxLines(maxlines);
mMaxLines = maxlines;
}
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* 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 com.google.android.apps.iosched.ui;
public class TrackInfo {
public String id;
public String name;
public int color;
public String trackAbstract;
public int level;
public int meta;
public String hashtag;
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* 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 com.google.android.apps.iosched.ui;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import java.io.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.util.Log;
import com.google.android.gms.maps.model.Tile;
import com.google.android.gms.maps.model.TileProvider;
import com.larvalabs.svgandroid.SVG;
import com.larvalabs.svgandroid.SVGParser;
public class SVGTileProvider implements TileProvider {
private static final String TAG = makeLogTag(SVGTileProvider.class);
private static final int POOL_MAX_SIZE = 5;
private static final int BASE_TILE_SIZE = 256;
private final TileGeneratorPool mPool;
private final Matrix mBaseMatrix;
private final int mScale;
private final int mDimension;
private byte[] mSvgFile;
public SVGTileProvider(File file, float dpi) throws IOException {
mScale = Math.round(dpi + .3f); // Make it look nice on N7 (1.3 dpi)
mDimension = BASE_TILE_SIZE * mScale;
mPool = new TileGeneratorPool(POOL_MAX_SIZE);
mSvgFile = readFile(file);
RectF limits = SVGParser.getSVGFromInputStream(new ByteArrayInputStream(mSvgFile)).getLimits();
mBaseMatrix = new Matrix();
mBaseMatrix.setPolyToPoly(
new float[]{
0, 0,
limits.width(), 0,
limits.width(), limits.height()
}, 0,
new float[]{
40.95635986328125f, 98.94217824936158f,
40.95730018615723f, 98.94123077396628f,
40.95791244506836f, 98.94186019897214f
}, 0, 3);
}
@Override
public Tile getTile(int x, int y, int zoom) {
TileGenerator tileGenerator = mPool.get();
byte[] tileData = tileGenerator.getTileImageData(x, y, zoom);
mPool.restore(tileGenerator);
return new Tile(mDimension, mDimension, tileData);
}
private class TileGeneratorPool {
private final ConcurrentLinkedQueue<TileGenerator> mPool = new ConcurrentLinkedQueue<TileGenerator>();
private final int mMaxSize;
private TileGeneratorPool(int maxSize) {
mMaxSize = maxSize;
}
public TileGenerator get() {
TileGenerator i = mPool.poll();
if (i == null) {
return new TileGenerator();
}
return i;
}
public void restore(TileGenerator tileGenerator) {
if (mPool.size() < mMaxSize && mPool.offer(tileGenerator)) {
return;
}
// pool is too big or returning to pool failed, so just try to clean
// up.
tileGenerator.cleanUp();
}
}
public class TileGenerator {
private Bitmap mBitmap;
private SVG mSvg;
private ByteArrayOutputStream mStream;
public TileGenerator() {
mBitmap = Bitmap.createBitmap(mDimension, mDimension, Bitmap.Config.ARGB_8888);
mStream = new ByteArrayOutputStream(mDimension * mDimension * 4);
mSvg = SVGParser.getSVGFromInputStream(new ByteArrayInputStream(mSvgFile));
}
public byte[] getTileImageData(int x, int y, int zoom) {
mStream.reset();
Matrix matrix = new Matrix(mBaseMatrix);
float scale = (float) (Math.pow(2, zoom) * mScale);
matrix.postScale(scale, scale);
matrix.postTranslate(-x * mDimension, -y * mDimension);
mBitmap.eraseColor(Color.TRANSPARENT);
Canvas c = new Canvas(mBitmap);
c.setMatrix(matrix);
mSvg.getPicture().draw(c);
BufferedOutputStream stream = new BufferedOutputStream(mStream);
mBitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
try {
stream.close();
} catch (IOException e) {
Log.e(TAG, "Error while closing tile byte stream.");
e.printStackTrace();
}
return mStream.toByteArray();
}
/**
* Attempt to free memory and remove references.
*/
public void cleanUp() {
mBitmap.recycle();
mBitmap = null;
mSvg = null;
try {
mStream.close();
} catch (IOException e) {
// ignore
}
mStream = null;
}
}
private static byte[] readFile(File file) throws IOException {
InputStream in = new BufferedInputStream(new FileInputStream(file));
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int n;
while ((n = in.read(buffer)) != -1) {
baos.write(buffer, 0, n);
}
return baos.toByteArray();
} finally {
in.close();
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.ui;
import android.annotation.TargetApi;
import android.app.SearchManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.Html;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SearchView;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.util.BeamUtils;
import com.google.android.apps.iosched.util.ImageLoader;
import com.google.android.apps.iosched.util.ReflectionUtils;
import com.google.android.apps.iosched.util.UIUtils;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
/**
* An activity that shows session search results. This activity can be either single
* or multi-pane, depending on the device configuration.
*/
public class SearchActivity extends BaseActivity implements
SessionsFragment.Callbacks,
ImageLoader.ImageLoaderProvider {
private boolean mTwoPane;
private SessionsFragment mSessionsFragment;
private Fragment mDetailFragment;
private ImageLoader mImageLoader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mTwoPane = (findViewById(R.id.fragment_container_detail) != null);
FragmentManager fm = getSupportFragmentManager();
mSessionsFragment = (SessionsFragment) fm.findFragmentById(R.id.fragment_container_master);
if (mSessionsFragment == null) {
mSessionsFragment = new SessionsFragment();
fm.beginTransaction()
.add(R.id.fragment_container_master, mSessionsFragment)
.commit();
}
mDetailFragment = fm.findFragmentById(R.id.fragment_container_detail);
mImageLoader = new ImageLoader(this, R.drawable.person_image_empty)
.setMaxImageSize(getResources().getDimensionPixelSize(R.dimen.speaker_image_size))
.setFadeInImage(UIUtils.hasHoneycombMR1());
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
onNewIntent(getIntent());
}
@Override
public void onNewIntent(Intent intent) {
setIntent(intent);
String query = intent.getStringExtra(SearchManager.QUERY);
setTitle(Html.fromHtml(getString(R.string.title_search_query, query)));
mSessionsFragment.reloadFromArguments(intentToFragmentArguments(
new Intent(Intent.ACTION_VIEW, Sessions.buildSearchUri(query))));
EasyTracker.getTracker().sendView("Search: " + query);
LOGD("Tracker", "Search: " + query);
updateDetailBackground();
}
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.search, menu);
final MenuItem searchItem = menu.findItem(R.id.menu_search);
if (searchItem != null && UIUtils.hasHoneycomb()) {
SearchView searchView = (SearchView) searchItem.getActionView();
if (searchView != null) {
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setQueryRefinementEnabled(true);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
ReflectionUtils.tryInvoke(searchItem, "collapseActionView");
return false;
}
@Override
public boolean onQueryTextChange(String s) {
return false;
}
});
searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
@Override
public boolean onSuggestionSelect(int i) {
return false;
}
@Override
public boolean onSuggestionClick(int i) {
ReflectionUtils.tryInvoke(searchItem, "collapseActionView");
return false;
}
});
}
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_search:
if (!UIUtils.hasHoneycomb()) {
startSearch(null, false, Bundle.EMPTY, false);
return true;
}
break;
}
return super.onOptionsItemSelected(item);
}
private void updateDetailBackground() {
if (mTwoPane) {
findViewById(R.id.fragment_container_detail).setBackgroundResource(
(mDetailFragment == null)
? R.drawable.grey_frame_on_white_empty_sessions
: R.drawable.grey_frame_on_white);
}
}
@Override
public boolean onSessionSelected(String sessionId) {
Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId);
Intent detailIntent = new Intent(Intent.ACTION_VIEW, sessionUri);
if (mTwoPane) {
BeamUtils.setBeamSessionUri(this, sessionUri);
SessionDetailFragment fragment = new SessionDetailFragment();
fragment.setArguments(BaseActivity.intentToFragmentArguments(detailIntent));
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container_detail, fragment)
.commit();
mDetailFragment = fragment;
updateDetailBackground();
return true;
} else {
startActivity(detailIntent);
return false;
}
}
@Override
public ImageLoader getImageLoaderInstance() {
return mImageLoader;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.ui;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.sync.SyncHelper;
import com.google.android.apps.iosched.util.AccountUtils;
import com.google.android.apps.iosched.util.PrefUtils;
import com.google.android.apps.iosched.util.WiFiUtils;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.plus.PlusClient;
import com.google.android.gms.plus.model.people.Person;
import java.util.Arrays;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
public class AccountActivity extends ActionBarActivity
implements AccountUtils.AuthenticateCallback, GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, PlusClient.OnPersonLoadedListener {
private static final String TAG = makeLogTag(AccountActivity.class);
public static final String EXTRA_FINISH_INTENT
= "com.google.android.iosched.extra.FINISH_INTENT";
private static final int SETUP_ATTENDEE = 1;
private static final int SETUP_WIFI = 2;
private static final String KEY_CHOSEN_ACCOUNT = "chosen_account";
private static final int REQUEST_AUTHENTICATE = 100;
private static final int REQUEST_RECOVER_FROM_AUTH_ERROR = 101;
private static final int REQUEST_RECOVER_FROM_PLAY_SERVICES_ERROR = 102;
private static final int REQUEST_PLAY_SERVICES_ERROR_DIALOG = 103;
private static final String POST_AUTH_CATEGORY
= "com.google.android.iosched.category.POST_AUTH";
private Account mChosenAccount;
private Intent mFinishIntent;
private boolean mCancelAuth = false;
private boolean mAuthInProgress = false;
private boolean mAuthProgressFragmentResumed = false;
private boolean mCanRemoveAuthProgressFragment = false;
private PlusClient mPlusClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_letterboxed_when_large);
final Intent intent = getIntent();
if (intent.hasExtra(EXTRA_FINISH_INTENT)) {
mFinishIntent = intent.getParcelableExtra(EXTRA_FINISH_INTENT);
}
if (savedInstanceState == null) {
if (!AccountUtils.isAuthenticated(this)) {
getSupportFragmentManager().beginTransaction()
.add(R.id.root_container, new SignInMainFragment(), "signin_main")
.commit();
} else {
mChosenAccount = new Account(AccountUtils.getChosenAccountName(this), "com.google");
getSupportFragmentManager().beginTransaction()
.add(R.id.root_container,
SignInSetupFragment.makeFragment(SETUP_ATTENDEE), "setup_attendee")
.commit();
}
} else {
String accountName = savedInstanceState.getString(KEY_CHOSEN_ACCOUNT);
if (accountName != null) {
mChosenAccount = new Account(accountName, "com.google");
mPlusClient = (new PlusClient.Builder(this, this, this))
.setAccountName(accountName)
.setScopes(AccountUtils.AUTH_SCOPES)
.build();
}
}
}
@Override
public void onRecoverableException(final int code) {
runOnUiThread(new Runnable() {
@Override
public void run() {
final Dialog d = GooglePlayServicesUtil.getErrorDialog(
code,
AccountActivity.this,
REQUEST_RECOVER_FROM_PLAY_SERVICES_ERROR);
d.show();
}
});
}
@Override
public void onUnRecoverableException(final String errorMessage) {
LOGW(TAG, "Encountered unrecoverable exception: " + errorMessage);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
if (mChosenAccount != null)
outState.putString(KEY_CHOSEN_ACCOUNT, mChosenAccount.name);
super.onSaveInstanceState(outState);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_AUTHENTICATE ||
requestCode == REQUEST_RECOVER_FROM_AUTH_ERROR ||
requestCode == REQUEST_PLAY_SERVICES_ERROR_DIALOG) {
if (resultCode == RESULT_OK) {
if (mPlusClient != null) mPlusClient.connect();
} else {
if (mAuthProgressFragmentResumed) {
runOnUiThread(new Runnable() {
@Override
public void run() {
getSupportFragmentManager().popBackStack();
}
});
} else {
mCanRemoveAuthProgressFragment = true;
}
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public void onStop() {
super.onStop();
if (mAuthInProgress) mCancelAuth = true;
if (mPlusClient != null)
mPlusClient.disconnect();
}
@Override
public void onPersonLoaded(ConnectionResult connectionResult, Person person) {
if (connectionResult.isSuccess()) {
// Se the profile id
if (person != null) {
AccountUtils.setPlusProfileId(this, person.getId());
}
} else {
LOGE(TAG, "Got " + connectionResult.getErrorCode() + ". Could not load plus profile.");
}
}
public static class SignInMainFragment extends Fragment {
public SignInMainFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_login_main, container, false);
TextView descriptionTextView = (TextView) rootView.findViewById(
R.id.sign_in_description);
descriptionTextView.setText(Html.fromHtml(getString(R.string.description_sign_in_main)));
SignInButton signinButtonView = (SignInButton) rootView.findViewById(R.id.sign_in_button);
signinButtonView.setSize(SignInButton.SIZE_WIDE);
signinButtonView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.root_container, new ChooseAccountFragment(),
"choose_account")
.addToBackStack("signin_main")
.commit();
}
});
return rootView;
}
}
public static class SignInSetupFragment extends ListFragment {
private static final String ARG_SETUP_ID = "setupId";
private int mDescriptionHeaderResId = 0;
private int mDescriptionBodyResId = 0;
private int mSelectionResId = 0;
private int mSetupId;
private static final int ATCONF_DIMEN_INDEX = 1;
public SignInSetupFragment() {}
public static Fragment makeFragment(int setupId) {
Bundle args = new Bundle();
args.putInt(ARG_SETUP_ID, setupId);
SignInSetupFragment fragment = new SignInSetupFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
mSetupId = getArguments().getInt(ARG_SETUP_ID);
switch (mSetupId) {
case SETUP_ATTENDEE:
mDescriptionHeaderResId = R.string.description_setup_attendee_mode_header;
mDescriptionBodyResId = R.string.description_setup_attendee_mode_body;
mSelectionResId = R.array.selection_setup_attendee;
break;
case SETUP_WIFI:
mDescriptionHeaderResId = R.string.description_setup_wifi_header;
mDescriptionBodyResId = R.string.description_setup_wifi_body;
mSelectionResId = R.array.selection_setup_wifi;
break;
default:
throw new IllegalArgumentException("Undefined setup id.");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_login_setup, container, false);
final TextView descriptionView = (TextView) rootView.findViewById(
R.id.login_setup_desc);
descriptionView.setText(Html.fromHtml(getString(mDescriptionHeaderResId) +
getString(mDescriptionBodyResId)));
return rootView;
}
@Override
public void onResume() {
super.onResume();
setListAdapter(
new ArrayAdapter<String> (getActivity(),
R.layout.list_item_login_option,
getResources().getStringArray(mSelectionResId)));
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
final Activity activity = getActivity();
if (mSetupId == SETUP_ATTENDEE) {
if (position == 0) {
// Attendee is at the conference. If WiFi AP isn't set already, go to
// the WiFi set up screen. Otherwise, set up is done.
PrefUtils.setAttendeeAtVenue(activity, true);
PrefUtils.setUsingLocalTime(activity, false);
// If WiFi has already been configured, set up is complete. Otherwise,
// show the WiFi AP configuration screen.
//if (WiFiUtils.shouldInstallWiFi(activity)) {
if (WiFiUtils.shouldBypassWiFiSetup(activity)) {
((AccountActivity)activity).finishSetup();
} else {
getFragmentManager().beginTransaction()
.replace(R.id.root_container,
SignInSetupFragment.makeFragment(SETUP_WIFI), "setup_wifi")
.addToBackStack("setup_attendee")
.commit();
}
EasyTracker.getTracker()
.setCustomDimension(ATCONF_DIMEN_INDEX,"conference attendee");
} else if (position == 1) {
// Attendee is remote. Set up is done.
PrefUtils.setAttendeeAtVenue(activity, false);
PrefUtils.setUsingLocalTime(activity, true);
EasyTracker.getTracker()
.setCustomDimension(ATCONF_DIMEN_INDEX,"remote attendee");
((AccountActivity)activity).finishSetup();
}
} else if (mSetupId == SETUP_WIFI) {
if (position == 0) {
WiFiUtils.setWiFiConfigStatus(activity, WiFiUtils.WIFI_CONFIG_REQUESTED);
}
// Done with set up.
((AccountActivity)activity).finishSetup();
}
}
}
public static class ChooseAccountFragment extends ListFragment {
public ChooseAccountFragment() {
}
@Override
public void onResume() {
super.onResume();
reloadAccountList();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_login_choose_account, container, false);
TextView descriptionView = (TextView) rootView.findViewById(R.id.choose_account_intro);
descriptionView.setText(Html.fromHtml(getString(R.string.description_choose_account)));
return rootView;
}
private AccountListAdapter mAccountListAdapter;
private void reloadAccountList() {
if (mAccountListAdapter != null) {
mAccountListAdapter = null;
}
AccountManager am = AccountManager.get(getActivity());
Account[] accounts = am.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
mAccountListAdapter = new AccountListAdapter(getActivity(), Arrays.asList(accounts));
setListAdapter(mAccountListAdapter);
}
private class AccountListAdapter extends ArrayAdapter<Account> {
private static final int LAYOUT_RESOURCE = R.layout.list_item_login_option;
public AccountListAdapter(Context context, List<Account> accounts) {
super(context, LAYOUT_RESOURCE, accounts);
}
private class ViewHolder {
TextView text1;
}
@Override
public int getCount() {
return super.getCount() + 1;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = getLayoutInflater(null).inflate(LAYOUT_RESOURCE, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView.findViewById(android.R.id.text1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (position == getCount() - 1) {
holder.text1.setText(R.string.description_add_account);
} else {
final Account account = getItem(position);
if (account != null) {
holder.text1.setText(account.name);
} else {
holder.text1.setText("");
}
}
return convertView;
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
if (position == mAccountListAdapter.getCount() - 1) {
Intent addAccountIntent = new Intent(Settings.ACTION_ADD_ACCOUNT);
addAccountIntent.putExtra(Settings.EXTRA_AUTHORITIES,
new String[]{ScheduleContract.CONTENT_AUTHORITY});
startActivity(addAccountIntent);
return;
}
AccountActivity activity = (AccountActivity) getActivity();
ConnectivityManager cm = (ConnectivityManager)
activity.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork == null || !activeNetwork.isConnected()) {
Toast.makeText(activity, R.string.no_connection_cant_login,
Toast.LENGTH_SHORT).show();
return;
}
activity.mCancelAuth = false;
activity.mChosenAccount = mAccountListAdapter.getItem(position);
activity.getSupportFragmentManager().beginTransaction()
.replace(R.id.root_container, new AuthProgressFragment(), "loading")
.addToBackStack("choose_account")
.commit();
PlusClient.Builder builder = new PlusClient.Builder(activity, activity, activity);
activity.mPlusClient = builder
.setScopes(AccountUtils.AUTH_SCOPES)
.setAccountName(activity.mChosenAccount.name).build();
activity.mPlusClient.connect();
}
}
public static class AuthProgressFragment extends Fragment {
private static final int TRY_AGAIN_DELAY_MILLIS = 7 * 1000; // 7 seconds
private final Handler mHandler = new Handler();
public AuthProgressFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_login_loading,
container, false);
final View takingAWhilePanel = rootView.findViewById(R.id.taking_a_while_panel);
final View tryAgainButton = rootView.findViewById(R.id.retry_button);
tryAgainButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getFragmentManager().popBackStack();
}
});
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (!isAdded()) {
return;
}
if (AccountUtils.isAuthenticated(getActivity())) {
((AccountActivity) getActivity()).onAuthTokenAvailable();
return;
}
takingAWhilePanel.setVisibility(View.VISIBLE);
}
}, TRY_AGAIN_DELAY_MILLIS);
return rootView;
}
@Override
public void onPause() {
super.onPause();
((AccountActivity) getActivity()).mAuthProgressFragmentResumed = false;
}
@Override
public void onResume() {
super.onResume();
((AccountActivity) getActivity()).mAuthProgressFragmentResumed = true;
if (((AccountActivity) getActivity()).mCanRemoveAuthProgressFragment) {
((AccountActivity) getActivity()).mCanRemoveAuthProgressFragment = false;
getFragmentManager().popBackStack();
}
}
@Override
public void onDetach() {
super.onDetach();
((AccountActivity) getActivity()).mCancelAuth = true;
}
}
private void tryAuthenticate() {
// Authenticate through the Google Play OAuth client.
mAuthInProgress = true;
AccountUtils.tryAuthenticate(this, this, mChosenAccount.name,
REQUEST_RECOVER_FROM_AUTH_ERROR);
}
@Override
public boolean shouldCancelAuthentication() {
return mCancelAuth;
}
@Override
public void onAuthTokenAvailable() {
// Cancel progress fragment.
// Create set up fragment.
mAuthInProgress = false;
if (mAuthProgressFragmentResumed) {
getSupportFragmentManager().popBackStack();
getSupportFragmentManager().beginTransaction()
.replace(R.id.root_container,
SignInSetupFragment.makeFragment(SETUP_ATTENDEE), "setup_attendee")
.addToBackStack("signin_main")
.commit();
}
}
private void finishSetup() {
ContentResolver.setIsSyncable(mChosenAccount, ScheduleContract.CONTENT_AUTHORITY, 1);
ContentResolver.setSyncAutomatically(mChosenAccount, ScheduleContract.CONTENT_AUTHORITY, true);
SyncHelper.requestManualSync(mChosenAccount);
PrefUtils.markSetupDone(this);
if (mFinishIntent != null) {
// Ensure the finish intent is unique within the task. Otherwise, if the task was
// started with this intent, and it finishes like it should, then startActivity on
// the intent again won't work.
mFinishIntent.addCategory(POST_AUTH_CATEGORY);
startActivity(mFinishIntent);
}
finish();
}
// Google Plus client callbacks.
@Override
public void onConnected(Bundle connectionHint) {
// It is possible that the authenticated account doesn't have a profile.
mPlusClient.loadPerson(this, "me");
tryAuthenticate();
}
@Override
public void onDisconnected() {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this,
REQUEST_RECOVER_FROM_AUTH_ERROR);
} catch (IntentSender.SendIntentException e) {
LOGE(TAG, "Internal error encountered: " + e.getMessage());
}
return;
}
final int errorCode = connectionResult.getErrorCode();
if (GooglePlayServicesUtil.isUserRecoverableError(errorCode)) {
GooglePlayServicesUtil.getErrorDialog(errorCode, this,
REQUEST_PLAY_SERVICES_ERROR_DIALOG).show();
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.ui;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.*;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.FrameLayout;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.MapUtils;
import com.google.android.apps.iosched.util.ParserUtils;
import com.google.android.apps.iosched.util.PrefUtils;
import com.google.android.apps.iosched.util.UIUtils;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.TileOverlay;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.android.gms.maps.model.TileProvider;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Locale;
/**
* Shows a map of the conference venue.
*/
public class MapFragment extends SupportMapFragment implements
GoogleMap.OnInfoWindowClickListener, GoogleMap.OnMarkerClickListener,
GoogleMap.OnCameraChangeListener,
LoaderCallbacks<Cursor> {
private static final LatLng MOSCONE = new LatLng(37.78353872135503, -122.40336209535599);
// Initial camera position
private static final LatLng CAMERA_MOSCONE = new LatLng(37.783107, -122.403789 );
private static final float CAMERA_ZOOM = 17.75f;
private static final int NUM_FLOORS = 3; // number of floors
private static final int INITIAL_FLOOR = 1;
/**
* When specified, will automatically point the map to the requested room.
*/
public static final String EXTRA_ROOM = "com.google.android.iosched.extra.ROOM";
private static final String TAG = makeLogTag(MapFragment.class);
// Marker types
public static final String TYPE_SESSION = "session";
public static final String TYPE_LABEL = "label";
public static final String TYPE_SANDBOX = "sandbox";
public static final String TYPE_INACTIVE = "inactive";
// Tile Providers
private TileProvider[] mTileProviders;
private TileOverlay[] mTileOverlays;
private Button[] mFloorButtons = new Button[NUM_FLOORS];
private View mFloorControls;
// Markers stored by id
private HashMap<String, MarkerModel> mMarkers = null;
// Markers stored by floor
private ArrayList<ArrayList<Marker>> mMarkersFloor = null;
private boolean mOverlaysLoaded = false;
private boolean mMarkersLoaded = false;
private boolean mTracksLoaded = false;
// Cached size of view
private int mWidth, mHeight;
// Padding for #centerMap
private int mShiftRight = 0;
private int mShiftTop = 0;
// Screen DPI
private float mDPI = 0;
// currently displayed floor
private int mFloor = -1;
// Show markers at default zoom level
private boolean mShowMarkers = true;
// Cached tracks data
private HashMap<String,TrackModel> mTracks = null;
private GoogleMap mMap;
private MapInfoWindowAdapter mInfoAdapter;
private MyLocationManager mMyLocationManager = null;
// Handler for info window queries
private AsyncQueryHandler mQueryHandler;
public interface Callbacks {
public void onSessionRoomSelected(String roomId, String roomTitle);
public void onSandboxRoomSelected(String trackId, String roomTitle);
}
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public void onSessionRoomSelected(String roomId, String roomTitle) {
}
@Override
public void onSandboxRoomSelected(String trackId, String roomTitle) {
}
};
private Callbacks mCallbacks = sDummyCallbacks;
private String mHighlightedRoom = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EasyTracker.getTracker().sendView("Map");
LOGD("Tracker", "Map");
clearMap();
// get DPI
mDPI = getActivity().getResources().getDisplayMetrics().densityDpi / 160f;
// setup the query handler to populate info windows
mQueryHandler = createInfowindowHandler(getActivity().getContentResolver());
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mapView = super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.fragment_map, container, false);
FrameLayout layout = (FrameLayout) v.findViewById(R.id.map_container);
layout.addView(mapView, 0);
mFloorControls = layout.findViewById(R.id.map_floorcontrol);
// setup floor button handlers
mFloorButtons[0] = (Button) v.findViewById(R.id.map_floor1);
mFloorButtons[1] = (Button) v.findViewById(R.id.map_floor2);
mFloorButtons[2] = (Button) v.findViewById(R.id.map_floor3);
for (int i = 0; i < mFloorButtons.length; i++) {
final int j = i;
mFloorButtons[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showFloor(j);
}
});
}
// get the height and width of the view
mapView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
@Override
public void onGlobalLayout() {
final View v = getView();
mHeight = v.getHeight();
mWidth = v.getWidth();
// also requires width and height
enableFloors();
if (v.getViewTreeObserver().isAlive()) {
// remove this layout listener
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
v.getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
} else {
v.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
}
}
}
});
if (mMap == null) {
setupMap(true);
}
// load all markers
LoaderManager lm = getActivity().getSupportLoaderManager();
lm.initLoader(MarkerQuery._TOKEN, null, this);
// load the tile overlays
lm.initLoader(OverlayQuery._TOKEN, null, this);
// load tracks data
lm.initLoader(TracksQuery._TOKEN, null, this);
return v;
}
/**
* Clears the map and initialises all map variables that hold markers and overlays.
*/
private void clearMap() {
if (mMap != null) {
mMap.clear();
}
// setup tile provider arrays
mTileProviders = new TileProvider[NUM_FLOORS];
mTileOverlays = new TileOverlay[NUM_FLOORS];
mMarkers = new HashMap<String, MarkerModel>();
mMarkersFloor = new ArrayList<ArrayList<Marker>>();
// initialise floor marker lists
for (int i = 0; i < NUM_FLOORS; i++) {
mMarkersFloor.add(i, new ArrayList<Marker>());
}
}
private void setupMap(boolean resetCamera) {
mInfoAdapter = new MapInfoWindowAdapter(getLayoutInflater(null), getResources(),
mMarkers);
mMap = getMap();
mMap.setOnMarkerClickListener(this);
mMap.setOnInfoWindowClickListener(this);
mMap.setOnCameraChangeListener(this);
mMap.setInfoWindowAdapter(mInfoAdapter);
if (resetCamera) {
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(CameraPosition.fromLatLngZoom(
CAMERA_MOSCONE, CAMERA_ZOOM)));
}
mMap.setIndoorEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);
if (MapUtils.getMyLocationEnabled(this.getActivity())) {
mMyLocationManager = new MyLocationManager();
}
Bundle data = getArguments();
if (data != null && data.containsKey(EXTRA_ROOM)) {
mHighlightedRoom = data.getString(EXTRA_ROOM);
}
LOGD(TAG, "Map setup complete.");
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof Callbacks)) {
throw new ClassCastException(
"Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
activity.getContentResolver().registerContentObserver(
ScheduleContract.MapMarkers.CONTENT_URI, true, mObserver);
activity.getContentResolver().registerContentObserver(
ScheduleContract.MapTiles.CONTENT_URI, true, mObserver);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity);
sp.registerOnSharedPreferenceChangeListener(mPrefChangeListener);
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = sDummyCallbacks;
getActivity().getContentResolver().unregisterContentObserver(mObserver);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
sp.unregisterOnSharedPreferenceChangeListener(mPrefChangeListener);
}
private void showFloor(int floor) {
if (mFloor != floor) {
if (mFloor >= 0) {
// hide old overlay
mTileOverlays[mFloor].setVisible(false);
mFloorButtons[mFloor].setBackgroundResource(R.drawable.map_floor_button_background);
mFloorButtons[mFloor].setTextColor(getResources().getColor(
R.color.map_floorselect_inactive));
// hide all markers
for (Marker m : mMarkersFloor.get(mFloor)) {
m.setVisible(false);
}
}
mFloor = floor;
// show the floor overlay
if (mTileOverlays[mFloor] != null) {
mTileOverlays[mFloor].setVisible(true);
}
// show all markers
for (Marker m : mMarkersFloor.get(mFloor)) {
m.setVisible(mShowMarkers);
}
// mark button active
mFloorButtons[mFloor]
.setBackgroundResource(R.drawable.map_floor_button_active_background);
mFloorButtons[mFloor].setTextColor(getResources().getColor(
R.color.map_floorselect_active));
}
}
/**
* Enable floor controls and display map features when all loaders have
* finished. This ensures that only complete data for the correct floor is
* shown.
*/
private void enableFloors() {
if (mOverlaysLoaded && mMarkersLoaded && mTracksLoaded && mWidth > 0 && mHeight > 0) {
mFloorControls.setVisibility(View.VISIBLE);
// highlight a room if argument is set and exists, otherwise show the default floor
if (mHighlightedRoom != null && mMarkers.containsKey(mHighlightedRoom)) {
highlightRoom(mHighlightedRoom);
mHighlightedRoom = null;
} else {
showFloor(INITIAL_FLOOR);
mHighlightedRoom = null;
}
}
}
void addTileProvider(int floor, File f) {
if (!f.exists()) {
return;
}
TileProvider provider;
try {
provider = new SVGTileProvider(f, mDPI);
} catch (IOException e) {
LOGD(TAG, "Could not create Tile Provider.");
e.printStackTrace();
return;
}
TileOverlayOptions tileOverlay = new TileOverlayOptions()
.tileProvider(provider).visible(false);
mTileProviders[floor] = provider;
mTileOverlays[floor] = mMap.addTileOverlay(tileOverlay);
}
@Override
public void onInfoWindowClick(Marker marker) {
final String snippet = marker.getSnippet();
if (TYPE_SESSION.equals(snippet)) {
final String roomId = marker.getTitle();
EasyTracker.getTracker().sendEvent(
"Map", "infoclick", roomId, 0L);
mCallbacks.onSessionRoomSelected(roomId, mMarkers.get(roomId).label);
// ignore other markers
} else if (TYPE_SANDBOX.equals(snippet)) {
final String roomId = marker.getTitle();
MarkerModel model = mMarkers.get(roomId);
EasyTracker.getTracker().sendEvent(
"Map", "infoclick", roomId, 0L);
mCallbacks.onSandboxRoomSelected(model.track, model.label);
}
}
@Override
public boolean onMarkerClick(Marker marker) {
final String snippet = marker.getSnippet();
// get the room id
String roomId = marker.getTitle();
if (TYPE_SESSION.equals(snippet)) {
// ignore other markers - sandbox is just another session type
EasyTracker.getTracker().sendEvent(
"Map", "markerclick", roomId, 0L);
final long time = UIUtils.getCurrentTime(getActivity());
Uri uri = ScheduleContract.Sessions.buildSessionsInRoomAfterUri(roomId, time);
final String order = ScheduleContract.Sessions.BLOCK_START + " ASC";
mQueryHandler.startQuery(SessionAfterQuery._TOKEN, roomId, uri,
SessionAfterQuery.PROJECTION, null, null, order);
} else if (TYPE_SANDBOX.equals(snippet)) {
// get the room id
EasyTracker.getTracker().sendEvent(
"Map", "markerclick", roomId, 0L);
final long time = UIUtils.getCurrentTime(getActivity());
String selection = ScheduleContract.Sandbox.AT_TIME_IN_ROOM_SELECTION;
Uri uri = ScheduleContract.Sandbox.CONTENT_URI;
String[] selectionArgs = ScheduleContract.Sandbox.buildAtTimeInRoomSelectionArgs(time, roomId);
final String order = ScheduleContract.Sandbox.COMPANY_NAME + " ASC";
mQueryHandler.startQuery(SandboxCompaniesAtQuery._TOKEN, roomId, uri,
SandboxCompaniesAtQuery.PROJECTION, selection, selectionArgs, order);
}
// ignore other markers
//centerMap(marker.getPosition());
return true;
}
private void centerMap(LatLng position) {
// calculate the new center of the map, taking into account optional
// padding
Projection proj = mMap.getProjection();
Point p = proj.toScreenLocation(position);
// apply padding
p.x = (int) (p.x - Math.round(mWidth * 0.5)) + mShiftRight;
p.y = (int) (p.y - Math.round(mHeight * 0.5)) + mShiftTop;
mMap.animateCamera(CameraUpdateFactory.scrollBy(p.x, p.y));
}
/**
* Set the padding around centered markers. Specified in the percentage of
* the screen space of the map.
*/
public void setCenterPadding(float xFraction, float yFraction) {
int oldShiftRight = mShiftRight;
int oldShiftTop = mShiftTop;
mShiftRight = Math.round(xFraction * mWidth);
mShiftTop = Math.round(yFraction * mWidth);
// re-center the map, shift displayed map by x and y fraction if map is
// ready
if (mMap != null) {
mMap.animateCamera(CameraUpdateFactory.scrollBy(mShiftRight - oldShiftRight, mShiftTop
- oldShiftTop));
}
}
private void highlightRoom(String roomId) {
MarkerModel m = mMarkers.get(roomId);
if (m != null) {
showFloor(m.floor);
// explicitly show the marker before info window is shown.
m.marker.setVisible(true);
onMarkerClick(m.marker);
centerMap(m.marker.getPosition());
}
}
/**
* Create an {@link AsyncQueryHandler} for use with the
* {@link MapInfoWindowAdapter}.
*/
private AsyncQueryHandler createInfowindowHandler(ContentResolver contentResolver) {
return new AsyncQueryHandler(contentResolver) {
StringBuilder mBuffer = new StringBuilder();
Formatter mFormatter = new Formatter(mBuffer, Locale.getDefault());
@Override
protected void onQueryComplete(int token, Object cookie,
Cursor cursor) {
MarkerModel model = mMarkers.get(cookie);
mInfoAdapter.clearData();
if (model == null || cursor == null) {
// query did not complete or incorrect data was loaded
return;
}
final long time = UIUtils.getCurrentTime(getActivity());
switch (token) {
case SessionAfterQuery._TOKEN: {
extractSession(cursor, model, time);
}
break;
case SandboxCompaniesAtQuery._TOKEN: {
extractSandbox(cursor, model, time);
}
}
// update the displayed window
model.marker.showInfoWindow();
}
private void extractSandbox(Cursor cursor, MarkerModel model, long time) {
// get tracks data from cache: icon and color
TrackModel track = mTracks.get(model.track);
int color = (track != null) ? track.color : 0 ;
int iconResId = 0;
if(track != null){
iconResId = getResources().getIdentifier(
"track_" + ParserUtils.sanitizeId(track.name),
"drawable", getActivity().getPackageName());
}
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
StringBuilder sb = new StringBuilder();
int count = 0;
final int maxCompaniesDisplay = getResources().getInteger(
R.integer.sandbox_company_list_max_display);
while (!cursor.isAfterLast() && count < maxCompaniesDisplay) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(cursor.getString(SandboxCompaniesAtQuery.COMPANY_NAME));
count++;
cursor.moveToNext();
}
if (count >= maxCompaniesDisplay && !cursor.isAfterLast()) {
// Additional sandbox companies to display
sb.append(", …");
}
mInfoAdapter.setSandbox(model.marker, model.label, color, iconResId,
sb.length() > 0 ? sb.toString() : null);
}else{
// No active sandbox companies
mInfoAdapter.setSandbox(model.marker, model.label, color, iconResId, null);
}
model.marker.showInfoWindow();
}
private static final long SHOW_UPCOMING_TIME = 24 * 60 * 60 * 1000; // 24 hours
private void extractSession(Cursor cursor, MarkerModel model, long time) {
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
String currentTitle = null;
String nextTitle = null;
String nextTime = null;
final long blockStart = cursor.getLong(SessionAfterQuery.BLOCK_START);
final long blockEnd = cursor.getLong(SessionAfterQuery.BLOCK_END);
boolean inProgress = time >= blockStart && time <= blockEnd;
if (inProgress) {
// A session is running, display its name and optionally
// the next session
currentTitle = cursor.getString(SessionAfterQuery.SESSION_TITLE);
//move to the next entry
cursor.moveToNext();
}
if (!cursor.isAfterLast()) {
//There is a session coming up next, display only it if it's within 24 hours of the current time
final long nextStart = cursor.getLong(SessionAfterQuery.BLOCK_START);
if (nextStart < time + SHOW_UPCOMING_TIME ) {
nextTitle = cursor.getString(SessionAfterQuery.SESSION_TITLE);
mBuffer.setLength(0);
boolean showWeekday = !DateUtils.isToday(blockStart)
&& !UIUtils.isSameDayDisplay(UIUtils.getCurrentTime(getActivity()), blockStart, getActivity());
nextTime = DateUtils.formatDateRange(getActivity(), mFormatter,
blockStart, blockStart,
DateUtils.FORMAT_SHOW_TIME | (showWeekday
? DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY
: 0),
PrefUtils.getDisplayTimeZone(getActivity()).getID()).toString();
}
}
// populate the info window adapter
mInfoAdapter.setSessionData(model.marker, model.label, currentTitle,
nextTitle,
nextTime,
inProgress);
} else {
// No entries, display name of room only
mInfoAdapter.setMarker(model.marker, model.label);
}
}
};
}
// Loaders
private void onMarkerLoaderComplete(Cursor cursor) {
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
// get data
String id = cursor.getString(MarkerQuery.MARKER_ID);
int floor = cursor.getInt(MarkerQuery.MARKER_FLOOR);
float lat = cursor.getFloat(MarkerQuery.MARKER_LATITUDE);
float lon = cursor.getFloat(MarkerQuery.MARKER_LONGITUDE);
String type = cursor.getString(MarkerQuery.MARKER_TYPE);
String label = cursor.getString(MarkerQuery.MARKER_LABEL);
String track = cursor.getString(MarkerQuery.MARKER_TRACK);
BitmapDescriptor icon = null;
if (TYPE_SESSION.equals(type)) {
icon = BitmapDescriptorFactory.fromResource(R.drawable.marker_session);
} else if (TYPE_SANDBOX.equals(type)) {
icon = BitmapDescriptorFactory.fromResource(R.drawable.marker_sandbox);
} else if (TYPE_LABEL.equals(type)) {
Bitmap b = MapUtils.createTextLabel(label, mDPI);
if (b != null) {
icon = BitmapDescriptorFactory.fromBitmap(b);
}
}
// add marker to map
if (icon != null) {
Marker m = mMap.addMarker(
new MarkerOptions().position(new LatLng(lat, lon)).title(id)
.snippet(type).icon(icon)
.visible(false));
MarkerModel model = new MarkerModel(id, floor, type, label, track, m);
mMarkersFloor.get(floor).add(m);
mMarkers.put(id, model);
}
cursor.moveToNext();
}
// no more markers to load
mMarkersLoaded = true;
enableFloors();
}
}
private void onTracksLoaderComplete(Cursor cursor){
if(cursor != null){
mTracks = new HashMap<String, TrackModel>();
cursor.moveToFirst();
while(!cursor.isAfterLast()){
final String name = cursor.getString(TracksQuery.TRACK_NAME);
final String id = cursor.getString(TracksQuery.TRACK_ID);
final int color = cursor.getInt(TracksQuery.TRACK_COLOR);
mTracks.put(id,new TrackModel(id,name,color));
cursor.moveToNext();
}
mTracksLoaded = true;
enableFloors();
}
}
private void onOverlayLoaderComplete(Cursor cursor) {
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
final int floor = cursor.getInt(OverlayQuery.TILE_FLOOR);
final String file = cursor.getString(OverlayQuery.TILE_FILE);
File f = MapUtils.getTileFile(getActivity().getApplicationContext(), file);
if (f != null) {
addTileProvider(floor, f);
}
cursor.moveToNext();
}
}
mOverlaysLoaded = true;
enableFloors();
}
private interface MarkerQuery {
int _TOKEN = 0x1;
String[] PROJECTION = {
ScheduleContract.MapMarkers.MARKER_ID,
ScheduleContract.MapMarkers.MARKER_FLOOR,
ScheduleContract.MapMarkers.MARKER_LATITUDE,
ScheduleContract.MapMarkers.MARKER_LONGITUDE,
ScheduleContract.MapMarkers.MARKER_TYPE,
ScheduleContract.MapMarkers.MARKER_LABEL,
ScheduleContract.MapMarkers.MARKER_TRACK
};
int MARKER_ID = 0;
int MARKER_FLOOR = 1;
int MARKER_LATITUDE = 2;
int MARKER_LONGITUDE = 3;
int MARKER_TYPE = 4;
int MARKER_LABEL = 5;
int MARKER_TRACK = 6;
}
private interface OverlayQuery {
int _TOKEN = 0x3;
String[] PROJECTION = {
ScheduleContract.MapTiles.TILE_FLOOR,
ScheduleContract.MapTiles.TILE_FILE
};
int TILE_FLOOR = 0;
int TILE_FILE = 1;
}
private interface SessionAfterQuery {
int _TOKEN = 0x5;
String[] PROJECTION = {
ScheduleContract.Sessions.SESSION_TITLE,
ScheduleContract.Sessions.BLOCK_START, ScheduleContract.Sessions.BLOCK_END,
ScheduleContract.Rooms.ROOM_NAME
};
int SESSION_TITLE = 0;
int BLOCK_START = 1;
int BLOCK_END = 2;
int ROOM_NAME = 3;
}
private interface SandboxCompaniesAtQuery {
int _TOKEN = 0x4;
String[] PROJECTION = {
ScheduleContract.Sandbox.COMPANY_NAME
};
int COMPANY_NAME = 0;
}
private interface TracksQuery {
int _TOKEN = 0x6;
String[] PROJECTION = {
ScheduleContract.Tracks.TRACK_ID,
ScheduleContract.Tracks.TRACK_NAME,
ScheduleContract.Tracks.TRACK_COLOR
};
int TRACK_ID = 0;
int TRACK_NAME = 1;
int TRACK_COLOR = 2;
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle data) {
switch (id) {
case MarkerQuery._TOKEN: {
Uri uri = ScheduleContract.MapMarkers.buildMarkerUri();
return new CursorLoader(getActivity(), uri, MarkerQuery.PROJECTION,
null, null, null);
}
case OverlayQuery._TOKEN: {
Uri uri = ScheduleContract.MapTiles.buildUri();
return new CursorLoader(getActivity(), uri,
OverlayQuery.PROJECTION, null, null, null);
}
case TracksQuery._TOKEN: {
Uri uri = ScheduleContract.Tracks.CONTENT_URI;
return new CursorLoader(getActivity(), uri,
TracksQuery.PROJECTION, null, null, null);
}
}
return null;
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (getActivity() == null) {
return;
}
switch (loader.getId()) {
case MarkerQuery._TOKEN:
onMarkerLoaderComplete(cursor);
break;
case OverlayQuery._TOKEN:
onOverlayLoaderComplete(cursor);
break;
case TracksQuery._TOKEN:
onTracksLoaderComplete(cursor);
break;
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (mMyLocationManager != null) {
mMyLocationManager.onDestroy();
}
}
@Override
public void onCameraChange(CameraPosition cameraPosition) {
// ensure markers have been loaded and are being displayed
if (mFloor < 0) {
return;
}
mShowMarkers = cameraPosition.zoom >= 17;
for (Marker m : mMarkersFloor.get(mFloor)) {
m.setVisible(mShowMarkers);
}
}
private final SharedPreferences.OnSharedPreferenceChangeListener mPrefChangeListener =
new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
if(!isAdded()){
return;
}
boolean enableMyLocation = MapUtils.getMyLocationEnabled(MapFragment.this.getActivity());
//enable or disable location manager
if (enableMyLocation && mMyLocationManager == null) {
// enable location manager
mMyLocationManager = new MyLocationManager();
} else if (!enableMyLocation && mMyLocationManager != null) {
// disable location manager
mMyLocationManager.onDestroy();
mMyLocationManager = null;
}
}
};
private final ContentObserver mObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange) {
if (!isAdded()) {
return;
}
//clear map reload all data
clearMap();
setupMap(false);
// reload data from loaders
LoaderManager lm = getActivity().getSupportLoaderManager();
mMarkersLoaded = false;
mOverlaysLoaded = false;
mTracksLoaded = false;
Loader<Cursor> loader =
lm.getLoader(MarkerQuery._TOKEN);
if (loader != null) {
loader.forceLoad();
}
loader = lm.getLoader(OverlayQuery._TOKEN);
if (loader != null) {
loader.forceLoad();
}
loader = lm.getLoader(TracksQuery._TOKEN);
if (loader != null) {
loader.forceLoad();
}
}
};
/**
* Manages the display of the "My Location" layer. Ensures that the layer is
* only visible when the user is within 200m of Moscone Center.
*/
private class MyLocationManager extends BroadcastReceiver {
private static final String ACTION_PROXIMITY_ALERT
= "com.google.android.apps.iosched.action.PROXIMITY_ALERT";
private static final float DISTANCE = 200; // 200 metres.
private final IntentFilter mIntentFilter = new IntentFilter(ACTION_PROXIMITY_ALERT);
private final LocationManager mLocationManager;
public MyLocationManager() {
mLocationManager = (LocationManager) getActivity().getSystemService(
Context.LOCATION_SERVICE);
Intent i = new Intent();
i.setAction(ACTION_PROXIMITY_ALERT);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity()
.getApplicationContext(), 0, i, 0);
mLocationManager.addProximityAlert(MOSCONE.latitude, MOSCONE.longitude, DISTANCE, -1,
pendingIntent);
getActivity().registerReceiver(this, mIntentFilter);
// The proximity alert is only fired if the user moves in/out of
// range. Look at the current location to see if it is within range.
checkCurrentLocation();
}
@Override
public void onReceive(Context context, Intent intent) {
boolean inMoscone = intent.getBooleanExtra(LocationManager.KEY_PROXIMITY_ENTERING,
false);
mMap.setMyLocationEnabled(inMoscone);
}
public void checkCurrentLocation() {
Criteria criteria = new Criteria();
String provider = mLocationManager.getBestProvider(criteria, false);
Location lastKnownLocation = mLocationManager.getLastKnownLocation(provider);
if (lastKnownLocation == null) {
return;
}
Location moscone = new Location(lastKnownLocation.getProvider());
moscone.setLatitude(MOSCONE.latitude);
moscone.setLongitude(MOSCONE.longitude);
moscone.setAccuracy(1);
if (moscone.distanceTo(lastKnownLocation) < DISTANCE) {
mMap.setMyLocationEnabled(true);
}
}
public void onDestroy() {
getActivity().unregisterReceiver(this);
}
}
/**
* A structure to store information about a Marker.
*/
public static class MarkerModel {
String id;
int floor;
String type;
String label;
String track = null;
Marker marker;
public MarkerModel(String id, int floor, String type, String label, String track, Marker marker) {
this.id = id;
this.floor = floor;
this.type = type;
this.label = label;
this.marker = marker;
this.track = track;
}
}
public static class TrackModel {
String id;
String name;
int color;
public TrackModel(String id, String name, int color) {
this.id = id;
this.name = name;
this.color = color;
}
}
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* 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 com.google.android.apps.iosched.ui;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.style.StyleSpan;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.R.drawable;
import com.google.android.apps.iosched.util.ImageLoader;
import com.google.api.services.plus.model.Activity;
import java.util.ArrayList;
import java.util.List;
import static com.google.api.services.plus.model.Activity.PlusObject.Attachments.Thumbnails;
/**
* Renders a Google+-like stream item.
*/
class PlusStreamRowViewBinder {
private static class ViewHolder {
// Author and metadata box
private View authorContainer;
private ImageView userImage;
private TextView userName;
private TextView time;
// Author's content
private TextView content;
// Original share box
private View originalContainer;
private TextView originalAuthor;
private TextView originalContent;
// Media box
private View mediaContainer;
private ImageView mediaBackground;
private ImageView mediaOverlay;
private TextView mediaTitle;
private TextView mediaSubtitle;
// Interactions box
private View interactionsContainer;
private TextView plusOnes;
private TextView shares;
private TextView comments;
}
private static int PLACEHOLDER_USER_IMAGE = 0;
private static int PLACEHOLDER_MEDIA_IMAGE = 1;
public static ImageLoader getPlusStreamImageLoader(FragmentActivity activity,
Resources resources) {
DisplayMetrics metrics = resources.getDisplayMetrics();
int largestWidth = metrics.widthPixels > metrics.heightPixels ?
metrics.widthPixels : metrics.heightPixels;
// Create list of placeholder drawables (this ImageLoader requires two different
// placeholder images).
ArrayList<Drawable> placeHolderDrawables = new ArrayList<Drawable>(2);
placeHolderDrawables.add(PLACEHOLDER_USER_IMAGE,
resources.getDrawable(drawable.person_image_empty));
placeHolderDrawables.add(PLACEHOLDER_MEDIA_IMAGE, new ColorDrawable(
resources.getColor(R.color.plus_empty_image_background_color)));
// Create ImageLoader instance
return new ImageLoader(activity, placeHolderDrawables)
.setMaxImageSize(largestWidth);
}
public static void bindActivityView(final View rootView, Activity activity,
ImageLoader imageLoader, boolean singleSourceMode) {
// Prepare view holder.
ViewHolder tempViews = (ViewHolder) rootView.getTag();
final ViewHolder views;
if (tempViews != null) {
views = tempViews;
} else {
views = new ViewHolder();
rootView.setTag(views);
// Author and metadata box
views.authorContainer = rootView.findViewById(R.id.stream_author_container);
views.userImage = (ImageView) rootView.findViewById(R.id.stream_user_image);
views.userName = (TextView) rootView.findViewById(R.id.stream_user_name);
views.time = (TextView) rootView.findViewById(R.id.stream_time);
// Author's content
views.content = (TextView) rootView.findViewById(R.id.stream_content);
// Original share box
views.originalContainer = rootView.findViewById(
R.id.stream_original_container);
views.originalAuthor = (TextView) rootView.findViewById(
R.id.stream_original_author);
views.originalContent = (TextView) rootView.findViewById(
R.id.stream_original_content);
// Media box
views.mediaContainer = rootView.findViewById(R.id.stream_media_container);
views.mediaBackground = (ImageView) rootView.findViewById(
R.id.stream_media_background);
views.mediaOverlay = (ImageView) rootView.findViewById(R.id.stream_media_overlay);
views.mediaTitle = (TextView) rootView.findViewById(R.id.stream_media_title);
views.mediaSubtitle = (TextView) rootView.findViewById(R.id.stream_media_subtitle);
// Interactions box
views.interactionsContainer = rootView.findViewById(
R.id.stream_interactions_container);
views.plusOnes = (TextView) rootView.findViewById(R.id.stream_plus_ones);
views.shares = (TextView) rootView.findViewById(R.id.stream_shares);
views.comments = (TextView) rootView.findViewById(R.id.stream_comments);
}
final Context context = rootView.getContext();
final Resources res = context.getResources();
// Determine if this is a reshare (affects how activity fields are to be interpreted).
Activity.PlusObject.Actor originalAuthor = activity.getObject().getActor();
boolean isReshare = "share".equals(activity.getVerb()) && originalAuthor != null;
// Author and metadata box
views.authorContainer.setVisibility(singleSourceMode ? View.GONE : View.VISIBLE);
views.userName.setText(activity.getActor().getDisplayName());
// Find user profile image url
String userImageUrl = null;
if (activity.getActor().getImage() != null) {
userImageUrl = activity.getActor().getImage().getUrl();
}
// Load image from network in background thread using Volley library
imageLoader.get(userImageUrl, views.userImage, PLACEHOLDER_USER_IMAGE);
long thenUTC = activity.getUpdated().getValue()
+ activity.getUpdated().getTimeZoneShift() * 60000;
views.time.setText(DateUtils.getRelativeTimeSpanString(thenUTC,
System.currentTimeMillis(),
DateUtils.SECOND_IN_MILLIS,
DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_ABBREV_RELATIVE));
// Author's additional content
String selfContent = isReshare
? activity.getAnnotation()
: activity.getObject().getContent();
views.content.setMaxLines(singleSourceMode ? 1000 : 5);
if (!TextUtils.isEmpty(selfContent)) {
views.content.setVisibility(View.VISIBLE);
views.content.setText(Html.fromHtml(selfContent));
} else {
views.content.setVisibility(View.GONE);
}
// Original share box
if (isReshare) {
views.originalContainer.setVisibility(View.VISIBLE);
// Set original author text, highlight author name
final String author = res.getString(
R.string.stream_originally_shared, originalAuthor.getDisplayName());
final SpannableStringBuilder spannableAuthor = new SpannableStringBuilder(author);
spannableAuthor.setSpan(new StyleSpan(Typeface.BOLD),
author.length() - originalAuthor.getDisplayName().length(), author.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
views.originalAuthor.setText(spannableAuthor, TextView.BufferType.SPANNABLE);
String originalContent = activity.getObject().getContent();
views.originalContent.setMaxLines(singleSourceMode ? 1000 : 3);
if (!TextUtils.isEmpty(originalContent)) {
views.originalContent.setVisibility(View.VISIBLE);
views.originalContent.setText(Html.fromHtml(originalContent));
} else {
views.originalContent.setVisibility(View.GONE);
}
} else {
views.originalContainer.setVisibility(View.GONE);
}
// Media box
// Set media content.
List<Activity.PlusObject.Attachments> attachments
= activity.getObject().getAttachments();
if (attachments != null && attachments.size() > 0) {
Activity.PlusObject.Attachments attachment = attachments.get(0);
String objectType = attachment.getObjectType();
String imageUrl = attachment.getImage() != null
? attachment.getImage().getUrl()
: null;
if (imageUrl == null && attachment.getThumbnails() != null
&& attachment.getThumbnails().size() > 0) {
Thumbnails thumb = attachment.getThumbnails().get(0);
imageUrl = thumb.getImage() != null
? thumb.getImage().getUrl()
: null;
}
// Load image from network in background thread using Volley library
imageLoader.get(imageUrl, views.mediaBackground, PLACEHOLDER_MEDIA_IMAGE);
boolean overlayStyle = false;
views.mediaOverlay.setImageDrawable(null);
if (("photo".equals(objectType)
|| "video".equals(objectType)
|| "album".equals(objectType))
&& !TextUtils.isEmpty(imageUrl)) {
overlayStyle = true;
views.mediaOverlay.setImageResource("video".equals(objectType)
? R.drawable.ic_stream_media_overlay_video
: R.drawable.ic_stream_media_overlay_photo);
} else if ("article".equals(objectType) || "event".equals(objectType)) {
overlayStyle = false;
views.mediaTitle.setText(attachment.getDisplayName());
if (!TextUtils.isEmpty(attachment.getUrl())) {
Uri uri = Uri.parse(attachment.getUrl());
views.mediaSubtitle.setText(uri.getHost());
} else {
views.mediaSubtitle.setText("");
}
}
views.mediaContainer.setVisibility(View.VISIBLE);
views.mediaContainer.setBackgroundResource(
overlayStyle ? R.color.plus_stream_media_background : android.R.color.black);
if (overlayStyle) {
views.mediaBackground.clearColorFilter();
} else {
views.mediaBackground.setColorFilter(res.getColor(R.color.plus_media_item_tint));
}
views.mediaOverlay.setVisibility(overlayStyle ? View.VISIBLE : View.GONE);
views.mediaTitle.setVisibility(overlayStyle ? View.GONE : View.VISIBLE);
views.mediaSubtitle.setVisibility(overlayStyle ? View.GONE : View.VISIBLE);
} else {
views.mediaContainer.setVisibility(View.GONE);
views.mediaBackground.setImageDrawable(null);
views.mediaOverlay.setImageDrawable(null);
}
// Interactions box
final int plusOneCount = (activity.getObject().getPlusoners() != null)
? activity.getObject().getPlusoners().getTotalItems().intValue() : 0;
if (plusOneCount > 0) {
views.plusOnes.setVisibility(View.VISIBLE);
views.plusOnes.setText(getPlusOneString(plusOneCount));
} else {
views.plusOnes.setVisibility(View.GONE);
}
final int commentCount = (activity.getObject().getReplies() != null)
? activity.getObject().getReplies().getTotalItems().intValue() : 0;
if (commentCount > 0) {
views.comments.setVisibility(View.VISIBLE);
views.comments.setText(Integer.toString(commentCount));
} else {
views.comments.setVisibility(View.GONE);
}
final int resharerCount = (activity.getObject().getResharers() != null)
? activity.getObject().getResharers().getTotalItems().intValue() : 0;
if (resharerCount > 0) {
views.shares.setVisibility(View.VISIBLE);
views.shares.setText(Integer.toString(resharerCount));
} else {
views.shares.setVisibility(View.GONE);
}
views.interactionsContainer.setVisibility(
(plusOneCount > 0 || commentCount > 0 || resharerCount > 0)
? View.VISIBLE : View.GONE);
}
private static final String LRM_PLUS = "\u200E+";
private static String getPlusOneString(int count) {
return LRM_PLUS + Integer.toString(count);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.provider;
import com.google.android.apps.iosched.appwidget.ScheduleWidgetProvider;
import com.google.android.apps.iosched.provider.ScheduleContract.Announcements;
import com.google.android.apps.iosched.provider.ScheduleContract.Blocks;
import com.google.android.apps.iosched.provider.ScheduleContract.Feedback;
import com.google.android.apps.iosched.provider.ScheduleContract.MapMarkers;
import com.google.android.apps.iosched.provider.ScheduleContract.MapTiles;
import com.google.android.apps.iosched.provider.ScheduleContract.Rooms;
import com.google.android.apps.iosched.provider.ScheduleContract.SearchSuggest;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.provider.ScheduleContract.Speakers;
import com.google.android.apps.iosched.provider.ScheduleContract.Tracks;
import com.google.android.apps.iosched.provider.ScheduleContract.Sandbox;
import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSearchColumns;
import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers;
import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks;
import com.google.android.apps.iosched.provider.ScheduleDatabase.Tables;
import com.google.android.apps.iosched.util.SelectionBuilder;
import android.app.Activity;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.BaseColumns;
import android.text.TextUtils;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Provider that stores {@link ScheduleContract} data. Data is usually inserted
* by {@link com.google.android.apps.iosched.sync.SyncHelper}, and queried by various
* {@link Activity} instances.
*/
public class ScheduleProvider extends ContentProvider {
private static final String TAG = makeLogTag(ScheduleProvider.class);
private ScheduleDatabase mOpenHelper;
private static final UriMatcher sUriMatcher = buildUriMatcher();
private static final int BLOCKS = 100;
private static final int BLOCKS_BETWEEN = 101;
private static final int BLOCKS_ID = 102;
private static final int BLOCKS_ID_SESSIONS = 103;
private static final int BLOCKS_ID_SESSIONS_STARRED = 104;
private static final int TRACKS = 200;
private static final int TRACKS_ID = 201;
private static final int TRACKS_ID_SESSIONS = 202;
private static final int TRACKS_ID_SANDBOX = 203;
private static final int ROOMS = 300;
private static final int ROOMS_ID = 301;
private static final int ROOMS_ID_SESSIONS = 302;
private static final int SESSIONS = 400;
private static final int SESSIONS_STARRED = 401;
private static final int SESSIONS_WITH_TRACK = 402;
private static final int SESSIONS_SEARCH = 403;
private static final int SESSIONS_AT = 404;
private static final int SESSIONS_ID = 405;
private static final int SESSIONS_ID_SPEAKERS = 406;
private static final int SESSIONS_ID_TRACKS = 407;
private static final int SESSIONS_ID_WITH_TRACK = 408;
private static final int SESSIONS_ROOM_AFTER = 410;
private static final int SPEAKERS = 500;
private static final int SPEAKERS_ID = 501;
private static final int SPEAKERS_ID_SESSIONS = 502;
private static final int SANDBOX = 600;
private static final int SANDBOX_SEARCH = 603;
private static final int SANDBOX_ID = 604;
private static final int ANNOUNCEMENTS = 700;
private static final int ANNOUNCEMENTS_ID = 701;
private static final int SEARCH_SUGGEST = 800;
private static final int SEARCH_INDEX = 801;
private static final int MAPMARKERS = 900;
private static final int MAPMARKERS_FLOOR = 901;
private static final int MAPMARKERS_ID = 902;
private static final int MAPTILES = 1000;
private static final int MAPTILES_FLOOR = 1001;
private static final int FEEDBACK_ALL = 1002;
private static final int FEEDBACK_FOR_SESSION = 1003;
/**
* Build and return a {@link UriMatcher} that catches all {@link Uri}
* variations supported by this {@link ContentProvider}.
*/
private static UriMatcher buildUriMatcher() {
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = ScheduleContract.CONTENT_AUTHORITY;
matcher.addURI(authority, "blocks", BLOCKS);
matcher.addURI(authority, "blocks/between/*/*", BLOCKS_BETWEEN);
matcher.addURI(authority, "blocks/*", BLOCKS_ID);
matcher.addURI(authority, "blocks/*/sessions", BLOCKS_ID_SESSIONS);
matcher.addURI(authority, "blocks/*/sessions/starred", BLOCKS_ID_SESSIONS_STARRED);
matcher.addURI(authority, "tracks", TRACKS);
matcher.addURI(authority, "tracks/*", TRACKS_ID);
matcher.addURI(authority, "tracks/*/sessions", TRACKS_ID_SESSIONS);
matcher.addURI(authority, "tracks/*/sandbox", TRACKS_ID_SANDBOX);
matcher.addURI(authority, "rooms", ROOMS);
matcher.addURI(authority, "rooms/*", ROOMS_ID);
matcher.addURI(authority, "rooms/*/sessions", ROOMS_ID_SESSIONS);
matcher.addURI(authority, "sessions", SESSIONS);
matcher.addURI(authority, "sessions/starred", SESSIONS_STARRED);
matcher.addURI(authority, "sessions/with_track", SESSIONS_WITH_TRACK);
matcher.addURI(authority, "sessions/search/*", SESSIONS_SEARCH);
matcher.addURI(authority, "sessions/at/*", SESSIONS_AT);
matcher.addURI(authority, "sessions/room/*/after/*", SESSIONS_ROOM_AFTER);
matcher.addURI(authority, "sessions/*", SESSIONS_ID);
matcher.addURI(authority, "sessions/*/speakers", SESSIONS_ID_SPEAKERS);
matcher.addURI(authority, "sessions/*/tracks", SESSIONS_ID_TRACKS);
matcher.addURI(authority, "sessions/*/with_track", SESSIONS_ID_WITH_TRACK);
matcher.addURI(authority, "speakers", SPEAKERS);
matcher.addURI(authority, "speakers/*", SPEAKERS_ID);
matcher.addURI(authority, "speakers/*/sessions", SPEAKERS_ID_SESSIONS);
matcher.addURI(authority, "sandbox", SANDBOX);
matcher.addURI(authority, "sandbox/search/*", SANDBOX_SEARCH);
matcher.addURI(authority, "sandbox/*", SANDBOX_ID);
matcher.addURI(authority, "announcements", ANNOUNCEMENTS);
matcher.addURI(authority, "announcements/*", ANNOUNCEMENTS_ID);
matcher.addURI(authority, "search_suggest_query", SEARCH_SUGGEST);
matcher.addURI(authority, "search_index", SEARCH_INDEX); // 'update' only
matcher.addURI(authority, "mapmarkers", MAPMARKERS);
matcher.addURI(authority, "mapmarkers/floor/*", MAPMARKERS_FLOOR);
matcher.addURI(authority, "mapmarkers/*", MAPMARKERS_ID);
matcher.addURI(authority, "maptiles", MAPTILES);
matcher.addURI(authority, "maptiles/*", MAPTILES_FLOOR);
matcher.addURI(authority, "feedback/*", FEEDBACK_FOR_SESSION);
matcher.addURI(authority, "feedback*", FEEDBACK_ALL);
matcher.addURI(authority, "feedback", FEEDBACK_ALL);
return matcher;
}
@Override
public boolean onCreate() {
mOpenHelper = new ScheduleDatabase(getContext());
return true;
}
private void deleteDatabase() {
// TODO: wait for content provider operations to finish, then tear down
mOpenHelper.close();
Context context = getContext();
ScheduleDatabase.deleteDatabase(context);
mOpenHelper = new ScheduleDatabase(getContext());
}
/** {@inheritDoc} */
@Override
public String getType(Uri uri) {
final int match = sUriMatcher.match(uri);
switch (match) {
case BLOCKS:
return Blocks.CONTENT_TYPE;
case BLOCKS_BETWEEN:
return Blocks.CONTENT_TYPE;
case BLOCKS_ID:
return Blocks.CONTENT_ITEM_TYPE;
case BLOCKS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case BLOCKS_ID_SESSIONS_STARRED:
return Sessions.CONTENT_TYPE;
case TRACKS:
return Tracks.CONTENT_TYPE;
case TRACKS_ID:
return Tracks.CONTENT_ITEM_TYPE;
case TRACKS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case TRACKS_ID_SANDBOX:
return Sandbox.CONTENT_TYPE;
case ROOMS:
return Rooms.CONTENT_TYPE;
case ROOMS_ID:
return Rooms.CONTENT_ITEM_TYPE;
case ROOMS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case SESSIONS:
return Sessions.CONTENT_TYPE;
case SESSIONS_STARRED:
return Sessions.CONTENT_TYPE;
case SESSIONS_WITH_TRACK:
return Sessions.CONTENT_TYPE;
case SESSIONS_SEARCH:
return Sessions.CONTENT_TYPE;
case SESSIONS_AT:
return Sessions.CONTENT_TYPE;
case SESSIONS_ID:
return Sessions.CONTENT_ITEM_TYPE;
case SESSIONS_ID_SPEAKERS:
return Speakers.CONTENT_TYPE;
case SESSIONS_ID_TRACKS:
return Tracks.CONTENT_TYPE;
case SESSIONS_ID_WITH_TRACK:
return Sessions.CONTENT_TYPE;
case SESSIONS_ROOM_AFTER:
return Sessions.CONTENT_TYPE;
case SPEAKERS:
return Speakers.CONTENT_TYPE;
case SPEAKERS_ID:
return Speakers.CONTENT_ITEM_TYPE;
case SPEAKERS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case SANDBOX:
return Sandbox.CONTENT_TYPE;
case SANDBOX_SEARCH:
return ScheduleContract.Sandbox.CONTENT_TYPE;
case SANDBOX_ID:
return ScheduleContract.Sandbox.CONTENT_ITEM_TYPE;
case ANNOUNCEMENTS:
return Announcements.CONTENT_TYPE;
case ANNOUNCEMENTS_ID:
return Announcements.CONTENT_ITEM_TYPE;
case MAPMARKERS:
return MapMarkers.CONTENT_TYPE;
case MAPMARKERS_FLOOR:
return MapMarkers.CONTENT_TYPE;
case MAPMARKERS_ID:
return MapMarkers.CONTENT_ITEM_TYPE;
case MAPTILES:
return MapTiles.CONTENT_TYPE;
case MAPTILES_FLOOR:
return MapTiles.CONTENT_ITEM_TYPE;
case FEEDBACK_FOR_SESSION:
return Feedback.CONTENT_ITEM_TYPE;
case FEEDBACK_ALL:
return Feedback.CONTENT_TYPE;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
/** {@inheritDoc} */
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
LOGV(TAG, "query(uri=" + uri + ", proj=" + Arrays.toString(projection) + ")");
final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
String uriFilter = uri.getQueryParameter(Sessions.QUERY_PARAMETER_FILTER);
final int match = sUriMatcher.match(uri);
switch (match) {
default: {
// Most cases are handled with simple SelectionBuilder
final SelectionBuilder builder = buildExpandedSelection(uri, match);
// If a special filter was specified, try to apply it
if (!TextUtils.isEmpty(uriFilter)) {
if (Sessions.QUERY_VALUE_FILTER_SESSIONS_CODELABS_ONLY.equals(uriFilter)) {
builder.where(Sessions.SESSION_TYPE + " NOT IN ('"
+ Sessions.SESSION_TYPE_OFFICE_HOURS + "','"
+ Sessions.SESSION_TYPE_KEYNOTE + "')");
} else if (Sessions.QUERY_VALUE_FILTER_OFFICE_HOURS_ONLY.equals(uriFilter)) {
builder.where(Sessions.SESSION_TYPE + " = ?",
Sessions.SESSION_TYPE_OFFICE_HOURS);
}
}
return builder.where(selection, selectionArgs).query(db, projection, sortOrder);
}
case SEARCH_SUGGEST: {
final SelectionBuilder builder = new SelectionBuilder();
// Adjust incoming query to become SQL text match
selectionArgs[0] = selectionArgs[0] + "%";
builder.table(Tables.SEARCH_SUGGEST);
builder.where(selection, selectionArgs);
builder.map(SearchManager.SUGGEST_COLUMN_QUERY,
SearchManager.SUGGEST_COLUMN_TEXT_1);
projection = new String[] {
BaseColumns._ID,
SearchManager.SUGGEST_COLUMN_TEXT_1,
SearchManager.SUGGEST_COLUMN_QUERY
};
final String limit = uri.getQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT);
return builder.query(db, projection, null, null, SearchSuggest.DEFAULT_SORT, limit);
}
}
}
/** {@inheritDoc} */
@Override
public Uri insert(Uri uri, ContentValues values) {
LOGV(TAG, "insert(uri=" + uri + ", values=" + values.toString() + ")");
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
boolean syncToNetwork = !ScheduleContract.hasCallerIsSyncAdapterParameter(uri);
switch (match) {
case BLOCKS: {
db.insertOrThrow(Tables.BLOCKS, null, values);
notifyChange(uri, syncToNetwork);
return Blocks.buildBlockUri(values.getAsString(Blocks.BLOCK_ID));
}
case TRACKS: {
db.insertOrThrow(Tables.TRACKS, null, values);
notifyChange(uri, syncToNetwork);
return Tracks.buildTrackUri(values.getAsString(Tracks.TRACK_ID));
}
case ROOMS: {
db.insertOrThrow(Tables.ROOMS, null, values);
notifyChange(uri, syncToNetwork);
return Rooms.buildRoomUri(values.getAsString(Rooms.ROOM_ID));
}
case SESSIONS: {
db.insertOrThrow(Tables.SESSIONS, null, values);
notifyChange(uri, syncToNetwork);
return Sessions.buildSessionUri(values.getAsString(Sessions.SESSION_ID));
}
case SESSIONS_ID_SPEAKERS: {
db.insertOrThrow(Tables.SESSIONS_SPEAKERS, null, values);
notifyChange(uri, syncToNetwork);
return Speakers.buildSpeakerUri(values.getAsString(SessionsSpeakers.SPEAKER_ID));
}
case SESSIONS_ID_TRACKS: {
db.insertOrThrow(Tables.SESSIONS_TRACKS, null, values);
notifyChange(uri, syncToNetwork);
return Tracks.buildTrackUri(values.getAsString(SessionsTracks.TRACK_ID));
}
case SPEAKERS: {
db.insertOrThrow(Tables.SPEAKERS, null, values);
notifyChange(uri, syncToNetwork);
return Speakers.buildSpeakerUri(values.getAsString(Speakers.SPEAKER_ID));
}
case SANDBOX: {
db.insertOrThrow(Tables.SANDBOX, null, values);
notifyChange(uri, syncToNetwork);
return Sandbox.buildCompanyUri(values.getAsString(Sandbox.COMPANY_ID));
}
case ANNOUNCEMENTS: {
db.insertOrThrow(Tables.ANNOUNCEMENTS, null, values);
notifyChange(uri, syncToNetwork);
return Announcements.buildAnnouncementUri(values
.getAsString(Announcements.ANNOUNCEMENT_ID));
}
case SEARCH_SUGGEST: {
db.insertOrThrow(Tables.SEARCH_SUGGEST, null, values);
notifyChange(uri, syncToNetwork);
return SearchSuggest.CONTENT_URI;
}
case MAPMARKERS: {
db.insertOrThrow(Tables.MAPMARKERS, null, values);
notifyChange(uri, syncToNetwork);
return MapMarkers.buildMarkerUri(values.getAsString(MapMarkers.MARKER_ID));
}
case MAPTILES: {
db.insertOrThrow(Tables.MAPTILES, null, values);
notifyChange(uri, syncToNetwork);
return MapTiles.buildFloorUri(values.getAsString(MapTiles.TILE_FLOOR));
}
case FEEDBACK_FOR_SESSION: {
db.insertOrThrow(Tables.FEEDBACK, null, values);
notifyChange(uri, syncToNetwork);
return Feedback.buildFeedbackUri(values.getAsString(Feedback.SESSION_ID));
}
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
/** {@inheritDoc} */
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
LOGV(TAG, "update(uri=" + uri + ", values=" + values.toString() + ")");
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
if (match == SEARCH_INDEX) {
// update the search index
ScheduleDatabase.updateSessionSearchIndex(db);
return 1;
}
final SelectionBuilder builder = buildSimpleSelection(uri);
int retVal = builder.where(selection, selectionArgs).update(db, values);
boolean syncToNetwork = !ScheduleContract.hasCallerIsSyncAdapterParameter(uri);
notifyChange(uri, syncToNetwork);
return retVal;
}
/** {@inheritDoc} */
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
LOGV(TAG, "delete(uri=" + uri + ")");
if (uri == ScheduleContract.BASE_CONTENT_URI) {
// Handle whole database deletes (e.g. when signing out)
deleteDatabase();
notifyChange(uri, false);
return 1;
}
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final SelectionBuilder builder = buildSimpleSelection(uri);
int retVal = builder.where(selection, selectionArgs).delete(db);
notifyChange(uri, !ScheduleContract.hasCallerIsSyncAdapterParameter(uri));
return retVal;
}
private void notifyChange(Uri uri, boolean syncToNetwork) {
Context context = getContext();
context.getContentResolver().notifyChange(uri, null, syncToNetwork);
// Widgets can't register content observers so we refresh widgets separately.
context.sendBroadcast(ScheduleWidgetProvider.getRefreshBroadcastIntent(context, false));
}
/**
* Apply the given set of {@link ContentProviderOperation}, executing inside
* a {@link SQLiteDatabase} transaction. All changes will be rolled back if
* any single one fails.
*/
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.beginTransaction();
try {
final int numOperations = operations.size();
final ContentProviderResult[] results = new ContentProviderResult[numOperations];
for (int i = 0; i < numOperations; i++) {
results[i] = operations.get(i).apply(this, results, i);
}
db.setTransactionSuccessful();
return results;
} finally {
db.endTransaction();
}
}
/**
* Build a simple {@link SelectionBuilder} to match the requested
* {@link Uri}. This is usually enough to support {@link #insert},
* {@link #update}, and {@link #delete} operations.
*/
private SelectionBuilder buildSimpleSelection(Uri uri) {
final SelectionBuilder builder = new SelectionBuilder();
final int match = sUriMatcher.match(uri);
switch (match) {
case BLOCKS: {
return builder.table(Tables.BLOCKS);
}
case BLOCKS_ID: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.BLOCKS)
.where(Blocks.BLOCK_ID + "=?", blockId);
}
case TRACKS: {
return builder.table(Tables.TRACKS);
}
case TRACKS_ID: {
final String trackId = Tracks.getTrackId(uri);
return builder.table(Tables.TRACKS)
.where(Tracks.TRACK_ID + "=?", trackId);
}
case ROOMS: {
return builder.table(Tables.ROOMS);
}
case ROOMS_ID: {
final String roomId = Rooms.getRoomId(uri);
return builder.table(Tables.ROOMS)
.where(Rooms.ROOM_ID + "=?", roomId);
}
case SESSIONS: {
return builder.table(Tables.SESSIONS);
}
case SESSIONS_ID: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS)
.where(Sessions.SESSION_ID + "=?", sessionId);
}
case SESSIONS_ID_SPEAKERS: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_SPEAKERS)
.where(Sessions.SESSION_ID + "=?", sessionId);
}
case SESSIONS_ID_TRACKS: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_TRACKS)
.where(Sessions.SESSION_ID + "=?", sessionId);
}
case SPEAKERS: {
return builder.table(Tables.SPEAKERS);
}
case SPEAKERS_ID: {
final String speakerId = Speakers.getSpeakerId(uri);
return builder.table(Tables.SPEAKERS)
.where(Speakers.SPEAKER_ID + "=?", speakerId);
}
case SANDBOX: {
return builder.table(Tables.SANDBOX);
}
case SANDBOX_ID: {
final String companyId = ScheduleContract.Sandbox.getCompanyId(uri);
return builder.table(Tables.SANDBOX)
.where(Sandbox.COMPANY_ID + "=?", companyId);
}
case ANNOUNCEMENTS: {
return builder.table(Tables.ANNOUNCEMENTS);
}
case ANNOUNCEMENTS_ID: {
final String announcementId = Announcements.getAnnouncementId(uri);
return builder.table(Tables.ANNOUNCEMENTS)
.where(Announcements.ANNOUNCEMENT_ID + "=?", announcementId);
}
case MAPMARKERS: {
return builder.table(Tables.MAPMARKERS);
}
case MAPMARKERS_FLOOR: {
final String floor = MapMarkers.getMarkerFloor(uri);
return builder.table(Tables.MAPMARKERS)
.where(MapMarkers.MARKER_FLOOR+ "=?", floor);
}
case MAPMARKERS_ID: {
final String markerId = MapMarkers.getMarkerId(uri);
return builder.table(Tables.MAPMARKERS)
.where(MapMarkers.MARKER_ID+ "=?", markerId);
}
case MAPTILES: {
return builder.table(Tables.MAPTILES);
}
case MAPTILES_FLOOR: {
final String floor = MapTiles.getFloorId(uri);
return builder.table(Tables.MAPTILES)
.where(MapTiles.TILE_FLOOR+ "=?", floor);
}
case SEARCH_SUGGEST: {
return builder.table(Tables.SEARCH_SUGGEST);
}
case FEEDBACK_FOR_SESSION: {
final String session_id = Feedback.getSessionId(uri);
return builder.table(Tables.FEEDBACK)
.where(Feedback.SESSION_ID + "=?", session_id);
}
case FEEDBACK_ALL: {
return builder.table(Tables.FEEDBACK);
}
default: {
throw new UnsupportedOperationException("Unknown uri for " + match + ": " + uri);
}
}
}
/**
* Build an advanced {@link SelectionBuilder} to match the requested
* {@link Uri}. This is usually only used by {@link #query}, since it
* performs table joins useful for {@link Cursor} data.
*/
private SelectionBuilder buildExpandedSelection(Uri uri, int match) {
final SelectionBuilder builder = new SelectionBuilder();
switch (match) {
case BLOCKS: {
return builder
.table(Tables.BLOCKS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.map(Blocks.NUM_LIVESTREAMED_SESSIONS,
Subquery.BLOCK_NUM_LIVESTREAMED_SESSIONS)
.map(Blocks.STARRED_SESSION_ID, Subquery.BLOCK_STARRED_SESSION_ID)
.map(Blocks.STARRED_SESSION_TITLE, Subquery.BLOCK_STARRED_SESSION_TITLE)
.map(Blocks.STARRED_SESSION_HASHTAGS,
Subquery.BLOCK_STARRED_SESSION_HASHTAGS)
.map(Blocks.STARRED_SESSION_URL, Subquery.BLOCK_STARRED_SESSION_URL)
.map(Blocks.STARRED_SESSION_LIVESTREAM_URL,
Subquery.BLOCK_STARRED_SESSION_LIVESTREAM_URL)
.map(Blocks.STARRED_SESSION_ROOM_NAME,
Subquery.BLOCK_STARRED_SESSION_ROOM_NAME)
.map(Blocks.STARRED_SESSION_ROOM_ID, Subquery.BLOCK_STARRED_SESSION_ROOM_ID);
}
case BLOCKS_BETWEEN: {
final List<String> segments = uri.getPathSegments();
final String startTime = segments.get(2);
final String endTime = segments.get(3);
return builder.table(Tables.BLOCKS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.map(Blocks.NUM_LIVESTREAMED_SESSIONS,
Subquery.BLOCK_NUM_LIVESTREAMED_SESSIONS)
.where(Blocks.BLOCK_START + ">=?", startTime)
.where(Blocks.BLOCK_START + "<=?", endTime);
}
case BLOCKS_ID: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.BLOCKS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.map(Blocks.NUM_LIVESTREAMED_SESSIONS,
Subquery.BLOCK_NUM_LIVESTREAMED_SESSIONS)
.where(Blocks.BLOCK_ID + "=?", blockId);
}
case BLOCKS_ID_SESSIONS: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.map(Blocks.NUM_LIVESTREAMED_SESSIONS,
Subquery.BLOCK_NUM_LIVESTREAMED_SESSIONS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId);
}
case BLOCKS_ID_SESSIONS_STARRED: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.map(Blocks.NUM_LIVESTREAMED_SESSIONS,
Subquery.BLOCK_NUM_LIVESTREAMED_SESSIONS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId)
.where(Qualified.SESSIONS_STARRED + "=1");
}
case TRACKS: {
return builder.table(Tables.TRACKS)
.map(Tracks.SESSIONS_COUNT, Subquery.TRACK_SESSIONS_COUNT)
.map(Tracks.OFFICE_HOURS_COUNT, Subquery.TRACK_OFFICE_HOURS_COUNT)
.map(Tracks.SANDBOX_COUNT, Subquery.TRACK_SANDBOX_COUNT);
}
case TRACKS_ID: {
final String trackId = Tracks.getTrackId(uri);
return builder.table(Tables.TRACKS)
.where(Tracks.TRACK_ID + "=?", trackId);
}
case TRACKS_ID_SESSIONS: {
final String trackId = Tracks.getTrackId(uri);
return builder.table(Tables.SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_TRACKS_TRACK_ID + "=?", trackId);
}
case TRACKS_ID_SANDBOX: {
final String trackId = Tracks.getTrackId(uri);
return builder.table(Tables.SANDBOX_JOIN_TRACKS_BLOCKS_ROOMS)
.mapToTable(ScheduleContract.Sandbox._ID, Tables.SANDBOX)
.mapToTable(Sandbox.TRACK_ID, Tables.SANDBOX)
.mapToTable(ScheduleContract.Sandbox.BLOCK_ID, Tables.BLOCKS)
.mapToTable(Sandbox.ROOM_ID, Tables.ROOMS)
.where(Qualified.SANDBOX_TRACK_ID + "=?", trackId);
}
case ROOMS: {
return builder.table(Tables.ROOMS);
}
case ROOMS_ID: {
final String roomId = Rooms.getRoomId(uri);
return builder.table(Tables.ROOMS)
.where(Rooms.ROOM_ID + "=?", roomId);
}
case ROOMS_ID_SESSIONS: {
final String roomId = Rooms.getRoomId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_ROOM_ID + "=?", roomId);
}
case SESSIONS: {
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS);
}
case SESSIONS_STARRED: {
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Sessions.SESSION_STARRED + "=1");
}
case SESSIONS_WITH_TRACK: {
return builder.table(Tables.SESSIONS_JOIN_TRACKS_JOIN_BLOCKS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Tracks.TRACK_ID, Tables.TRACKS)
.mapToTable(Tracks.TRACK_NAME, Tables.TRACKS)
.mapToTable(Blocks.BLOCK_ID, Tables.BLOCKS);
}
case SESSIONS_ID_WITH_TRACK: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_JOIN_TRACKS_JOIN_BLOCKS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Tracks.TRACK_ID, Tables.TRACKS)
.mapToTable(Tracks.TRACK_NAME, Tables.TRACKS)
.mapToTable(Blocks.BLOCK_ID, Tables.BLOCKS)
.where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId);
}
case SESSIONS_SEARCH: {
final String query = Sessions.getSearchQuery(uri);
return builder.table(Tables.SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS)
.map(Sessions.SEARCH_SNIPPET, Subquery.SESSIONS_SNIPPET)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(SessionsSearchColumns.BODY + " MATCH ?", query);
}
case SESSIONS_AT: {
final List<String> segments = uri.getPathSegments();
final String time = segments.get(2);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Sessions.BLOCK_START + "<=?", time)
.where(Sessions.BLOCK_END + ">=?", time);
}
case SESSIONS_ID: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId);
}
case SESSIONS_ID_SPEAKERS: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SPEAKERS)
.mapToTable(Speakers._ID, Tables.SPEAKERS)
.mapToTable(Speakers.SPEAKER_ID, Tables.SPEAKERS)
.where(Qualified.SESSIONS_SPEAKERS_SESSION_ID + "=?", sessionId);
}
case SESSIONS_ID_TRACKS: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_TRACKS_JOIN_TRACKS)
.mapToTable(Tracks._ID, Tables.TRACKS)
.mapToTable(Tracks.TRACK_ID, Tables.TRACKS)
.where(Qualified.SESSIONS_TRACKS_SESSION_ID + "=?", sessionId);
}
case SESSIONS_ROOM_AFTER: {
final String room = Sessions.getRoom(uri);
final String time = Sessions.getAfter(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_ROOM_ID+ "=?", room)
.where("("+Sessions.BLOCK_START + "<= ? AND "+Sessions.BLOCK_END+">= ?) OR ("+Sessions.BLOCK_START+" >= ?)", time,time,time);
}
case SPEAKERS: {
return builder.table(Tables.SPEAKERS);
}
case SPEAKERS_ID: {
final String speakerId = Speakers.getSpeakerId(uri);
return builder.table(Tables.SPEAKERS)
.where(Speakers.SPEAKER_ID + "=?", speakerId);
}
case SPEAKERS_ID_SESSIONS: {
final String speakerId = Speakers.getSpeakerId(uri);
return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_SPEAKERS_SPEAKER_ID + "=?", speakerId);
}
case SANDBOX: {
return builder.table(Tables.SANDBOX_JOIN_TRACKS_BLOCKS_ROOMS)
.mapToTable(Sandbox._ID, Tables.SANDBOX)
.mapToTable(Sandbox.TRACK_ID, Tables.SANDBOX)
.mapToTable(Sandbox.BLOCK_ID, Tables.SANDBOX)
.mapToTable(Sandbox.ROOM_ID, Tables.SANDBOX);
}
case SANDBOX_ID: {
final String companyId = ScheduleContract.Sandbox.getCompanyId(uri);
return builder.table(Tables.SANDBOX_JOIN_TRACKS_BLOCKS_ROOMS)
.mapToTable(ScheduleContract.Sandbox._ID, Tables.SANDBOX)
.mapToTable(Sandbox.TRACK_ID, Tables.SANDBOX)
.mapToTable(Sandbox.BLOCK_ID, Tables.SANDBOX)
.mapToTable(Sandbox.ROOM_ID, Tables.SANDBOX)
.where(Sandbox.COMPANY_ID + "=?", companyId);
}
case ANNOUNCEMENTS: {
return builder.table(Tables.ANNOUNCEMENTS);
}
case ANNOUNCEMENTS_ID: {
final String announcementId = Announcements.getAnnouncementId(uri);
return builder.table(Tables.ANNOUNCEMENTS)
.where(Announcements.ANNOUNCEMENT_ID + "=?", announcementId);
}
case MAPMARKERS: {
return builder.table(Tables.MAPMARKERS);
}
case MAPMARKERS_FLOOR: {
final String floor = MapMarkers.getMarkerFloor(uri);
return builder.table(Tables.MAPMARKERS)
.where(MapMarkers.MARKER_FLOOR+ "=?", floor);
}
case MAPMARKERS_ID: {
final String roomId = MapMarkers.getMarkerId(uri);
return builder.table(Tables.MAPMARKERS)
.where(MapMarkers.MARKER_ID+ "=?", roomId);
}
case MAPTILES: {
return builder.table(Tables.MAPTILES);
}
case MAPTILES_FLOOR: {
final String floor = MapTiles.getFloorId(uri);
return builder.table(Tables.MAPTILES)
.where(MapTiles.TILE_FLOOR+ "=?", floor);
}
case FEEDBACK_FOR_SESSION: {
final String sessionId = Feedback.getSessionId(uri);
return builder.table(Tables.FEEDBACK)
.where(Feedback.SESSION_ID + "=?", sessionId);
}
case FEEDBACK_ALL: {
return builder.table(Tables.FEEDBACK);
}
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
final int match = sUriMatcher.match(uri);
switch (match) {
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
private interface Subquery {
String BLOCK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_SESSION_ID + ") FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + ")";
String BLOCK_NUM_STARRED_SESSIONS = "(SELECT COUNT(1) FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1)";
String BLOCK_NUM_LIVESTREAMED_SESSIONS = "(SELECT COUNT(1) FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID
+ " AND IFNULL(" + Qualified.SESSIONS_LIVESTREAM_URL + ",'')!='')";
String BLOCK_STARRED_SESSION_ID = "(SELECT " + Qualified.SESSIONS_SESSION_ID + " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_TITLE = "(SELECT " + Qualified.SESSIONS_TITLE + " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_HASHTAGS = "(SELECT " + Qualified.SESSIONS_HASHTAGS + " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_URL = "(SELECT " + Qualified.SESSIONS_URL + " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_LIVESTREAM_URL = "(SELECT "
+ Qualified.SESSIONS_LIVESTREAM_URL
+ " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_ROOM_NAME = "(SELECT " + Qualified.ROOMS_ROOM_NAME + " FROM "
+ Tables.SESSIONS_JOIN_ROOMS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_ROOM_ID = "(SELECT " + Qualified.ROOMS_ROOM_ID + " FROM "
+ Tables.SESSIONS_JOIN_ROOMS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String TRACK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_TRACKS_SESSION_ID
+ ") FROM " + Tables.SESSIONS_TRACKS + " INNER JOIN " + Tables.SESSIONS + " ON "
+ Qualified.SESSIONS_SESSION_ID + "=" + Qualified.SESSIONS_TRACKS_SESSION_ID + " WHERE "
+ Qualified.SESSIONS_TRACKS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID
+ " AND " + Qualified.SESSIONS_SESSION_TYPE + " != \"" + Sessions.SESSION_TYPE_OFFICE_HOURS + "\")";
String TRACK_OFFICE_HOURS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_TRACKS_SESSION_ID
+ ") FROM " + Tables.SESSIONS_TRACKS + " INNER JOIN " + Tables.SESSIONS + " ON "
+ Qualified.SESSIONS_SESSION_ID + "=" + Qualified.SESSIONS_TRACKS_SESSION_ID + " WHERE "
+ Qualified.SESSIONS_TRACKS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID
+ " AND " + Qualified.SESSIONS_SESSION_TYPE + " = \"" + Sessions.SESSION_TYPE_OFFICE_HOURS + "\")";
String TRACK_SANDBOX_COUNT = "(SELECT COUNT(" + Qualified.SANDBOX_COMPANY_ID + ") FROM "
+ Tables.SANDBOX + " WHERE " + Qualified.SANDBOX_TRACK_ID + "="
+ Qualified.TRACKS_TRACK_ID + ")";
String SESSIONS_SNIPPET = "snippet(" + Tables.SESSIONS_SEARCH + ",'{','}','\u2026')";
}
/**
* {@link ScheduleContract} fields that are fully qualified with a specific
* parent {@link Tables}. Used when needed to work around SQL ambiguity.
*/
private interface Qualified {
String SESSIONS_SESSION_ID = Tables.SESSIONS + "." + Sessions.SESSION_ID;
String SESSIONS_SESSION_TYPE = Tables.SESSIONS+ "." + Sessions.SESSION_TYPE;
String SESSIONS_BLOCK_ID = Tables.SESSIONS + "." + Sessions.BLOCK_ID;
String SESSIONS_ROOM_ID = Tables.SESSIONS + "." + Sessions.ROOM_ID;
String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "."
+ SessionsTracks.SESSION_ID;
String SESSIONS_TRACKS_TRACK_ID = Tables.SESSIONS_TRACKS + "."
+ SessionsTracks.TRACK_ID;
String SESSIONS_SPEAKERS_SESSION_ID = Tables.SESSIONS_SPEAKERS + "."
+ SessionsSpeakers.SESSION_ID;
String SESSIONS_SPEAKERS_SPEAKER_ID = Tables.SESSIONS_SPEAKERS + "."
+ SessionsSpeakers.SPEAKER_ID;
String SANDBOX_COMPANY_ID = Tables.SANDBOX + "." + Sandbox.COMPANY_ID;
String SANDBOX_TRACK_ID = Tables.SANDBOX + "." + Sandbox.TRACK_ID;
String SESSIONS_STARRED = Tables.SESSIONS + "." + Sessions.SESSION_STARRED;
String SESSIONS_TITLE = Tables.SESSIONS + "." + Sessions.SESSION_TITLE;
String SESSIONS_HASHTAGS = Tables.SESSIONS + "." + Sessions.SESSION_HASHTAGS;
String SESSIONS_URL = Tables.SESSIONS + "." + Sessions.SESSION_URL;
String SESSIONS_LIVESTREAM_URL = Tables.SESSIONS + "." + Sessions.SESSION_LIVESTREAM_URL;
String ROOMS_ROOM_NAME = Tables.ROOMS + "." + Rooms.ROOM_NAME;
String ROOMS_ROOM_ID = Tables.ROOMS + "." + Rooms.ROOM_ID;
String TRACKS_TRACK_ID = Tables.TRACKS + "." + Tracks.TRACK_ID;
String BLOCKS_BLOCK_ID = Tables.BLOCKS + "." + Blocks.BLOCK_ID;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.provider;
import com.google.android.apps.iosched.util.ParserUtils;
import android.app.SearchManager;
import android.graphics.Color;
import android.net.Uri;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.text.format.DateUtils;
import java.util.List;
/**
* Contract class for interacting with {@link ScheduleProvider}. Unless
* otherwise noted, all time-based fields are milliseconds since epoch and can
* be compared against {@link System#currentTimeMillis()}.
* <p>
* The backing {@link android.content.ContentProvider} assumes that {@link Uri}
* are generated using stronger {@link String} identifiers, instead of
* {@code int} {@link BaseColumns#_ID} values, which are prone to shuffle during
* sync.
*/
public class ScheduleContract {
/**
* Special value for {@link SyncColumns#UPDATED} indicating that an entry
* has never been updated, or doesn't exist yet.
*/
public static final long UPDATED_NEVER = -2;
/**
* Special value for {@link SyncColumns#UPDATED} indicating that the last
* update time is unknown, usually when inserted from a local file source.
*/
public static final long UPDATED_UNKNOWN = -1;
public interface SyncColumns {
/** Last time this entry was updated or synchronized. */
String UPDATED = "updated";
}
interface BlocksColumns {
/** Unique string identifying this block of time. */
String BLOCK_ID = "block_id";
/** Title describing this block of time. */
String BLOCK_TITLE = "block_title";
/** Time when this block starts. */
String BLOCK_START = "block_start";
/** Time when this block ends. */
String BLOCK_END = "block_end";
/** Type describing this block. */
String BLOCK_TYPE = "block_type";
/** Extra string metadata for the block. */
String BLOCK_META = "block_meta";
}
interface TracksColumns {
/** Unique string identifying this track. */
String TRACK_ID = "track_id";
/** Name describing this track. */
String TRACK_NAME = "track_name";
/** Color used to identify this track, in {@link Color#argb} format. */
String TRACK_COLOR = "track_color";
/** The level (1 being primary, 2 being secondary) of the track. */
String TRACK_LEVEL = "track_level";
/** The sort order of the track within the level. */
String TRACK_ORDER_IN_LEVEL = "track_order_in_level";
/** Type of meta-track this is, or 0 if not meta. */
String TRACK_META = "track_is_meta";
/** Type of track. */
String TRACK_ABSTRACT = "track_abstract";
/** Hashtag for track. */
String TRACK_HASHTAG = "track_hashtag";
}
interface RoomsColumns {
/** Unique string identifying this room. */
String ROOM_ID = "room_id";
/** Name describing this room. */
String ROOM_NAME = "room_name";
/** Building floor this room exists on. */
String ROOM_FLOOR = "room_floor";
}
interface SessionsColumns {
/** Unique string identifying this session. */
String SESSION_ID = "session_id";
/** The type of session (session, keynote, codelab, etc). */
String SESSION_TYPE = "session_type";
/** Difficulty level of the session. */
String SESSION_LEVEL = "session_level";
/** Title describing this track. */
String SESSION_TITLE = "session_title";
/** Body of text explaining this session in detail. */
String SESSION_ABSTRACT = "session_abstract";
/** Requirements that attendees should meet. */
String SESSION_REQUIREMENTS = "session_requirements";
/** Kewords/tags for this session. */
String SESSION_TAGS = "session_keywords";
/** Hashtag for this session. */
String SESSION_HASHTAGS = "session_hashtag";
/** Full URL to session online. */
String SESSION_URL = "session_url";
/** Full URL to YouTube. */
String SESSION_YOUTUBE_URL = "session_youtube_url";
/** Full URL to PDF. */
String SESSION_PDF_URL = "session_pdf_url";
/** Full URL to official session notes. */
String SESSION_NOTES_URL = "session_notes_url";
/** User-specific flag indicating starred status. */
String SESSION_STARRED = "session_starred";
/** Key for session Calendar event. (Used in ICS or above) */
String SESSION_CAL_EVENT_ID = "session_cal_event_id";
/** The YouTube live stream URL. */
String SESSION_LIVESTREAM_URL = "session_livestream_url";
/** The Moderator URL. */
String SESSION_MODERATOR_URL = "session_moderator_url";
}
interface SpeakersColumns {
/** Unique string identifying this speaker. */
String SPEAKER_ID = "speaker_id";
/** Name of this speaker. */
String SPEAKER_NAME = "speaker_name";
/** Profile photo of this speaker. */
String SPEAKER_IMAGE_URL = "speaker_image_url";
/** Company this speaker works for. */
String SPEAKER_COMPANY = "speaker_company";
/** Body of text describing this speaker in detail. */
String SPEAKER_ABSTRACT = "speaker_abstract";
/** Full URL to the speaker's profile. */
String SPEAKER_URL = "speaker_url";
}
interface SandboxColumns {
/** Unique string identifying this sandbox company. */
String COMPANY_ID = "company_id";
/** Name of this sandbox company. */
String COMPANY_NAME = "company_name";
/** Body of text describing this sandbox company. */
String COMPANY_DESC = "company_desc";
/** Link to sandbox company online. */
String COMPANY_URL = "company_url";
/** Link to sandbox company logo. */
String COMPANY_LOGO_URL = "company_logo_url";
}
interface AnnouncementsColumns {
/** Unique string identifying this announcment. */
String ANNOUNCEMENT_ID = "announcement_id";
/** Title of the announcement. */
String ANNOUNCEMENT_TITLE = "announcement_title";
/** Google+ activity JSON for the announcement. */
String ANNOUNCEMENT_ACTIVITY_JSON = "announcement_activity_json";
/** Full URL for the announcement. */
String ANNOUNCEMENT_URL = "announcement_url";
/** Date of the announcement. */
String ANNOUNCEMENT_DATE = "announcement_date";
}
interface MapMarkerColumns {
/** Unique string identifying this marker. */
String MARKER_ID = "map_marker_id";
/** Type of marker. */
String MARKER_TYPE = "map_marker_type";
/** Latitudinal position of marker. */
String MARKER_LATITUDE = "map_marker_latitude";
/** Longitudinal position of marker. */
String MARKER_LONGITUDE = "map_marker_longitude";
/** Label (title) for this marker. */
String MARKER_LABEL = "map_marker_label";
/** Building floor this marker is on. */
String MARKER_FLOOR = "map_marker_floor";
/** Track of sandbox marker */
String MARKER_TRACK = "track_id";
}
interface FeedbackColumns {
String SESSION_ID = "session_id";
String SESSION_RATING = "feedback_session_rating";
String ANSWER_RELEVANCE = "feedback_answer_q1";
String ANSWER_CONTENT = "feedback_answer_q2";
String ANSWER_SPEAKER = "feedback_answer_q3";
String ANSWER_WILLUSE = "feedback_answer_q4";
String COMMENTS = "feedback_comments";
}
interface MapTileColumns {
/** Floor **/
String TILE_FLOOR = "map_tile_floor";
/** Filename **/
String TILE_FILE = "map_tile_file";
/** Url **/
String TILE_URL = "map_tile_url";
}
public static final String CONTENT_AUTHORITY = "com.google.android.apps.iosched";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
private static final String PATH_BLOCKS = "blocks";
private static final String PATH_AT = "at";
private static final String PATH_AFTER = "after";
private static final String PATH_BETWEEN = "between";
private static final String PATH_TRACKS = "tracks";
private static final String PATH_ROOM = "room";
private static final String PATH_ROOMS = "rooms";
private static final String PATH_SESSIONS = "sessions";
private static final String PATH_FEEDBACK = "feedback";
private static final String PATH_WITH_TRACK = "with_track";
private static final String PATH_STARRED = "starred";
private static final String PATH_SPEAKERS = "speakers";
private static final String PATH_SANDBOX = "sandbox";
private static final String PATH_ANNOUNCEMENTS = "announcements";
private static final String PATH_MAP_MARKERS = "mapmarkers";
private static final String PATH_MAP_FLOOR = "floor";
private static final String PATH_MAP_TILES= "maptiles";
private static final String PATH_SEARCH = "search";
private static final String PATH_SEARCH_SUGGEST = "search_suggest_query";
private static final String PATH_SEARCH_INDEX = "search_index";
/**
* Blocks are generic timeslots that {@link Sessions} and other related
* events fall into.
*/
public static class Blocks implements BlocksColumns, BaseColumns {
public static final String BLOCK_TYPE_GENERIC = "generic";
public static final String BLOCK_TYPE_FOOD = "food";
public static final String BLOCK_TYPE_SESSION = "session";
public static final String BLOCK_TYPE_CODELAB = "codelab";
public static final String BLOCK_TYPE_KEYNOTE = "keynote";
public static final String BLOCK_TYPE_OFFICE_HOURS = "officehours";
public static final String BLOCK_TYPE_SANDBOX = "sandbox_only";
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_BLOCKS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.block";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.block";
/** Count of {@link Sessions} inside given block. */
public static final String SESSIONS_COUNT = "sessions_count";
/**
* Flag indicating the number of sessions inside this block that have
* {@link Sessions#SESSION_STARRED} set.
*/
public static final String NUM_STARRED_SESSIONS = "num_starred_sessions";
/**
* Flag indicating the number of sessions inside this block that have a
* {@link Sessions#SESSION_LIVESTREAM_URL} set.
*/
public static final String NUM_LIVESTREAMED_SESSIONS = "num_livestreamed_sessions";
/**
* The {@link Sessions#SESSION_ID} of the first starred session in this
* block.
*/
public static final String STARRED_SESSION_ID = "starred_session_id";
/**
* The {@link Sessions#SESSION_TITLE} of the first starred session in
* this block.
*/
public static final String STARRED_SESSION_TITLE = "starred_session_title";
/**
* The {@link Sessions#SESSION_LIVESTREAM_URL} of the first starred
* session in this block.
*/
public static final String STARRED_SESSION_LIVESTREAM_URL =
"starred_session_livestream_url";
/**
* The {@link Rooms#ROOM_NAME} of the first starred session in this
* block.
*/
public static final String STARRED_SESSION_ROOM_NAME = "starred_session_room_name";
/**
* The {@link Rooms#ROOM_ID} of the first starred session in this block.
*/
public static final String STARRED_SESSION_ROOM_ID = "starred_session_room_id";
/**
* The {@link Sessions#SESSION_HASHTAGS} of the first starred session in
* this block.
*/
public static final String STARRED_SESSION_HASHTAGS = "starred_session_hashtags";
/**
* The {@link Sessions#SESSION_URL} of the first starred session in this
* block.
*/
public static final String STARRED_SESSION_URL = "starred_session_url";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC, "
+ BlocksColumns.BLOCK_END + " ASC";
public static final String EMPTY_SESSIONS_SELECTION = BLOCK_TYPE + " IN ('"
+ Blocks.BLOCK_TYPE_SESSION + "','"
+ Blocks.BLOCK_TYPE_CODELAB + "','"
+ Blocks.BLOCK_TYPE_OFFICE_HOURS + "') AND "
+ SESSIONS_COUNT + " = 0";
/** Build {@link Uri} for requested {@link #BLOCK_ID}. */
public static Uri buildBlockUri(String blockId) {
return CONTENT_URI.buildUpon().appendPath(blockId).build();
}
/**
* Build {@link Uri} that references any {@link Sessions} associated
* with the requested {@link #BLOCK_ID}.
*/
public static Uri buildSessionsUri(String blockId) {
return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS).build();
}
/**
* Build {@link Uri} that references starred {@link Sessions} associated
* with the requested {@link #BLOCK_ID}.
*/
public static Uri buildStarredSessionsUri(String blockId) {
return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS)
.appendPath(PATH_STARRED).build();
}
/** Read {@link #BLOCK_ID} from {@link Blocks} {@link Uri}. */
public static String getBlockId(Uri uri) {
return uri.getPathSegments().get(1);
}
/**
* Generate a {@link #BLOCK_ID} that will always match the requested
* {@link Blocks} details.
*/
public static String generateBlockId(long startTime, long endTime) {
startTime /= DateUtils.SECOND_IN_MILLIS;
endTime /= DateUtils.SECOND_IN_MILLIS;
return ParserUtils.sanitizeId(startTime + "-" + endTime);
}
}
/**
* Tracks are overall categories for {@link Sessions} and {@link com.google.android.apps.iosched.provider.ScheduleContract.Sandbox},
* such as "Android" or "Enterprise."
*/
public static class Tracks implements TracksColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_TRACKS).build();
public static final int TRACK_META_NONE = 0;
public static final int TRACK_META_SESSIONS_ONLY = 1;
public static final int TRACK_META_SANDBOX_OFFICE_HOURS_ONLY = 2;
public static final int TRACK_META_OFFICE_HOURS_ONLY = 3;
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.track";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.track";
/** "All tracks" ID. */
public static final String ALL_TRACK_ID = "all";
/** Count of {@link Sessions} inside given track that aren't office hours. */
public static final String SESSIONS_COUNT = "sessions_count";
/** Count of {@link Sessions} inside given track that are office hours. */
public static final String OFFICE_HOURS_COUNT = "office_hours_count";
/** Count of {@link com.google.android.apps.iosched.provider.ScheduleContract.Sandbox} inside given track. */
public static final String SANDBOX_COUNT = "sandbox_count";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = TracksColumns.TRACK_LEVEL + ", "
+ TracksColumns.TRACK_ORDER_IN_LEVEL + ", "
+ TracksColumns.TRACK_NAME;
/** Build {@link Uri} for requested {@link #TRACK_ID}. */
public static Uri buildTrackUri(String trackId) {
return CONTENT_URI.buildUpon().appendPath(trackId).build();
}
/**
* Build {@link Uri} that references any {@link Sessions} associated
* with the requested {@link #TRACK_ID}.
*/
public static Uri buildSessionsUri(String trackId) {
return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_SESSIONS).build();
}
/**
* Build {@link Uri} that references any {@link com.google.android.apps.iosched.provider.ScheduleContract.Sandbox} associated with
* the requested {@link #TRACK_ID}.
*/
public static Uri buildSandboxUri(String trackId) {
return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_SANDBOX).build();
}
/** Read {@link #TRACK_ID} from {@link Tracks} {@link Uri}. */
public static String getTrackId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
/**
* Rooms are physical locations at the conference venue.
*/
public static class Rooms implements RoomsColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_ROOMS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.room";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.room";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = RoomsColumns.ROOM_FLOOR + " ASC, "
+ RoomsColumns.ROOM_NAME + " COLLATE NOCASE ASC";
/** Build {@link Uri} for requested {@link #ROOM_ID}. */
public static Uri buildRoomUri(String roomId) {
return CONTENT_URI.buildUpon().appendPath(roomId).build();
}
/**
* Build {@link Uri} that references any {@link Sessions} associated
* with the requested {@link #ROOM_ID}.
*/
public static Uri buildSessionsDirUri(String roomId) {
return CONTENT_URI.buildUpon().appendPath(roomId).appendPath(PATH_SESSIONS).build();
}
/** Read {@link #ROOM_ID} from {@link Rooms} {@link Uri}. */
public static String getRoomId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
/**
* Each session is a block of time that has a {@link Tracks}, a
* {@link Rooms}, and zero or more {@link Speakers}.
*/
public static class Feedback implements BaseColumns, FeedbackColumns, SyncColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_FEEDBACK).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.session_feedback";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.session_feedback";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = BaseColumns._ID + " ASC, ";
/** Build {@link Uri} to feedback for given session. */
public static Uri buildFeedbackUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId).build();
}
/** Read {@link #SESSION_ID} from {@link Feedback} {@link Uri}. */
public static String getSessionId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
public static class Sessions implements SessionsColumns, BlocksColumns, RoomsColumns,
SyncColumns, BaseColumns {
public static final String SESSION_TYPE_SESSION = "SESSION";
public static final String SESSION_TYPE_CODELAB = "CODE_LAB";
public static final String SESSION_TYPE_KEYNOTE = "KEYNOTE";
public static final String SESSION_TYPE_OFFICE_HOURS = "OFFICE_HOURS";
public static final String SESSION_TYPE_SANDBOX = "DEVELOPER_SANDBOX";
public static final String QUERY_PARAMETER_FILTER = "filter";
public static final String QUERY_VALUE_FILTER_SESSIONS_CODELABS_ONLY
= "sessions_codelabs_only"; // excludes keynote and office hours
public static final String QUERY_VALUE_FILTER_OFFICE_HOURS_ONLY = "office_hours_only";
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_SESSIONS).build();
public static final Uri CONTENT_STARRED_URI =
CONTENT_URI.buildUpon().appendPath(PATH_STARRED).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.session";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.session";
public static final String BLOCK_ID = "block_id";
public static final String ROOM_ID = "room_id";
public static final String SEARCH_SNIPPET = "search_snippet";
// TODO: shortcut primary track to offer sub-sorting here
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC,"
+ SessionsColumns.SESSION_TITLE + " COLLATE NOCASE ASC";
public static final String LIVESTREAM_SELECTION =
SESSION_LIVESTREAM_URL + " is not null AND " + SESSION_LIVESTREAM_URL + "!=''";
// Used to fetch sessions for a particular time
public static final String AT_TIME_SELECTION =
BLOCK_START + " < ? and " + BLOCK_END + " " + "> ?";
// Builds selectionArgs for {@link AT_TIME_SELECTION}
public static String[] buildAtTimeSelectionArgs(long time) {
final String timeString = String.valueOf(time);
return new String[] { timeString, timeString };
}
// Used to fetch upcoming sessions
public static final String UPCOMING_SELECTION =
BLOCK_START + " = (select min(" + BLOCK_START + ") from " +
ScheduleDatabase.Tables.BLOCKS_JOIN_SESSIONS + " where " + LIVESTREAM_SELECTION +
" and " + BLOCK_START + " >" + " ?)";
// Builds selectionArgs for {@link UPCOMING_SELECTION}
public static String[] buildUpcomingSelectionArgs(long minTime) {
return new String[] { String.valueOf(minTime) };
}
/** Build {@link Uri} for requested {@link #SESSION_ID}. */
public static Uri buildSessionUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId).build();
}
/**
* Build {@link Uri} that references any {@link Speakers} associated
* with the requested {@link #SESSION_ID}.
*/
public static Uri buildSpeakersDirUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_SPEAKERS).build();
}
/**
* Build {@link Uri} that includes track detail with list of sessions.
*/
public static Uri buildWithTracksUri() {
return CONTENT_URI.buildUpon().appendPath(PATH_WITH_TRACK).build();
}
/**
* Build {@link Uri} that includes track detail for a specific session.
*/
public static Uri buildWithTracksUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId)
.appendPath(PATH_WITH_TRACK).build();
}
/**
* Build {@link Uri} that references any {@link Tracks} associated with
* the requested {@link #SESSION_ID}.
*/
public static Uri buildTracksDirUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_TRACKS).build();
}
public static Uri buildSearchUri(String query) {
return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build();
}
public static boolean isSearchUri(Uri uri) {
List<String> pathSegments = uri.getPathSegments();
return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1));
}
/** Build {@link Uri} that references sessions in a room that have begun after the requested time **/
public static Uri buildSessionsInRoomAfterUri(String room,long time) {
return CONTENT_URI.buildUpon().appendPath(PATH_ROOM).appendPath(room).appendPath(PATH_AFTER)
.appendPath(String.valueOf(time)).build();
}
public static String getRoom(Uri uri){
return uri.getPathSegments().get(2);
}
public static String getAfter(Uri uri){
return uri.getPathSegments().get(4);
}
/** Read {@link #SESSION_ID} from {@link Sessions} {@link Uri}. */
public static String getSessionId(Uri uri) {
return uri.getPathSegments().get(1);
}
public static String getSearchQuery(Uri uri) {
return uri.getPathSegments().get(2);
}
}
/**
* Speakers are individual people that lead {@link Sessions}.
*/
public static class Speakers implements SpeakersColumns, SyncColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_SPEAKERS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.speaker";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.speaker";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = SpeakersColumns.SPEAKER_NAME
+ " COLLATE NOCASE ASC";
/** Build {@link Uri} for requested {@link #SPEAKER_ID}. */
public static Uri buildSpeakerUri(String speakerId) {
return CONTENT_URI.buildUpon().appendPath(speakerId).build();
}
/**
* Build {@link Uri} that references any {@link Sessions} associated
* with the requested {@link #SPEAKER_ID}.
*/
public static Uri buildSessionsDirUri(String speakerId) {
return CONTENT_URI.buildUpon().appendPath(speakerId).appendPath(PATH_SESSIONS).build();
}
/** Read {@link #SPEAKER_ID} from {@link Speakers} {@link Uri}. */
public static String getSpeakerId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
/**
* Each sandbox company is a company appearing at the conference that may be
* associated with a specific {@link Tracks} and time block.
*/
public static class Sandbox implements SandboxColumns, SyncColumns, BlocksColumns, RoomsColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_SANDBOX).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.sandbox";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.sandbox";
/** {@link Tracks#TRACK_ID} that this sandbox company belongs to. */
public static final String TRACK_ID = "track_id";
// Used to fetch sandbox companies at a particular time
public static final String AT_TIME_IN_ROOM_SELECTION =
BLOCK_START + " < ? and " + BLOCK_END + " " + "> ? and " + " SANDBOX.ROOM_ID = ?";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = SandboxColumns.COMPANY_NAME
+ " COLLATE NOCASE ASC";
// Builds selectionArgs for {@link AT_TIME_SELECTION}
public static String[] buildAtTimeInRoomSelectionArgs(long time, String roomId) {
final String timeString = String.valueOf(time);
return new String[] { timeString, timeString, roomId };
}
/** Build {@link Uri} for requested {@link #COMPANY_ID}. */
public static Uri buildCompanyUri(String companyId) {
return CONTENT_URI.buildUpon().appendPath(companyId).build();
}
/** Read {@link #COMPANY_ID} from {@link com.google.android.apps.iosched.provider.ScheduleContract.Sandbox} {@link Uri}. */
public static String getCompanyId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
/**
* Announcements of breaking news
*/
public static class Announcements implements AnnouncementsColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_ANNOUNCEMENTS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.announcement";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.announcement";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = AnnouncementsColumns.ANNOUNCEMENT_DATE
+ " COLLATE NOCASE DESC";
/** Build {@link Uri} for requested {@link #ANNOUNCEMENT_ID}. */
public static Uri buildAnnouncementUri(String announcementId) {
return CONTENT_URI.buildUpon().appendPath(announcementId).build();
}
/**
* Read {@link #ANNOUNCEMENT_ID} from {@link Announcements} {@link Uri}.
*/
public static String getAnnouncementId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
/**
* TileProvider entries are used to create an overlay provider for the map.
*/
public static class MapTiles implements MapTileColumns, BaseColumns {
public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon()
.appendPath(PATH_MAP_TILES).build();
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.maptiles";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.maptiles";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = MapTileColumns.TILE_FLOOR + " ASC";
/** Build {@link Uri} for all overlay zoom entries */
public static Uri buildUri() {
return CONTENT_URI;
}
/** Build {@link Uri} for requested floor. */
public static Uri buildFloorUri(String floor) {
return CONTENT_URI.buildUpon()
.appendPath(String.valueOf(floor)).build();
}
/** Read floor from {@link MapMarkers} {@link Uri}. */
public static String getFloorId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
/**
* Markers refer to marked positions on the map.
*/
public static class MapMarkers implements MapMarkerColumns, BaseColumns {
public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon()
.appendPath(PATH_MAP_MARKERS).build();
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.mapmarker";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.mapmarker";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = MapMarkerColumns.MARKER_FLOOR
+ " ASC, " + MapMarkerColumns.MARKER_ID + " ASC";
/** Build {@link Uri} for requested {@link #MARKER_ID}. */
public static Uri buildMarkerUri(String markerId) {
return CONTENT_URI.buildUpon().appendPath(markerId).build();
}
/** Build {@link Uri} for all markers */
public static Uri buildMarkerUri() {
return CONTENT_URI;
}
/** Build {@link Uri} for requested {@link #MARKER_ID}. */
public static Uri buildFloorUri(int floor) {
return CONTENT_URI.buildUpon().appendPath(PATH_MAP_FLOOR)
.appendPath("" + floor).build();
}
/** Read {@link #MARKER_ID} from {@link MapMarkers} {@link Uri}. */
public static String getMarkerId(Uri uri) {
return uri.getPathSegments().get(1);
}
/** Read {@link #FLOOR} from {@link MapMarkers} {@link Uri}. */
public static String getMarkerFloor(Uri uri) {
return uri.getPathSegments().get(2);
}
}
public static class SearchSuggest {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_SEARCH_SUGGEST).build();
public static final String DEFAULT_SORT = SearchManager.SUGGEST_COLUMN_TEXT_1
+ " COLLATE NOCASE ASC";
}
public static class SearchIndex {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_SEARCH_INDEX).build();
}
public static Uri addCallerIsSyncAdapterParameter(Uri uri) {
return uri.buildUpon().appendQueryParameter(
ContactsContract.CALLER_IS_SYNCADAPTER, "true").build();
}
public static boolean hasCallerIsSyncAdapterParameter(Uri uri) {
return TextUtils.equals("true",
uri.getQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER));
}
private ScheduleContract() {
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.provider;
import android.accounts.Account;
import android.content.ContentResolver;
import com.google.android.apps.iosched.provider.ScheduleContract.AnnouncementsColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Blocks;
import com.google.android.apps.iosched.provider.ScheduleContract.BlocksColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.FeedbackColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.MapMarkerColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.MapTileColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Rooms;
import com.google.android.apps.iosched.provider.ScheduleContract.RoomsColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.provider.ScheduleContract.SessionsColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Speakers;
import com.google.android.apps.iosched.provider.ScheduleContract.SpeakersColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Tracks;
import com.google.android.apps.iosched.provider.ScheduleContract.TracksColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Sandbox;
import android.app.SearchManager;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import com.google.android.apps.iosched.sync.SyncHelper;
import com.google.android.apps.iosched.util.AccountUtils;
import static com.google.android.apps.iosched.util.LogUtils.*;
/**
* Helper for managing {@link SQLiteDatabase} that stores data for
* {@link ScheduleProvider}.
*/
public class ScheduleDatabase extends SQLiteOpenHelper {
private static final String TAG = makeLogTag(ScheduleDatabase.class);
private static final String DATABASE_NAME = "schedule.db";
// NOTE: carefully update onUpgrade() when bumping database versions to make
// sure user data is saved.
private static final int VER_2013_LAUNCH = 104; // 1.0
private static final int VER_2013_RM2 = 105; // 1.1
private static final int DATABASE_VERSION = VER_2013_RM2;
private final Context mContext;
interface Tables {
String BLOCKS = "blocks";
String TRACKS = "tracks";
String ROOMS = "rooms";
String SESSIONS = "sessions";
String SPEAKERS = "speakers";
String SESSIONS_SPEAKERS = "sessions_speakers";
String SESSIONS_TRACKS = "sessions_tracks";
String SANDBOX = "sandbox";
String ANNOUNCEMENTS = "announcements";
String MAPMARKERS = "mapmarkers";
String MAPTILES = "mapoverlays";
String FEEDBACK = "feedback";
String SESSIONS_SEARCH = "sessions_search";
String SEARCH_SUGGEST = "search_suggest";
String SESSIONS_JOIN_BLOCKS_ROOMS = "sessions "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SESSIONS_JOIN_ROOMS = "sessions "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SANDBOX_JOIN_TRACKS_BLOCKS_ROOMS = "sandbox "
+ "LEFT OUTER JOIN tracks ON sandbox.track_id=tracks.track_id "
+ "LEFT OUTER JOIN blocks ON sandbox.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sandbox.room_id=rooms.room_id";
String SESSIONS_SPEAKERS_JOIN_SPEAKERS = "sessions_speakers "
+ "LEFT OUTER JOIN speakers ON sessions_speakers.speaker_id=speakers.speaker_id";
String SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_speakers "
+ "LEFT OUTER JOIN sessions ON sessions_speakers.session_id=sessions.session_id "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SESSIONS_TRACKS_JOIN_TRACKS = "sessions_tracks "
+ "LEFT OUTER JOIN tracks ON sessions_tracks.track_id=tracks.track_id";
String SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_tracks "
+ "LEFT OUTER JOIN sessions ON sessions_tracks.session_id=sessions.session_id "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_search "
+ "LEFT OUTER JOIN sessions ON sessions_search.session_id=sessions.session_id "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SESSIONS_JOIN_TRACKS_JOIN_BLOCKS = "sessions "
+ "LEFT OUTER JOIN sessions_tracks ON "
+ "sessions_tracks.session_id=sessions.session_id "
+ "LEFT OUTER JOIN tracks ON tracks.track_id=sessions_tracks.track_id "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id";
String BLOCKS_JOIN_SESSIONS = "blocks "
+ "LEFT OUTER JOIN sessions ON blocks.block_id=sessions.block_id";
String MAPMARKERS_JOIN_TRACKS = "mapmarkers "
+ "LEFT OUTER JOIN tracks ON tracks.track_id=mapmarkers.track_id ";
}
private interface Triggers {
// Deletes from session_tracks and sessions_speakers when corresponding sessions
// are deleted.
String SESSIONS_TRACKS_DELETE = "sessions_tracks_delete";
String SESSIONS_SPEAKERS_DELETE = "sessions_speakers_delete";
String SESSIONS_FEEDBACK_DELETE = "sessions_feedback_delete";
}
public interface SessionsSpeakers {
String SESSION_ID = "session_id";
String SPEAKER_ID = "speaker_id";
}
public interface SessionsTracks {
String SESSION_ID = "session_id";
String TRACK_ID = "track_id";
}
interface SessionsSearchColumns {
String SESSION_ID = "session_id";
String BODY = "body";
}
/** Fully-qualified field names. */
private interface Qualified {
String SESSIONS_SEARCH = Tables.SESSIONS_SEARCH + "(" + SessionsSearchColumns.SESSION_ID
+ "," + SessionsSearchColumns.BODY + ")";
String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "."
+ SessionsTracks.SESSION_ID;
String SESSIONS_SPEAKERS_SESSION_ID = Tables.SESSIONS_SPEAKERS+ "."
+ SessionsSpeakers.SESSION_ID;
String SESSIONS_SPEAKERS_SPEAKER_ID = Tables.SESSIONS_SPEAKERS+ "."
+ SessionsSpeakers.SPEAKER_ID;
String SPEAKERS_SPEAKER_ID = Tables.SPEAKERS + "." + Speakers.SPEAKER_ID;
String FEEDBACK_SESSION_ID = Tables.FEEDBACK + "." + FeedbackColumns.SESSION_ID;
}
/** {@code REFERENCES} clauses. */
private interface References {
String BLOCK_ID = "REFERENCES " + Tables.BLOCKS + "(" + Blocks.BLOCK_ID + ")";
String TRACK_ID = "REFERENCES " + Tables.TRACKS + "(" + Tracks.TRACK_ID + ")";
String ROOM_ID = "REFERENCES " + Tables.ROOMS + "(" + Rooms.ROOM_ID + ")";
String SESSION_ID = "REFERENCES " + Tables.SESSIONS + "(" + Sessions.SESSION_ID + ")";
String SPEAKER_ID = "REFERENCES " + Tables.SPEAKERS + "(" + Speakers.SPEAKER_ID + ")";
}
public ScheduleDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + Tables.BLOCKS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ BlocksColumns.BLOCK_ID + " TEXT NOT NULL,"
+ BlocksColumns.BLOCK_TITLE + " TEXT NOT NULL,"
+ BlocksColumns.BLOCK_START + " INTEGER NOT NULL,"
+ BlocksColumns.BLOCK_END + " INTEGER NOT NULL,"
+ BlocksColumns.BLOCK_TYPE + " TEXT,"
+ BlocksColumns.BLOCK_META + " TEXT,"
+ "UNIQUE (" + BlocksColumns.BLOCK_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.TRACKS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ TracksColumns.TRACK_ID + " TEXT NOT NULL,"
+ TracksColumns.TRACK_NAME + " TEXT,"
+ TracksColumns.TRACK_COLOR + " INTEGER,"
+ TracksColumns.TRACK_LEVEL + " INTEGER,"
+ TracksColumns.TRACK_ORDER_IN_LEVEL + " INTEGER,"
+ TracksColumns.TRACK_META + " INTEGER NOT NULL DEFAULT 0,"
+ TracksColumns.TRACK_ABSTRACT + " TEXT,"
+ TracksColumns.TRACK_HASHTAG + " TEXT,"
+ "UNIQUE (" + TracksColumns.TRACK_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.ROOMS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ RoomsColumns.ROOM_ID + " TEXT NOT NULL,"
+ RoomsColumns.ROOM_NAME + " TEXT,"
+ RoomsColumns.ROOM_FLOOR + " TEXT,"
+ "UNIQUE (" + RoomsColumns.ROOM_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.SESSIONS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ SessionsColumns.SESSION_ID + " TEXT NOT NULL,"
+ Sessions.BLOCK_ID + " TEXT " + References.BLOCK_ID + ","
+ Sessions.ROOM_ID + " TEXT " + References.ROOM_ID + ","
+ SessionsColumns.SESSION_TYPE + " TEXT,"
+ SessionsColumns.SESSION_LEVEL + " TEXT,"
+ SessionsColumns.SESSION_TITLE + " TEXT,"
+ SessionsColumns.SESSION_ABSTRACT + " TEXT,"
+ SessionsColumns.SESSION_REQUIREMENTS + " TEXT,"
+ SessionsColumns.SESSION_TAGS + " TEXT,"
+ SessionsColumns.SESSION_HASHTAGS + " TEXT,"
+ SessionsColumns.SESSION_URL + " TEXT,"
+ SessionsColumns.SESSION_YOUTUBE_URL + " TEXT,"
+ SessionsColumns.SESSION_MODERATOR_URL + " TEXT,"
+ SessionsColumns.SESSION_PDF_URL + " TEXT,"
+ SessionsColumns.SESSION_NOTES_URL + " TEXT,"
+ SessionsColumns.SESSION_STARRED + " INTEGER NOT NULL DEFAULT 0,"
+ SessionsColumns.SESSION_CAL_EVENT_ID + " INTEGER,"
+ SessionsColumns.SESSION_LIVESTREAM_URL + " TEXT,"
+ "UNIQUE (" + SessionsColumns.SESSION_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.SPEAKERS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ SpeakersColumns.SPEAKER_ID + " TEXT NOT NULL,"
+ SpeakersColumns.SPEAKER_NAME + " TEXT,"
+ SpeakersColumns.SPEAKER_IMAGE_URL + " TEXT,"
+ SpeakersColumns.SPEAKER_COMPANY + " TEXT,"
+ SpeakersColumns.SPEAKER_ABSTRACT + " TEXT,"
+ SpeakersColumns.SPEAKER_URL + " TEXT,"
+ "UNIQUE (" + SpeakersColumns.SPEAKER_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.SESSIONS_SPEAKERS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SessionsSpeakers.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + ","
+ SessionsSpeakers.SPEAKER_ID + " TEXT NOT NULL " + References.SPEAKER_ID + ","
+ "UNIQUE (" + SessionsSpeakers.SESSION_ID + ","
+ SessionsSpeakers.SPEAKER_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.SESSIONS_TRACKS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SessionsTracks.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + ","
+ SessionsTracks.TRACK_ID + " TEXT NOT NULL " + References.TRACK_ID
+ ")");
db.execSQL("CREATE TABLE " + Tables.SANDBOX + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ ScheduleContract.SandboxColumns.COMPANY_ID + " TEXT NOT NULL,"
+ Sandbox.TRACK_ID + " TEXT " + References.TRACK_ID + ","
+ Sandbox.BLOCK_ID + " TEXT " + References.BLOCK_ID + ","
+ Sandbox.ROOM_ID + " TEXT " + References.ROOM_ID + ","
+ ScheduleContract.SandboxColumns.COMPANY_NAME + " TEXT,"
+ ScheduleContract.SandboxColumns.COMPANY_DESC + " TEXT,"
+ ScheduleContract.SandboxColumns.COMPANY_URL + " TEXT,"
+ ScheduleContract.SandboxColumns.COMPANY_LOGO_URL + " TEXT,"
+ "UNIQUE (" + ScheduleContract.SandboxColumns.COMPANY_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.ANNOUNCEMENTS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ AnnouncementsColumns.ANNOUNCEMENT_ID + " TEXT,"
+ AnnouncementsColumns.ANNOUNCEMENT_TITLE + " TEXT NOT NULL,"
+ AnnouncementsColumns.ANNOUNCEMENT_ACTIVITY_JSON + " BLOB,"
+ AnnouncementsColumns.ANNOUNCEMENT_URL + " TEXT,"
+ AnnouncementsColumns.ANNOUNCEMENT_DATE + " INTEGER NOT NULL)");
db.execSQL("CREATE TABLE " + Tables.MAPTILES + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ MapTileColumns.TILE_FLOOR+ " INTEGER NOT NULL,"
+ MapTileColumns.TILE_FILE+ " TEXT NOT NULL,"
+ MapTileColumns.TILE_URL+ " TEXT NOT NULL,"
+ "UNIQUE (" + MapTileColumns.TILE_FLOOR+ ") ON CONFLICT REPLACE)");
doMigration2013RM2(db);
// Full-text search index. Update using updateSessionSearchIndex method.
// Use the porter tokenizer for simple stemming, so that "frustration" matches "frustrated."
db.execSQL("CREATE VIRTUAL TABLE " + Tables.SESSIONS_SEARCH + " USING fts3("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SessionsSearchColumns.BODY + " TEXT NOT NULL,"
+ SessionsSearchColumns.SESSION_ID
+ " TEXT NOT NULL " + References.SESSION_ID + ","
+ "UNIQUE (" + SessionsSearchColumns.SESSION_ID + ") ON CONFLICT REPLACE,"
+ "tokenize=porter)");
// Search suggestions
db.execSQL("CREATE TABLE " + Tables.SEARCH_SUGGEST + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SearchManager.SUGGEST_COLUMN_TEXT_1 + " TEXT NOT NULL)");
// Session deletion triggers
db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_TRACKS_DELETE + " AFTER DELETE ON "
+ Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.SESSIONS_TRACKS + " "
+ " WHERE " + Qualified.SESSIONS_TRACKS_SESSION_ID + "=old." + Sessions.SESSION_ID
+ ";" + " END;");
db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SPEAKERS_DELETE + " AFTER DELETE ON "
+ Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.SESSIONS_SPEAKERS + " "
+ " WHERE " + Qualified.SESSIONS_SPEAKERS_SESSION_ID + "=old." + Sessions.SESSION_ID
+ ";" + " END;");
}
private void doMigration2013RM2(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + Tables.FEEDBACK + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ Sessions.SESSION_ID + " TEXT " + References.SESSION_ID + ","
+ FeedbackColumns.SESSION_RATING + " INTEGER NOT NULL,"
+ FeedbackColumns.ANSWER_RELEVANCE + " INTEGER NOT NULL,"
+ FeedbackColumns.ANSWER_CONTENT + " INTEGER NOT NULL,"
+ FeedbackColumns.ANSWER_SPEAKER + " INTEGER NOT NULL,"
+ FeedbackColumns.ANSWER_WILLUSE + " INTEGER NOT NULL,"
+ FeedbackColumns.COMMENTS + " TEXT)");
db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_FEEDBACK_DELETE + " AFTER DELETE ON "
+ Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.FEEDBACK + " "
+ " WHERE " + Qualified.FEEDBACK_SESSION_ID + "=old." + Sessions.SESSION_ID
+ ";" + " END;");
db.execSQL("CREATE TABLE " + Tables.MAPMARKERS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ MapMarkerColumns.MARKER_ID+ " TEXT NOT NULL,"
+ MapMarkerColumns.MARKER_TYPE+ " TEXT NOT NULL,"
+ MapMarkerColumns.MARKER_LATITUDE+ " DOUBLE NOT NULL,"
+ MapMarkerColumns.MARKER_LONGITUDE+ " DOUBLE NOT NULL,"
+ MapMarkerColumns.MARKER_LABEL+ " TEXT,"
+ MapMarkerColumns.MARKER_FLOOR+ " INTEGER NOT NULL,"
+ MapMarkerColumns.MARKER_TRACK+ " TEXT,"
+ "UNIQUE (" + MapMarkerColumns.MARKER_ID + ") ON CONFLICT REPLACE)");
}
/**
* Updates the session search index. This should be done sparingly, as the queries are rather
* complex.
*/
static void updateSessionSearchIndex(SQLiteDatabase db) {
db.execSQL("DELETE FROM " + Tables.SESSIONS_SEARCH);
db.execSQL("INSERT INTO " + Qualified.SESSIONS_SEARCH
+ " SELECT s." + Sessions.SESSION_ID + ",("
// Full text body
+ Sessions.SESSION_TITLE + "||'; '||"
+ Sessions.SESSION_ABSTRACT + "||'; '||"
+ "IFNULL(" + Sessions.SESSION_TAGS + ",'')||'; '||"
+ "IFNULL(GROUP_CONCAT(t." + Speakers.SPEAKER_NAME + ",' '),'')||'; '||"
+ "'')"
+ " FROM " + Tables.SESSIONS + " s "
+ " LEFT OUTER JOIN"
// Subquery resulting in session_id, speaker_id, speaker_name
+ "(SELECT " + Sessions.SESSION_ID + "," + Qualified.SPEAKERS_SPEAKER_ID
+ "," + Speakers.SPEAKER_NAME
+ " FROM " + Tables.SESSIONS_SPEAKERS
+ " INNER JOIN " + Tables.SPEAKERS
+ " ON " + Qualified.SESSIONS_SPEAKERS_SPEAKER_ID + "="
+ Qualified.SPEAKERS_SPEAKER_ID
+ ") t"
// Grand finale
+ " ON s." + Sessions.SESSION_ID + "=t." + Sessions.SESSION_ID
+ " GROUP BY s." + Sessions.SESSION_ID);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
LOGD(TAG, "onUpgrade() from " + oldVersion + " to " + newVersion);
// Cancel any sync currently in progress
Account account = AccountUtils.getChosenAccount(mContext);
if (account != null) {
LOGI(TAG, "Cancelling any pending syncs for for account");
ContentResolver.cancelSync(account, ScheduleContract.CONTENT_AUTHORITY);
}
// NOTE: This switch statement is designed to handle cascading database
// updates, starting at the current version and falling through to all
// future upgrade cases. Only use "break;" when you want to drop and
// recreate the entire database.
int version = oldVersion;
switch (version) {
// Note: Data from prior years not preserved.
case VER_2013_LAUNCH:
LOGI(TAG, "Performing migration for DB version " + version);
// Reset BLOCKS table
db.execSQL("DELETE FROM " + Tables.BLOCKS);
// Reset MapMarkers table
db.execSQL("DROP TABLE IF EXISTS " + Tables.MAPMARKERS);
// Apply new schema changes
doMigration2013RM2(db);
case VER_2013_RM2:
version = VER_2013_RM2;
LOGI(TAG, "DB at version " + version);
// Current version, no further action necessary
}
LOGD(TAG, "after upgrade logic, at version " + version);
if (version != DATABASE_VERSION) {
LOGW(TAG, "Destroying old data during upgrade");
db.execSQL("DROP TABLE IF EXISTS " + Tables.BLOCKS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.TRACKS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.ROOMS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SPEAKERS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SPEAKERS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_TRACKS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SANDBOX);
db.execSQL("DROP TABLE IF EXISTS " + Tables.ANNOUNCEMENTS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.FEEDBACK);
db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_TRACKS_DELETE);
db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SPEAKERS_DELETE);
db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_FEEDBACK_DELETE);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SEARCH);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SEARCH_SUGGEST);
db.execSQL("DROP TABLE IF EXISTS " + Tables.MAPMARKERS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.MAPTILES);
onCreate(db);
}
if (account != null) {
LOGI(TAG, "DB upgrade complete. Requesting resync.");
SyncHelper.requestManualSync(account);
}
}
public static void deleteDatabase(Context context) {
context.deleteDatabase(DATABASE_NAME);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.util;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ShareCompat;
import android.view.ActionProvider;
import android.view.MenuItem;
import android.widget.ShareActionProvider;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.appwidget.ScheduleWidgetProvider;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.service.ScheduleUpdaterService;
import com.google.android.apps.iosched.ui.MapFragment;
import com.google.android.apps.iosched.ui.SocialStreamActivity;
import com.google.android.apps.iosched.ui.SocialStreamFragment;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Helper class for dealing with common actions to take on a session.
*/
public final class SessionsHelper {
private static final String TAG = makeLogTag(SessionsHelper.class);
private final Activity mActivity;
public SessionsHelper(Activity activity) {
mActivity = activity;
}
public void startMapActivity(String roomId) {
Intent intent = new Intent(mActivity.getApplicationContext(),
UIUtils.getMapActivityClass(mActivity));
intent.putExtra(MapFragment.EXTRA_ROOM, roomId);
mActivity.startActivity(intent);
}
public Intent createShareIntent(int messageTemplateResId, String title, String hashtags,
String url) {
ShareCompat.IntentBuilder builder = ShareCompat.IntentBuilder.from(mActivity)
.setType("text/plain")
.setText(mActivity.getString(messageTemplateResId,
title, UIUtils.getSessionHashtagsString(hashtags), url));
return builder.getIntent();
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void tryConfigureShareMenuItem(MenuItem menuItem, int messageTemplateResId,
final String title, String hashtags, String url) {
if (UIUtils.hasICS()) {
ActionProvider itemProvider = menuItem.getActionProvider();
ShareActionProvider provider;
if (!(itemProvider instanceof ShareActionProvider)) {
provider = new ShareActionProvider(mActivity);
} else {
provider = (ShareActionProvider) itemProvider;
}
provider.setShareIntent(createShareIntent(messageTemplateResId, title, hashtags, url));
provider.setOnShareTargetSelectedListener(
new ShareActionProvider.OnShareTargetSelectedListener() {
@Override
public boolean onShareTargetSelected(ShareActionProvider source, Intent intent) {
EasyTracker.getTracker().sendEvent("Session", "Shared", title, 0L);
LOGD("Tracker", "Shared: " + title);
return false;
}
});
menuItem.setActionProvider(provider);
}
}
public void shareSession(Context context, int messageTemplateResId, String title,
String hashtags, String url) {
EasyTracker.getTracker().sendEvent("Session", "Shared", title, 0L);
LOGD("Tracker", "Shared: " + title);
context.startActivity(Intent.createChooser(
createShareIntent(messageTemplateResId, title, hashtags, url),
context.getString(R.string.title_share)));
}
public void setSessionStarred(Uri sessionUri, boolean starred, String title) {
LOGD(TAG, "setSessionStarred uri=" + sessionUri + " starred=" +
starred + " title=" + title);
sessionUri = ScheduleContract.addCallerIsSyncAdapterParameter(sessionUri);
final ContentValues values = new ContentValues();
values.put(ScheduleContract.Sessions.SESSION_STARRED, starred);
AsyncQueryHandler handler =
new AsyncQueryHandler(mActivity.getContentResolver()) {
};
handler.startUpdate(-1, null, sessionUri, values, null, null);
EasyTracker.getTracker().sendEvent(
"Session", starred ? "Starred" : "Unstarred", title, 0L);
// Because change listener is set to null during initialization, these
// won't fire on pageview.
mActivity.sendBroadcast(ScheduleWidgetProvider.getRefreshBroadcastIntent(mActivity, false));
// Sync to the cloudz.
uploadStarredSession(mActivity, sessionUri, starred);
}
public static void uploadStarredSession(Context context, Uri sessionUri, boolean starred) {
final Intent updateServerIntent = new Intent(context, ScheduleUpdaterService.class);
updateServerIntent.putExtra(ScheduleUpdaterService.EXTRA_SESSION_ID,
ScheduleContract.Sessions.getSessionId(sessionUri));
updateServerIntent.putExtra(ScheduleUpdaterService.EXTRA_IN_SCHEDULE, starred);
context.startService(updateServerIntent);
}
public void startSocialStream(String hashtags) {
Intent intent = new Intent(mActivity, SocialStreamActivity.class);
intent.putExtra(SocialStreamFragment.EXTRA_QUERY, UIUtils.getSessionHashtagsString(hashtags));
mActivity.startActivity(intent);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.util;
import com.google.android.apps.iosched.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.TextView;
/**
* This is a set of helper methods for showing contextual help information in the app.
*/
public class HelpUtils {
public static void showAbout(FragmentActivity activity) {
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("dialog_about");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
new AboutDialog().show(ft, "dialog_about");
}
public static class AboutDialog extends DialogFragment {
private static final String VERSION_UNAVAILABLE = "N/A";
public AboutDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get app version
PackageManager pm = getActivity().getPackageManager();
String packageName = getActivity().getPackageName();
String versionName;
try {
PackageInfo info = pm.getPackageInfo(packageName, 0);
versionName = info.versionName;
} catch (PackageManager.NameNotFoundException e) {
versionName = VERSION_UNAVAILABLE;
}
// Build the about body view and append the link to see OSS licenses
SpannableStringBuilder aboutBody = new SpannableStringBuilder();
aboutBody.append(Html.fromHtml(getString(R.string.about_body, versionName)));
SpannableString licensesLink = new SpannableString(getString(R.string.about_licenses));
licensesLink.setSpan(new ClickableSpan() {
@Override
public void onClick(View view) {
HelpUtils.showOpenSourceLicenses(getActivity());
}
}, 0, licensesLink.length(), 0);
aboutBody.append("\n\n");
aboutBody.append(licensesLink);
SpannableString eulaLink = new SpannableString(getString(R.string.about_eula));
eulaLink.setSpan(new ClickableSpan() {
@Override
public void onClick(View view) {
HelpUtils.showEula(getActivity());
}
}, 0, eulaLink.length(), 0);
aboutBody.append("\n\n");
aboutBody.append(eulaLink);
LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
TextView aboutBodyView = (TextView) layoutInflater.inflate(R.layout.dialog_about, null);
aboutBodyView.setText(aboutBody);
aboutBodyView.setMovementMethod(new LinkMovementMethod());
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.title_about)
.setView(aboutBodyView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
)
.create();
}
}
public static void showOpenSourceLicenses(FragmentActivity activity) {
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("dialog_licenses");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
new OpenSourceLicensesDialog().show(ft, "dialog_licenses");
}
public static class OpenSourceLicensesDialog extends DialogFragment {
public OpenSourceLicensesDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
WebView webView = new WebView(getActivity());
webView.loadUrl("file:///android_asset/licenses.html");
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.about_licenses)
.setView(webView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
)
.create();
}
}
public static void showEula(FragmentActivity activity) {
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("dialog_eula");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
new EulaDialog().show(ft, "dialog_eula");
}
public static class EulaDialog extends DialogFragment {
public EulaDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int padding = getResources().getDimensionPixelSize(R.dimen.content_padding_normal);
TextView eulaTextView = new TextView(getActivity());
eulaTextView.setText(Html.fromHtml(getString(R.string.eula_text)));
eulaTextView.setMovementMethod(LinkMovementMethod.getInstance());
eulaTextView.setPadding(padding, padding, padding, padding);
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.about_eula)
.setView(eulaTextView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
)
.create();
}
}
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* 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 com.google.android.apps.iosched.util;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
/**
* Helper for Google Play services-related operations.
*/
public class PlayServicesUtils {
public static boolean checkGooglePlaySevices(final Activity activity) {
final int googlePlayServicesCheck = GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity);
switch (googlePlayServicesCheck) {
case ConnectionResult.SUCCESS:
return true;
case ConnectionResult.SERVICE_DISABLED:
case ConnectionResult.SERVICE_INVALID:
case ConnectionResult.SERVICE_MISSING:
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(googlePlayServicesCheck, activity, 0);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
activity.finish();
}
});
dialog.show();
}
return false;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.util;
import java.util.ArrayList;
import java.util.Collections;
/**
* Provides static methods for creating {@code List} instances easily, and other
* utility methods for working with lists.
*/
public class Lists {
/**
* Creates an empty {@code ArrayList} instance.
*
* <p><b>Note:</b> if you only need an <i>immutable</i> empty List, use
* {@link Collections#emptyList} instead.
*
* @return a newly-created, initially-empty {@code ArrayList}
*/
public static <E> ArrayList<E> newArrayList() {
return new ArrayList<E>();
}
/**
* Creates a resizable {@code ArrayList} instance containing the given
* elements.
*
* <p><b>Note:</b> due to a bug in javac 1.5.0_06, we cannot support the
* following:
*
* <p>{@code List<Base> list = Lists.newArrayList(sub1, sub2);}
*
* <p>where {@code sub1} and {@code sub2} are references to subtypes of
* {@code Base}, not of {@code Base} itself. To get around this, you must
* use:
*
* <p>{@code List<Base> list = Lists.<Base>newArrayList(sub1, sub2);}
*
* @param elements the elements that the list should contain, in order
* @return a newly-created {@code ArrayList} containing those elements
*/
public static <E> ArrayList<E> newArrayList(E... elements) {
int capacity = (elements.length * 110) / 100 + 5;
ArrayList<E> list = new ArrayList<E>(capacity);
Collections.addAll(list, elements);
return list;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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.
*/
/*
* Modifications:
* -Imported from AOSP frameworks/base/core/java/com/android/internal/content
* -Changed package name
*/
package com.google.android.apps.iosched.util;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Helper for building selection clauses for {@link SQLiteDatabase}. Each
* appended clause is combined using {@code AND}. This class is <em>not</em>
* thread safe.
*/
public class SelectionBuilder {
private static final String TAG = makeLogTag(SelectionBuilder.class);
private String mTable = null;
private Map<String, String> mProjectionMap = Maps.newHashMap();
private StringBuilder mSelection = new StringBuilder();
private ArrayList<String> mSelectionArgs = Lists.newArrayList();
/**
* Reset any internal state, allowing this builder to be recycled.
*/
public SelectionBuilder reset() {
mTable = null;
mSelection.setLength(0);
mSelectionArgs.clear();
return this;
}
/**
* Append the given selection clause to the internal state. Each clause is
* surrounded with parenthesis and combined using {@code AND}.
*/
public SelectionBuilder where(String selection, String... selectionArgs) {
if (TextUtils.isEmpty(selection)) {
if (selectionArgs != null && selectionArgs.length > 0) {
throw new IllegalArgumentException(
"Valid selection required when including arguments=");
}
// Shortcut when clause is empty
return this;
}
if (mSelection.length() > 0) {
mSelection.append(" AND ");
}
mSelection.append("(").append(selection).append(")");
if (selectionArgs != null) {
Collections.addAll(mSelectionArgs, selectionArgs);
}
return this;
}
public SelectionBuilder table(String table) {
mTable = table;
return this;
}
private void assertTable() {
if (mTable == null) {
throw new IllegalStateException("Table not specified");
}
}
public SelectionBuilder mapToTable(String column, String table) {
mProjectionMap.put(column, table + "." + column);
return this;
}
public SelectionBuilder map(String fromColumn, String toClause) {
mProjectionMap.put(fromColumn, toClause + " AS " + fromColumn);
return this;
}
/**
* Return selection string for current internal state.
*
* @see #getSelectionArgs()
*/
public String getSelection() {
return mSelection.toString();
}
/**
* Return selection arguments for current internal state.
*
* @see #getSelection()
*/
public String[] getSelectionArgs() {
return mSelectionArgs.toArray(new String[mSelectionArgs.size()]);
}
private void mapColumns(String[] columns) {
for (int i = 0; i < columns.length; i++) {
final String target = mProjectionMap.get(columns[i]);
if (target != null) {
columns[i] = target;
}
}
}
@Override
public String toString() {
return "SelectionBuilder[table=" + mTable + ", selection=" + getSelection()
+ ", selectionArgs=" + Arrays.toString(getSelectionArgs()) + "]";
}
/**
* Execute query using the current internal state as {@code WHERE} clause.
*/
public Cursor query(SQLiteDatabase db, String[] columns, String orderBy) {
return query(db, columns, null, null, orderBy, null);
}
/**
* Execute query using the current internal state as {@code WHERE} clause.
*/
public Cursor query(SQLiteDatabase db, String[] columns, String groupBy,
String having, String orderBy, String limit) {
assertTable();
if (columns != null) mapColumns(columns);
LOGV(TAG, "query(columns=" + Arrays.toString(columns) + ") " + this);
return db.query(mTable, columns, getSelection(), getSelectionArgs(), groupBy, having,
orderBy, limit);
}
/**
* Execute update using the current internal state as {@code WHERE} clause.
*/
public int update(SQLiteDatabase db, ContentValues values) {
assertTable();
LOGV(TAG, "update() " + this);
return db.update(mTable, values, getSelection(), getSelectionArgs());
}
/**
* Execute delete using the current internal state as {@code WHERE} clause.
*/
public int delete(SQLiteDatabase db) {
assertTable();
LOGV(TAG, "delete() " + this);
return db.delete(mTable, getSelection(), getSelectionArgs());
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.util;
import android.content.Context;
import android.content.pm.PackageManager;
import com.google.android.apps.iosched.Config;
import static com.google.android.apps.iosched.util.LogUtils.*;
public class NetUtils {
private static final String TAG = makeLogTag(AccountUtils.class);
private static String mUserAgent = null;
public static String getUserAgent(Context mContext) {
if (mUserAgent == null) {
mUserAgent = Config.APP_NAME;
try {
String packageName = mContext.getPackageName();
String version = mContext.getPackageManager().getPackageInfo(packageName, 0).versionName;
mUserAgent = mUserAgent + " (" + packageName + "/" + version + ")";
LOGD(TAG, "User agent set to: " + mUserAgent);
} catch (PackageManager.NameNotFoundException e) {
LOGE(TAG, "Unable to find self by package name", e);
}
}
return mUserAgent;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.util;
import java.lang.reflect.InvocationTargetException;
public class ReflectionUtils {
public static Object tryInvoke(Object target, String methodName, Object... args) {
Class<?>[] argTypes = new Class<?>[args.length];
for (int i = 0; i < args.length; i++) {
argTypes[i] = args[i].getClass();
}
return tryInvoke(target, methodName, argTypes, args);
}
public static Object tryInvoke(Object target, String methodName, Class<?>[] argTypes,
Object... args) {
try {
return target.getClass().getMethod(methodName, argTypes).invoke(target, args);
} catch (NoSuchMethodException ignored) {
} catch (IllegalAccessException ignored) {
} catch (InvocationTargetException ignored) {
}
return null;
}
public static <E> E callWithDefault(Object target, String methodName, E defaultValue) {
try {
//noinspection unchecked
return (E) target.getClass().getMethod(methodName, (Class[]) null).invoke(target);
} catch (NoSuchMethodException ignored) {
} catch (IllegalAccessException ignored) {
} catch (InvocationTargetException ignored) {
}
return defaultValue;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.util;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.*;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.apps.iosched.BuildConfig;
import com.google.android.apps.iosched.Config;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Blocks;
import com.google.android.apps.iosched.provider.ScheduleContract.Rooms;
import com.google.android.apps.iosched.ui.phone.MapActivity;
import com.google.android.apps.iosched.ui.tablet.MapMultiPaneActivity;
import java.io.*;
import java.lang.ref.WeakReference;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Formatter;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Pattern;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* An assortment of UI helpers.
*/
public class UIUtils {
private static final String TAG = makeLogTag(UIUtils.class);
/**
* Time zone to use when formatting all session times. To always use the
* phone local time, use {@link TimeZone#getDefault()}.
*/
public static final TimeZone CONFERENCE_TIME_ZONE = TimeZone.getTimeZone("America/Los_Angeles");
public static final long CONFERENCE_START_MILLIS = ParserUtils.parseTime(
"2013-05-15T09:00:00.000-07:00");
public static final long CONFERENCE_END_MILLIS = ParserUtils.parseTime(
"2013-05-17T16:00:00.000-07:00");
public static final String CONFERENCE_HASHTAG = "#io13";
public static final String TARGET_FORM_FACTOR_ACTIVITY_METADATA =
"com.google.android.apps.iosched.meta.TARGET_FORM_FACTOR";
public static final String TARGET_FORM_FACTOR_HANDSET = "handset";
public static final String TARGET_FORM_FACTOR_TABLET = "tablet";
/**
* Flags used with {@link DateUtils#formatDateRange}.
*/
private static final int TIME_FLAGS = DateUtils.FORMAT_SHOW_TIME
| DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY;
/**
* Regex to search for HTML escape sequences.
*
* <p></p>Searches for any continuous string of characters starting with an ampersand and ending with a
* semicolon. (Example: &amp;)
*/
private static final Pattern REGEX_HTML_ESCAPE = Pattern.compile(".*&\\S;.*");
/**
* Used in {@link #tryTranslateHttpIntent(android.app.Activity)}.
*/
private static final Uri SESSION_DETAIL_WEB_URL_PREFIX
= Uri.parse("https://developers.google.com/events/io/sessions/");
private static StyleSpan sBoldSpan = new StyleSpan(Typeface.BOLD);
private static ForegroundColorSpan sColorSpan = new ForegroundColorSpan(0xff111111);
private static CharSequence sEmptyRoomText;
private static CharSequence sNowPlayingText;
private static CharSequence sLivestreamNowText;
private static CharSequence sLivestreamAvailableText;
public static final String GOOGLE_PLUS_PACKAGE_NAME = "com.google.android.apps.plus";
public static final int ANIMATION_FADE_IN_TIME = 250;
public static final String TRACK_ICONS_TAG = "tracks";
/**
* Format and return the given {@link Blocks} and {@link Rooms} values using
* {@link #CONFERENCE_TIME_ZONE}.
*/
public static String formatSessionSubtitle(String sessionTitle,
long blockStart, long blockEnd, String roomName, StringBuilder recycle,
Context context) {
// Determine if the session is in the past
long currentTimeMillis = UIUtils.getCurrentTime(context);
boolean conferenceEnded = currentTimeMillis > UIUtils.CONFERENCE_END_MILLIS;
boolean blockEnded = currentTimeMillis > blockEnd;
if (blockEnded && !conferenceEnded) {
return context.getString(R.string.session_finished);
}
if (sEmptyRoomText == null) {
sEmptyRoomText = context.getText(R.string.unknown_room);
}
if (roomName == null) {
return context.getString(R.string.session_subtitle,
formatBlockTimeString(blockStart, blockEnd, recycle, context),
sEmptyRoomText);
}
return context.getString(R.string.session_subtitle,
formatBlockTimeString(blockStart, blockEnd, recycle, context), roomName);
}
/**
* Format and return the given {@link Blocks} values using {@link #CONFERENCE_TIME_ZONE}
* (unless local time was explicitly requested by the user).
*/
public static String formatBlockTimeString(long blockStart, long blockEnd,
StringBuilder recycle, Context context) {
if (recycle == null) {
recycle = new StringBuilder();
} else {
recycle.setLength(0);
}
Formatter formatter = new Formatter(recycle);
return DateUtils.formatDateRange(context, formatter, blockStart, blockEnd, TIME_FLAGS,
PrefUtils.getDisplayTimeZone(context).getID()).toString();
}
public static boolean isSameDayDisplay(long time1, long time2, Context context) {
TimeZone displayTimeZone = PrefUtils.getDisplayTimeZone(context);
Calendar cal1 = Calendar.getInstance(displayTimeZone);
Calendar cal2 = Calendar.getInstance(displayTimeZone);
cal1.setTimeInMillis(time1);
cal2.setTimeInMillis(time2);
return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
&& cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
}
/**
* Populate the given {@link TextView} with the requested text, formatting
* through {@link Html#fromHtml(String)} when applicable. Also sets
* {@link TextView#setMovementMethod} so inline links are handled.
*/
public static void setTextMaybeHtml(TextView view, String text) {
if (TextUtils.isEmpty(text)) {
view.setText("");
return;
}
if ((text.contains("<") && text.contains(">")) || REGEX_HTML_ESCAPE.matcher(text).find()) {
view.setText(Html.fromHtml(text));
view.setMovementMethod(LinkMovementMethod.getInstance());
} else {
view.setText(text);
}
}
public static void updateTimeAndLivestreamBlockUI(final Context context,
long blockStart, long blockEnd, boolean hasLivestream, TextView titleView,
TextView subtitleView, CharSequence subtitle) {
long currentTimeMillis = getCurrentTime(context);
boolean conferenceEnded = currentTimeMillis > CONFERENCE_END_MILLIS;
boolean blockEnded = currentTimeMillis > blockEnd;
boolean blockNow = (blockStart <= currentTimeMillis && currentTimeMillis <= blockEnd);
if (titleView != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
titleView.setTypeface(Typeface.create((blockEnded && !conferenceEnded)
? "sans-serif-light" : "sans-serif", Typeface.NORMAL));
} else {
titleView.setTypeface(Typeface.SANS_SERIF,
(blockEnded && !conferenceEnded) ? Typeface.NORMAL : Typeface.BOLD);
}
}
if (subtitleView != null) {
boolean empty = true;
SpannableStringBuilder sb = new SpannableStringBuilder(); // TODO: recycle
if (subtitle != null) {
sb.append(subtitle);
empty = false;
}
if (blockNow) {
if (sNowPlayingText == null) {
sNowPlayingText = Html.fromHtml(context.getString(R.string.now_playing_badge));
}
if (!empty) {
sb.append(" ");
}
sb.append(sNowPlayingText);
if (hasLivestream) {
if (sLivestreamNowText == null) {
sLivestreamNowText = Html.fromHtml(" " +
context.getString(R.string.live_now_badge));
}
sb.append(sLivestreamNowText);
}
} else if (hasLivestream) {
if (sLivestreamAvailableText == null) {
sLivestreamAvailableText = Html.fromHtml(
context.getString(R.string.live_available_badge));
}
if (!empty) {
sb.append(" ");
}
sb.append(sLivestreamAvailableText);
}
subtitleView.setText(sb);
}
}
/**
* Given a snippet string with matching segments surrounded by curly
* braces, turn those areas into bold spans, removing the curly braces.
*/
public static Spannable buildStyledSnippet(String snippet) {
final SpannableStringBuilder builder = new SpannableStringBuilder(snippet);
// Walk through string, inserting bold snippet spans
int startIndex, endIndex = -1, delta = 0;
while ((startIndex = snippet.indexOf('{', endIndex)) != -1) {
endIndex = snippet.indexOf('}', startIndex);
// Remove braces from both sides
builder.delete(startIndex - delta, startIndex - delta + 1);
builder.delete(endIndex - delta - 1, endIndex - delta);
// Insert bold style
builder.setSpan(sBoldSpan, startIndex - delta, endIndex - delta - 1,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.setSpan(sColorSpan, startIndex - delta, endIndex - delta - 1,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
delta += 2;
}
return builder;
}
public static void preferPackageForIntent(Context context, Intent intent, String packageName) {
PackageManager pm = context.getPackageManager();
for (ResolveInfo resolveInfo : pm.queryIntentActivities(intent, 0)) {
if (resolveInfo.activityInfo.packageName.equals(packageName)) {
intent.setPackage(packageName);
break;
}
}
}
public static String getSessionHashtagsString(String hashtags) {
if (!TextUtils.isEmpty(hashtags)) {
if (!hashtags.startsWith("#")) {
hashtags = "#" + hashtags;
}
if (hashtags.contains(CONFERENCE_HASHTAG)) {
return hashtags;
}
return CONFERENCE_HASHTAG + " " + hashtags;
} else {
return CONFERENCE_HASHTAG;
}
}
private static final int BRIGHTNESS_THRESHOLD = 130;
/**
* Calculate whether a color is light or dark, based on a commonly known
* brightness formula.
*
* @see {@literal http://en.wikipedia.org/wiki/HSV_color_space%23Lightness}
*/
public static boolean isColorDark(int color) {
return ((30 * Color.red(color) +
59 * Color.green(color) +
11 * Color.blue(color)) / 100) <= BRIGHTNESS_THRESHOLD;
}
/**
* Create the track icon bitmap. Don't call this directly, instead use either
* {@link UIUtils.TrackIconAsyncTask} or {@link UIUtils.TrackIconViewAsyncTask} to
* asynchronously load the track icon.
*/
private static Bitmap createTrackIcon(Context context, String trackName, int trackColor) {
final Resources res = context.getResources();
int iconSize = res.getDimensionPixelSize(R.dimen.track_icon_source_size);
Bitmap icon = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(icon);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(trackColor);
canvas.drawCircle(iconSize / 2, iconSize / 2, iconSize / 2, paint);
int iconResId = res.getIdentifier(
"track_" + ParserUtils.sanitizeId(trackName),
"drawable", context.getPackageName());
if (iconResId != 0) {
Drawable sourceIconDrawable = res.getDrawable(iconResId);
sourceIconDrawable.setBounds(0, 0, iconSize, iconSize);
sourceIconDrawable.draw(canvas);
}
return icon;
}
/**
* Synchronously get the track icon bitmap. Don't call this from the main thread, instead use either
* {@link UIUtils.TrackIconAsyncTask} or {@link UIUtils.TrackIconViewAsyncTask} to
* asynchronously load the track icon.
*/
public static Bitmap getTrackIconSync(Context ctx, String trackName, int trackColor) {
if (TextUtils.isEmpty(trackName)) {
return null;
}
// Find a suitable disk cache directory for the track icons and create if it doesn't
// already exist.
File outputDir = ImageLoader.getDiskCacheDir(ctx, TRACK_ICONS_TAG);
if (!outputDir.exists()) {
outputDir.mkdirs();
}
// Generate a unique filename to store this track icon in using a hash function.
File imageFile = new File(outputDir + File.separator + hashKeyForDisk(trackName));
Bitmap bitmap = null;
// If file already exists and is readable, try and decode the bitmap from the disk.
if (imageFile.exists() && imageFile.canRead()) {
bitmap = BitmapFactory.decodeFile(imageFile.toString());
}
// If bitmap is still null here the track icon was not found in the disk cache.
if (bitmap == null) {
// Create the icon using the provided track name and color.
bitmap = UIUtils.createTrackIcon(ctx, trackName, trackColor);
// Now write it out to disk for future use.
BufferedOutputStream outputStream = null;
try {
outputStream = new BufferedOutputStream(new FileOutputStream(imageFile));
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
} catch (FileNotFoundException e) {
LOGE(TAG, "TrackIconAsyncTask - unable to open file - " + e);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException ignored) {
}
}
}
}
return bitmap;
}
/**
* A hashing method that changes a string (like a URL) into a hash suitable for using as a
* disk filename.
*/
private static String hashKeyForDisk(String key) {
String cacheKey;
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(key.getBytes());
cacheKey = bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
cacheKey = String.valueOf(key.hashCode());
}
return cacheKey;
}
private static String bytesToHexString(byte[] bytes) {
// http://stackoverflow.com/questions/332079
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
/**
* A subclass of {@link TrackIconAsyncTask} that loads the generated track icon bitmap into
* the provided {@link ImageView}. This class also handles concurrency in the case the
* ImageView is recycled (eg. in a ListView adapter) so that the incorrect image will not show
* in a recycled view.
*/
public static class TrackIconViewAsyncTask extends TrackIconAsyncTask {
private WeakReference<ImageView> mImageViewReference;
public TrackIconViewAsyncTask(ImageView imageView, String trackName, int trackColor,
BitmapCache bitmapCache) {
super(trackName, trackColor, bitmapCache);
// Store this AsyncTask in the tag of the ImageView so we can compare if the same task
// is still running on this ImageView once processing is complete. This helps with
// view recycling that takes place in a ListView type adapter.
imageView.setTag(this);
// If we have a BitmapCache, check if this track icon is available already.
Bitmap bitmap =
bitmapCache != null ? bitmapCache.getBitmapFromMemCache(trackName) : null;
// If found in BitmapCache set the Bitmap directly and cancel the task.
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
cancel(true);
} else {
// Otherwise clear the ImageView and store a WeakReference for later use. Better
// to use a WeakReference here in case the task runs long and the holding Activity
// or Fragment goes away.
imageView.setImageDrawable(null);
mImageViewReference = new WeakReference<ImageView>(imageView);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
@Override
protected void onPostExecute(Bitmap bitmap) {
ImageView imageView = mImageViewReference != null ? mImageViewReference.get() : null;
// If ImageView is still around, bitmap processed OK and this task is not canceled.
if (imageView != null && bitmap != null && !isCancelled()) {
// Ensure this task is still the same one assigned to this ImageView, if not the
// view was likely recycled and a new task with a different icon is now running
// on the view and we shouldn't proceed.
if (this.equals(imageView.getTag())) {
// On HC-MR1 run a quick fade-in animation.
if (hasHoneycombMR1()) {
imageView.setAlpha(0f);
imageView.setImageBitmap(bitmap);
imageView.animate()
.alpha(1f)
.setDuration(ANIMATION_FADE_IN_TIME)
.setListener(null);
} else {
// Before HC-MR1 set the Bitmap directly.
imageView.setImageBitmap(bitmap);
}
}
}
}
}
/**
* Asynchronously load the track icon bitmap. To use, subclass and override
* {@link #onPostExecute(android.graphics.Bitmap)} which passes in the generated track icon
* bitmap.
*/
public static abstract class TrackIconAsyncTask extends AsyncTask<Context, Void, Bitmap> {
private String mTrackName;
private int mTrackColor;
private BitmapCache mBitmapCache;
public TrackIconAsyncTask(String trackName, int trackColor) {
mTrackName = trackName;
mTrackColor = trackColor;
}
public TrackIconAsyncTask(String trackName, int trackColor, BitmapCache bitmapCache) {
mTrackName = trackName;
mTrackColor = trackColor;
mBitmapCache = bitmapCache;
}
@Override
protected Bitmap doInBackground(Context... contexts) {
Bitmap bitmap = getTrackIconSync(contexts[0], mTrackName, mTrackColor);
// Store bitmap in memory cache for future use.
if (bitmap != null && mBitmapCache != null) {
mBitmapCache.addBitmapToCache(mTrackName, bitmap);
}
return bitmap;
}
protected abstract void onPostExecute(Bitmap bitmap);
}
public static boolean hasHoneycomb() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
}
public static boolean hasHoneycombMR1() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
}
public static boolean hasICS() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}
public static boolean hasJellyBeanMR1() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;
}
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
public static boolean isHoneycombTablet(Context context) {
return hasHoneycomb() && isTablet(context);
}
// Shows whether a notification was fired for a particular session time block. In the
// event that notification has not been fired yet, return false and set the bit.
public static boolean isNotificationFiredForBlock(Context context, String blockId) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
final String key = String.format("notification_fired_%s", blockId);
boolean fired = sp.getBoolean(key, false);
sp.edit().putBoolean(key, true).commit();
return fired;
}
private static final long sAppLoadTime = System.currentTimeMillis();
public static long getCurrentTime(final Context context) {
if (BuildConfig.DEBUG) {
return context.getSharedPreferences("mock_data", Context.MODE_PRIVATE)
.getLong("mock_current_time", System.currentTimeMillis())
+ System.currentTimeMillis() - sAppLoadTime;
// return ParserUtils.parseTime("2012-06-27T09:44:45.000-07:00")
// + System.currentTimeMillis() - sAppLoadTime;
} else {
return System.currentTimeMillis();
}
}
public static boolean shouldShowLiveSessionsOnly(final Context context) {
return !PrefUtils.isAttendeeAtVenue(context)
&& getCurrentTime(context) < CONFERENCE_END_MILLIS;
}
/**
* Enables and disables {@linkplain android.app.Activity activities} based on their
* {@link #TARGET_FORM_FACTOR_ACTIVITY_METADATA}" meta-data and the current device.
* Values should be either "handset", "tablet", or not present (meaning universal).
* <p>
* <a href="http://stackoverflow.com/questions/13202805">Original code</a> by Dandre Allison.
* @param context the current context of the device
* @see #isHoneycombTablet(android.content.Context)
*/
public static void enableDisableActivitiesByFormFactor(Context context) {
final PackageManager pm = context.getPackageManager();
boolean isTablet = isHoneycombTablet(context);
try {
PackageInfo pi = pm.getPackageInfo(context.getPackageName(),
PackageManager.GET_ACTIVITIES | PackageManager.GET_META_DATA);
if (pi == null) {
LOGE(TAG, "No package info found for our own package.");
return;
}
final ActivityInfo[] activityInfos = pi.activities;
for (ActivityInfo info : activityInfos) {
String targetDevice = null;
if (info.metaData != null) {
targetDevice = info.metaData.getString(TARGET_FORM_FACTOR_ACTIVITY_METADATA);
}
boolean tabletActivity = TARGET_FORM_FACTOR_TABLET.equals(targetDevice);
boolean handsetActivity = TARGET_FORM_FACTOR_HANDSET.equals(targetDevice);
boolean enable = !(handsetActivity && isTablet)
&& !(tabletActivity && !isTablet);
String className = info.name;
pm.setComponentEnabledSetting(
new ComponentName(context, Class.forName(className)),
enable
? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
: PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
} catch (PackageManager.NameNotFoundException e) {
LOGE(TAG, "No package info found for our own package.", e);
} catch (ClassNotFoundException e) {
LOGE(TAG, "Activity not found within package.", e);
}
}
public static Class getMapActivityClass(Context context) {
if (UIUtils.isHoneycombTablet(context)) {
return MapMultiPaneActivity.class;
}
return MapActivity.class;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static void setActivatedCompat(View view, boolean activated) {
if (hasHoneycomb()) {
view.setActivated(activated);
}
}
/**
* If an activity's intent is for a Google I/O web URL that the app can handle
* natively, this method translates the intent to the equivalent native intent.
*/
public static void tryTranslateHttpIntent(Activity activity) {
Intent intent = activity.getIntent();
if (intent == null) {
return;
}
Uri uri = intent.getData();
if (uri == null || TextUtils.isEmpty(uri.getPath())) {
return;
}
String prefixPath = SESSION_DETAIL_WEB_URL_PREFIX.getPath();
String path = uri.getPath();
if (SESSION_DETAIL_WEB_URL_PREFIX.getScheme().equals(uri.getScheme()) &&
SESSION_DETAIL_WEB_URL_PREFIX.getHost().equals(uri.getHost()) &&
path.startsWith(prefixPath)) {
String sessionId = path.substring(prefixPath.length());
activity.setIntent(new Intent(
Intent.ACTION_VIEW,
ScheduleContract.Sessions.buildSessionUri(sessionId)));
}
}
/**
* The Conference API image URLs can be absolute or relative. In the case they are relative
* we should prepend the main Conference URL.
* @param imageUrl A Conference API image URL
* @return An absolute image URL
*/
public static String getConferenceImageUrl(String imageUrl) {
if (!TextUtils.isEmpty(imageUrl) && !imageUrl.startsWith("http")) {
return Config.CONFERENCE_IMAGE_PREFIX_URL + imageUrl;
}
return imageUrl;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.util;
import com.google.android.apps.iosched.BuildConfig;
import android.util.Log;
public class LogUtils {
private static final String LOG_PREFIX = "iosched_";
private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length();
private static final int MAX_LOG_TAG_LENGTH = 23;
public static String makeLogTag(String str) {
if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
}
return LOG_PREFIX + str;
}
/**
* Don't use this when obfuscating class names!
*/
public static String makeLogTag(Class cls) {
return makeLogTag(cls.getSimpleName());
}
public static void LOGD(final String tag, String message) {
//noinspection PointlessBooleanExpression,ConstantConditions
if (BuildConfig.DEBUG || Log.isLoggable(tag, Log.DEBUG)) {
Log.d(tag, message);
}
}
public static void LOGD(final String tag, String message, Throwable cause) {
//noinspection PointlessBooleanExpression,ConstantConditions
if (BuildConfig.DEBUG || Log.isLoggable(tag, Log.DEBUG)) {
Log.d(tag, message, cause);
}
}
public static void LOGV(final String tag, String message) {
//noinspection PointlessBooleanExpression,ConstantConditions
if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
Log.v(tag, message);
}
}
public static void LOGV(final String tag, String message, Throwable cause) {
//noinspection PointlessBooleanExpression,ConstantConditions
if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
Log.v(tag, message, cause);
}
}
public static void LOGI(final String tag, String message) {
Log.i(tag, message);
}
public static void LOGI(final String tag, String message, Throwable cause) {
Log.i(tag, message, cause);
}
public static void LOGW(final String tag, String message) {
Log.w(tag, message);
}
public static void LOGW(final String tag, String message, Throwable cause) {
Log.w(tag, message, cause);
}
public static void LOGE(final String tag, String message) {
Log.e(tag, message);
}
public static void LOGE(final String tag, String message, Throwable cause) {
Log.e(tag, message, cause);
}
private LogUtils() {
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.util;
import android.content.Context;
public class TimeUtils {
private static final int SECOND = 1000;
private static final int MINUTE = 60 * SECOND;
private static final int HOUR = 60 * MINUTE;
private static final int DAY = 24 * HOUR;
public static String getTimeAgo(long time, Context ctx) {
// TODO: use DateUtils methods instead
if (time < 1000000000000L) {
// if timestamp given in seconds, convert to millis
time *= 1000;
}
long now = UIUtils.getCurrentTime(ctx);
if (time > now || time <= 0) {
return null;
}
final long diff = now - time;
if (diff < MINUTE) {
return "just now";
} else if (diff < 2 * MINUTE) {
return "a minute ago";
} else if (diff < 50 * MINUTE) {
return diff / MINUTE + " minutes ago";
} else if (diff < 90 * MINUTE) {
return "an hour ago";
} else if (diff < 24 * HOUR) {
return diff / HOUR + " hours ago";
} else if (diff < 48 * HOUR) {
return "yesterday";
} else {
return diff / DAY + " days ago";
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.util;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.util.LruCache;
import com.android.volley.toolbox.ImageLoader;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* This class holds our bitmap caches (memory and disk).
*/
public class BitmapCache implements ImageLoader.ImageCache {
private static final String TAG = makeLogTag(BitmapCache.class);
// Default memory cache size as a percent of device memory class
private static final float DEFAULT_MEM_CACHE_PERCENT = 0.15f;
private LruCache<String, Bitmap> mMemoryCache;
/**
* Don't instantiate this class directly, use
* {@link #getInstance(android.support.v4.app.FragmentManager, float)}.
* @param memCacheSize Memory cache size in KB.
*/
private BitmapCache(int memCacheSize) {
init(memCacheSize);
}
/**
* Find and return an existing BitmapCache stored in a {@link RetainFragment}, if not found a
* new one is created using the supplied params and saved to a {@link RetainFragment}.
*
* @param fragmentManager The fragment manager to use when dealing with the retained fragment.
* @param fragmentTag The tag of the retained fragment (should be unique for each memory cache
* that needs to be retained).
* @param memCacheSize Memory cache size in KB.
*/
public static BitmapCache getInstance(FragmentManager fragmentManager, String fragmentTag,
int memCacheSize) {
BitmapCache bitmapCache = null;
RetainFragment mRetainFragment = null;
if (fragmentManager != null) {
// Search for, or create an instance of the non-UI RetainFragment
mRetainFragment = getRetainFragment(fragmentManager, fragmentTag);
// See if we already have a BitmapCache stored in RetainFragment
bitmapCache = (BitmapCache) mRetainFragment.getObject();
}
// No existing BitmapCache, create one and store it in RetainFragment
if (bitmapCache == null) {
bitmapCache = new BitmapCache(memCacheSize);
if (mRetainFragment != null) {
mRetainFragment.setObject(bitmapCache);
}
}
return bitmapCache;
}
public static BitmapCache getInstance(FragmentManager fragmentManager, int memCacheSize) {
return getInstance(fragmentManager, TAG, memCacheSize);
}
public static BitmapCache getInstance(FragmentManager fragmentManager, float memCachePercent) {
return getInstance(fragmentManager, calculateMemCacheSize(memCachePercent));
}
public static BitmapCache getInstance(FragmentManager fragmentManger) {
return getInstance(fragmentManger, DEFAULT_MEM_CACHE_PERCENT);
}
/**
* Initialize the cache.
*/
private void init(int memCacheSize) {
// Set up memory cache
LOGD(TAG, "Memory cache created (size = " + memCacheSize + "KB)");
mMemoryCache = new LruCache<String, Bitmap>(memCacheSize) {
/**
* Measure item size in kilobytes rather than units which is more practical
* for a bitmap cache
*/
@Override
protected int sizeOf(String key, Bitmap bitmap) {
final int bitmapSize = getBitmapSize(bitmap) / 1024;
return bitmapSize == 0 ? 1 : bitmapSize;
}
};
}
/**
* Adds a bitmap to both memory and disk cache.
* @param data Unique identifier for the bitmap to store
* @param bitmap The bitmap to store
*/
public void addBitmapToCache(String data, Bitmap bitmap) {
if (data == null || bitmap == null) {
return;
}
synchronized (mMemoryCache) {
// Add to memory cache
if (mMemoryCache.get(data) == null) {
LOGD(TAG, "Memory cache put - " + data);
mMemoryCache.put(data, bitmap);
}
}
}
/**
* Get from memory cache.
*
* @param data Unique identifier for which item to get
* @return The bitmap if found in cache, null otherwise
*/
public Bitmap getBitmapFromMemCache(String data) {
if (data != null) {
synchronized (mMemoryCache) {
final Bitmap memBitmap = mMemoryCache.get(data);
if (memBitmap != null) {
LOGD(TAG, "Memory cache hit - " + data);
return memBitmap;
}
}
LOGD(TAG, "Memory cache miss - " + data);
}
return null;
}
/**
* Clears the memory cache.
*/
public void clearCache() {
if (mMemoryCache != null) {
mMemoryCache.evictAll();
LOGD(TAG, "Memory cache cleared");
}
}
/**
* Sets the memory cache size based on a percentage of the max available VM memory.
* Eg. setting percent to 0.2 would set the memory cache to one fifth of the available
* memory. Throws {@link IllegalArgumentException} if percent is < 0.05 or > .8.
* memCacheSize is stored in kilobytes instead of bytes as this will eventually be passed
* to construct a LruCache which takes an int in its constructor.
*
* This value should be chosen carefully based on a number of factors
* Refer to the corresponding Android Training class for more discussion:
* http://developer.android.com/training/displaying-bitmaps/
*
* @param percent Percent of memory class to use to size memory cache
* @return Memory cache size in KB
*/
public static int calculateMemCacheSize(float percent) {
if (percent < 0.05f || percent > 0.8f) {
throw new IllegalArgumentException("setMemCacheSizePercent - percent must be "
+ "between 0.05 and 0.8 (inclusive)");
}
return Math.round(percent * Runtime.getRuntime().maxMemory() / 1024);
}
/**
* Get the size in bytes of a bitmap.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
public static int getBitmapSize(Bitmap bitmap) {
if (UIUtils.hasHoneycombMR1()) {
return bitmap.getByteCount();
}
// Pre HC-MR1
return bitmap.getRowBytes() * bitmap.getHeight();
}
/**
* Locate an existing instance of this Fragment or if not found, create and
* add it using FragmentManager.
*
* @param fm The FragmentManager manager to use.
* @param fragmentTag The tag of the retained fragment (should be unique for each memory
* cache that needs to be retained).
* @return The existing instance of the Fragment or the new instance if just
* created.
*/
private static RetainFragment getRetainFragment(FragmentManager fm, String fragmentTag) {
// Check to see if we have retained the worker fragment.
RetainFragment mRetainFragment = (RetainFragment) fm.findFragmentByTag(fragmentTag);
// If not retained (or first time running), we need to create and add it.
if (mRetainFragment == null) {
mRetainFragment = new RetainFragment();
fm.beginTransaction().add(mRetainFragment, fragmentTag).commitAllowingStateLoss();
}
return mRetainFragment;
}
@Override
public Bitmap getBitmap(String key) {
return getBitmapFromMemCache(key);
}
@Override
public void putBitmap(String key, Bitmap bitmap) {
addBitmapToCache(key, bitmap);
}
/**
* A simple non-UI Fragment that stores a single Object and is retained over configuration
* changes. It will be used to retain the BitmapCache object.
*/
public static class RetainFragment extends Fragment {
private Object mObject;
/**
* Empty constructor as per the Fragment documentation
*/
public RetainFragment() {}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Make sure this Fragment is retained over a configuration change
setRetainInstance(true);
}
/**
* Store a single object in this Fragment.
*
* @param object The object to store
*/
public void setObject(Object object) {
mObject = object;
}
/**
* Get the stored object.
*
* @return The stored object
*/
public Object getObject() {
return mObject;
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.util;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import com.google.android.apps.iosched.gcm.ServerUtilities;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.AccountActivity;
import com.google.android.gms.auth.*;
import com.google.android.gms.common.Scopes;
import java.io.IOException;
import static com.google.android.apps.iosched.util.LogUtils.*;
public class AccountUtils {
private static final String TAG = makeLogTag(AccountUtils.class);
private static final String PREF_CHOSEN_ACCOUNT = "chosen_account";
private static final String PREF_AUTH_TOKEN = "auth_token";
private static final String PREF_PLUS_PROFILE_ID = "plus_profile_id";
public static final String AUTH_SCOPES[] = {
Scopes.PLUS_LOGIN,
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/developerssite" };
static final String AUTH_TOKEN_TYPE;
static {
StringBuilder sb = new StringBuilder();
sb.append("oauth2:");
for (String scope : AUTH_SCOPES) {
sb.append(scope);
sb.append(" ");
}
AUTH_TOKEN_TYPE = sb.toString();
}
public static boolean isAuthenticated(final Context context) {
return !TextUtils.isEmpty(getChosenAccountName(context));
}
public static String getChosenAccountName(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getString(PREF_CHOSEN_ACCOUNT, null);
}
public static Account getChosenAccount(final Context context) {
String account = getChosenAccountName(context);
if (account != null) {
return new Account(account, GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
} else {
return null;
}
}
static void setChosenAccountName(final Context context, final String accountName) {
LOGD(TAG, "Chose account " + accountName);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putString(PREF_CHOSEN_ACCOUNT, accountName).commit();
}
public static String getAuthToken(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getString(PREF_AUTH_TOKEN, null);
}
private static void setAuthToken(final Context context, final String authToken) {
LOGI(TAG, "Auth token of length "
+ (TextUtils.isEmpty(authToken) ? 0 : authToken.length()));
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putString(PREF_AUTH_TOKEN, authToken).commit();
LOGD(TAG, "Auth Token: " + authToken);
}
static void invalidateAuthToken(final Context context) {
GoogleAuthUtil.invalidateToken(context, getAuthToken(context));
setAuthToken(context, null);
}
public static void setPlusProfileId(final Context context, final String profileId) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putString(PREF_PLUS_PROFILE_ID, profileId).commit();
}
public static String getPlusProfileId(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getString(PREF_PLUS_PROFILE_ID, null);
}
public static void refreshAuthToken(Context mContext) {
invalidateAuthToken(mContext);
tryAuthenticateWithErrorNotification(mContext, ScheduleContract.CONTENT_AUTHORITY,
getChosenAccountName(mContext));
}
public static interface AuthenticateCallback {
public boolean shouldCancelAuthentication();
public void onAuthTokenAvailable();
public void onRecoverableException(final int code);
public void onUnRecoverableException(final String errorMessage);
}
static void tryAuthenticateWithErrorNotification(Context context, String syncAuthority, String accountName) {
try {
LOGI(TAG, "Requesting new auth token (with notification)");
final String token = GoogleAuthUtil.getTokenWithNotification(context, accountName, AUTH_TOKEN_TYPE,
null, syncAuthority, null);
setAuthToken(context, token);
setChosenAccountName(context, accountName);
} catch (UserRecoverableNotifiedException e) {
// Notification has already been pushed.
LOGW(TAG, "User recoverable exception. Check notification.", e);
} catch (GoogleAuthException e) {
// This is likely unrecoverable.
LOGE(TAG, "Unrecoverable authentication exception: " + e.getMessage(), e);
} catch (IOException e) {
LOGE(TAG, "transient error encountered: " + e.getMessage());
}
}
public static void tryAuthenticate(final Activity activity, final AuthenticateCallback callback,
final String accountName, final int requestCode) {
(new GetTokenTask(activity, callback, accountName, requestCode)).execute();
}
private static class GetTokenTask extends AsyncTask <Void, Void, String> {
private String mAccountName;
private Activity mActivity;
private AuthenticateCallback mCallback;
private int mRequestCode;
public GetTokenTask(Activity activity, AuthenticateCallback callback, String name, int requestCode) {
mAccountName = name;
mActivity = activity;
mCallback = callback;
mRequestCode = requestCode;
}
@Override
protected String doInBackground(Void... params) {
try {
if (mCallback.shouldCancelAuthentication()) return null;
final String token = GoogleAuthUtil.getToken(mActivity, mAccountName, AUTH_TOKEN_TYPE);
// Persists auth token.
setAuthToken(mActivity, token);
setChosenAccountName(mActivity, mAccountName);
return token;
} catch (GooglePlayServicesAvailabilityException e) {
mCallback.onRecoverableException(e.getConnectionStatusCode());
} catch (UserRecoverableAuthException e) {
mActivity.startActivityForResult(e.getIntent(), mRequestCode);
} catch (IOException e) {
LOGE(TAG, "transient error encountered: " + e.getMessage());
mCallback.onUnRecoverableException(e.getMessage());
} catch (GoogleAuthException e) {
LOGE(TAG, "transient error encountered: " + e.getMessage());
mCallback.onUnRecoverableException(e.getMessage());
} catch (RuntimeException e) {
LOGE(TAG, "Error encountered: " + e.getMessage());
mCallback.onUnRecoverableException(e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(String token) {
super.onPostExecute(token);
mCallback.onAuthTokenAvailable();
}
}
public static void signOut(final Context context) {
// Sign out of GCM message router
ServerUtilities.onSignOut(context);
// Destroy auth tokens
invalidateAuthToken(context);
// Remove remaining application state
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().clear().commit();
context.getContentResolver().delete(ScheduleContract.BASE_CONTENT_URI, null, null);
}
public static void startAuthenticationFlow(final Context context, final Intent finishIntent) {
Intent loginFlowIntent = new Intent(context, AccountActivity.class);
loginFlowIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
loginFlowIntent.putExtra(AccountActivity.EXTRA_FINISH_INTENT, finishIntent);
context.startActivity(loginFlowIntent);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.util;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.net.http.AndroidHttpClient;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.widget.ImageView;
import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HttpClientStack;
import com.android.volley.toolbox.HurlStack;
import java.io.File;
import java.util.ArrayList;
/**
* A class that wraps up remote image loading requests using the Volley library combined with a
* memory cache. An single instance of this class should be created once when your Activity or
* Fragment is created, then use {@link #get(String, android.widget.ImageView)} or one of
* the variations to queue the image to be fetched and loaded from the network. Loading images
* in a {@link android.widget.ListView} or {@link android.widget.GridView} is also supported but
* you must store the {@link com.android.volley.Request} in your ViewHolder type class and pass it
* into loadImage to ensure the request is canceled as views are recycled.
*/
public class ImageLoader extends com.android.volley.toolbox.ImageLoader {
private static final ColorDrawable transparentDrawable = new ColorDrawable(
android.R.color.transparent);
private static final int HALF_FADE_IN_TIME = UIUtils.ANIMATION_FADE_IN_TIME / 2;
private static final String CACHE_DIR = "images";
private Resources mResources;
private ArrayList<Drawable> mPlaceHolderDrawables;
private boolean mFadeInImage = true;
private int mMaxImageHeight = 0;
private int mMaxImageWidth = 0;
/**
* Creates an ImageLoader with Bitmap memory cache. No default placeholder image will be shown
* while the image is being fetched and loaded.
*/
public ImageLoader(FragmentActivity activity) {
super(newRequestQueue(activity),
BitmapCache.getInstance(activity.getSupportFragmentManager()));
mResources = activity.getResources();
}
/**
* Creates an ImageLoader with Bitmap memory cache and a default placeholder image while the
* image is being fetched and loaded.
*/
public ImageLoader(FragmentActivity activity, int defaultPlaceHolderResId) {
super(newRequestQueue(activity),
BitmapCache.getInstance(activity.getSupportFragmentManager()));
mResources = activity.getResources();
mPlaceHolderDrawables = new ArrayList<Drawable>(1);
mPlaceHolderDrawables.add(defaultPlaceHolderResId == -1 ?
null : mResources.getDrawable(defaultPlaceHolderResId));
}
/**
* Creates an ImageLoader with Bitmap memory cache and a list of default placeholder drawables.
*/
public ImageLoader(FragmentActivity activity, ArrayList<Drawable> placeHolderDrawables) {
super(newRequestQueue(activity),
BitmapCache.getInstance(activity.getSupportFragmentManager()));
mResources = activity.getResources();
mPlaceHolderDrawables = placeHolderDrawables;
}
/**
* Starts processing requests on the {@link RequestQueue}.
*/
public void startProcessingQueue() {
getRequestQueue().start();
}
/**
* Stops processing requests on the {@link RequestQueue}.
*/
public void stopProcessingQueue() {
getRequestQueue().stop();
}
public ImageLoader setFadeInImage(boolean fadeInImage) {
mFadeInImage = fadeInImage;
return this;
}
public ImageLoader setMaxImageSize(int maxImageWidth, int maxImageHeight) {
mMaxImageWidth = maxImageWidth;
mMaxImageHeight = maxImageHeight;
return this;
}
public ImageLoader setMaxImageSize(int maxImageSize) {
return setMaxImageSize(maxImageSize, maxImageSize);
}
public ImageContainer get(String requestUrl, ImageView imageView) {
return get(requestUrl, imageView, 0);
}
public ImageContainer get(String requestUrl, ImageView imageView, int placeHolderIndex) {
return get(requestUrl, imageView, mPlaceHolderDrawables.get(placeHolderIndex),
mMaxImageWidth, mMaxImageHeight);
}
public ImageContainer get(String requestUrl, ImageView imageView, Drawable placeHolder) {
return get(requestUrl, imageView, placeHolder, mMaxImageWidth, mMaxImageHeight);
}
public ImageContainer get(String requestUrl, ImageView imageView, Drawable placeHolder,
int maxWidth, int maxHeight) {
// Find any old image load request pending on this ImageView (in case this view was
// recycled)
ImageContainer imageContainer = imageView.getTag() != null &&
imageView.getTag() instanceof ImageContainer ?
(ImageContainer) imageView.getTag() : null;
// Find image url from prior request
String recycledImageUrl = imageContainer != null ? imageContainer.getRequestUrl() : null;
// If the new requestUrl is null or the new requestUrl is different to the previous
// recycled requestUrl
if (requestUrl == null || !requestUrl.equals(recycledImageUrl)) {
if (imageContainer != null) {
// Cancel previous image request
imageContainer.cancelRequest();
imageView.setTag(null);
}
if (requestUrl != null) {
// Queue new request to fetch image
imageContainer = get(requestUrl,
getImageListener(mResources, imageView, placeHolder, mFadeInImage),
maxWidth, maxHeight);
// Store request in ImageView tag
imageView.setTag(imageContainer);
} else {
imageView.setImageDrawable(placeHolder);
imageView.setTag(null);
}
}
return imageContainer;
}
private static ImageListener getImageListener(final Resources resources,
final ImageView imageView, final Drawable placeHolder, final boolean fadeInImage) {
return new ImageListener() {
@Override
public void onResponse(ImageContainer response, boolean isImmediate) {
imageView.setTag(null);
if (response.getBitmap() != null) {
setImageBitmap(imageView, response.getBitmap(), resources,
fadeInImage && !isImmediate);
} else {
imageView.setImageDrawable(placeHolder);
}
}
@Override
public void onErrorResponse(VolleyError volleyError) {
}
};
}
private static RequestQueue newRequestQueue(Context context) {
// On HC+ use HurlStack which is based on HttpURLConnection. Otherwise fall back on
// AndroidHttpClient (based on Apache DefaultHttpClient) which should no longer be used
// on newer platform versions where HttpURLConnection is simply better.
Network network = new BasicNetwork(
UIUtils.hasHoneycomb() ?
new HurlStack() :
new HttpClientStack(AndroidHttpClient.newInstance(
NetUtils.getUserAgent(context))));
Cache cache = new DiskBasedCache(getDiskCacheDir(context, CACHE_DIR));
RequestQueue queue = new RequestQueue(cache, network);
queue.start();
return queue;
}
/**
* Sets a {@link android.graphics.Bitmap} to an {@link android.widget.ImageView} using a
* fade-in animation. If there is a {@link android.graphics.drawable.Drawable} already set on
* the ImageView then use that as the image to fade from. Otherwise fade in from a transparent
* Drawable.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
private static void setImageBitmap(final ImageView imageView, final Bitmap bitmap,
Resources resources, boolean fadeIn) {
// If we're fading in and on HC MR1+
if (fadeIn && UIUtils.hasHoneycombMR1()) {
// Use ViewPropertyAnimator to run a simple fade in + fade out animation to update the
// ImageView
imageView.animate()
.scaleY(0.95f)
.scaleX(0.95f)
.alpha(0f)
.setDuration(imageView.getDrawable() == null ? 0 : HALF_FADE_IN_TIME)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
imageView.setImageBitmap(bitmap);
imageView.animate()
.alpha(1f)
.scaleY(1f)
.scaleX(1f)
.setDuration(HALF_FADE_IN_TIME)
.setListener(null);
}
});
} else if (fadeIn) {
// Otherwise use a TransitionDrawable to fade in
Drawable initialDrawable;
if (imageView.getDrawable() != null) {
initialDrawable = imageView.getDrawable();
} else {
initialDrawable = transparentDrawable;
}
BitmapDrawable bitmapDrawable = new BitmapDrawable(resources, bitmap);
// Use TransitionDrawable to fade in
final TransitionDrawable td =
new TransitionDrawable(new Drawable[] {
initialDrawable,
bitmapDrawable
});
imageView.setImageDrawable(td);
td.startTransition(UIUtils.ANIMATION_FADE_IN_TIME);
} else {
// No fade in, just set bitmap directly
imageView.setImageBitmap(bitmap);
}
}
/**
* Get a usable cache directory (external if available, internal otherwise).
*
* @param context The context to use
* @param uniqueName A unique directory name to append to the cache dir
* @return The cache dir
*/
public static File getDiskCacheDir(Context context, String uniqueName) {
// Check if media is mounted or storage is built-in, if so, try and use external cache dir
// otherwise use internal cache dir
// TODO: getCacheDir() should be moved to a background thread as it attempts to create the
// directory if it does not exist (no disk access should happen on the main/UI thread).
final String cachePath =
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
!Environment.isExternalStorageRemovable()
? getExternalCacheDir(context).getPath()
: context.getCacheDir().getPath();
return new File(cachePath + File.separator + uniqueName);
}
/**
* Get the external app cache directory.
*
* @param context The context to use
* @return The external cache dir
*/
private static File getExternalCacheDir(Context context) {
// TODO: This needs to be moved to a background thread to ensure no disk access on the
// main/UI thread as unfortunately getExternalCacheDir() calls mkdirs() for us (even
// though the Volley library will later try and call mkdirs() as well from a background
// thread).
return context.getExternalCacheDir();
}
/**
* Interface an activity can implement to provide an ImageLoader to its children fragments.
*/
public interface ImageLoaderProvider {
public ImageLoader getImageLoaderInstance();
}
}
| Java |
package com.google.android.apps.iosched.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.preference.PreferenceManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class MapUtils {
private static final String TILE_PATH = "maptiles";
private static final String PREF_MYLOCATION_ENABLED = "map_mylocation_enabled";
private static final String TAG = LogUtils.makeLogTag(MapUtils.class);
private static float mDPI = -1.0f;
private static int mLabelPadding;
private static final float LABEL_OUTLINEWIDTH = 3.5f;
private static final int LABEL_PADDING = 2;
private static final int LABEL_TEXTSIZE = 14;
private static Paint mLabelOutlinePaint = null;
private static Paint mLabelTextPaint;
private static void setupLabels() {
float strokeWidth = LABEL_OUTLINEWIDTH * mDPI;
mLabelTextPaint = new Paint();
mLabelTextPaint.setTextSize(LABEL_TEXTSIZE * mDPI);
mLabelTextPaint.setColor(Color.WHITE);
mLabelTextPaint.setAntiAlias(true);
mLabelOutlinePaint = new Paint(mLabelTextPaint);
mLabelOutlinePaint.setStyle(Paint.Style.STROKE);
mLabelOutlinePaint.setColor(0x99000000);
mLabelOutlinePaint.setStrokeWidth(strokeWidth);
mLabelOutlinePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
mLabelOutlinePaint.setStrokeJoin(Paint.Join.ROUND);
mLabelOutlinePaint.setStrokeCap(Paint.Cap.ROUND);
mLabelPadding = (int) Math.ceil(LABEL_PADDING * mDPI + strokeWidth);
}
public static Bitmap createTextLabel(String label, float dpi) {
if (dpi != mDPI) {
mDPI = dpi;
setupLabels();
}
// calculate size
Rect bounds = new Rect();
mLabelTextPaint.getTextBounds(label, 0, label.length(), bounds);
// calculate text size
int bitmapH = Math.abs(bounds.top) + 2 * mLabelPadding;
int bitmapW = bounds.right + 2 * mLabelPadding;
// Create bitmap and draw text
Bitmap b = Bitmap.createBitmap(bitmapW, bitmapH, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
c.drawText(label, mLabelPadding, bitmapH - mLabelPadding, mLabelOutlinePaint);
c.drawText(label, mLabelPadding, bitmapH - mLabelPadding, mLabelTextPaint);
return b;
}
private static String[] mapTileAssets;
/**
* Returns true if the given tile file exists as a local asset.
*/
public static boolean hasTileAsset(Context context, String filename) {
//cache the list of available files
if (mapTileAssets == null) {
try {
mapTileAssets = context.getAssets().list("maptiles");
} catch (IOException e) {
// no assets
mapTileAssets = new String[0];
}
}
// search for given filename
for (String s : mapTileAssets) {
if (s.equals(filename)) {
return true;
}
}
return false;
}
/**
* Copy the file from the assets to the map tiles directory if it was
* shipped with the APK.
*/
public static boolean copyTileAsset(Context context, String filename) {
if (!hasTileAsset(context, filename)) {
// file does not exist as asset
return false;
}
// copy file from asset to internal storage
try {
InputStream is = context.getAssets().open(TILE_PATH + File.separator + filename);
File f = getTileFile(context, filename);
FileOutputStream os = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int dataSize;
while ((dataSize = is.read(buffer)) > 0) {
os.write(buffer, 0, dataSize);
}
os.close();
} catch (IOException e) {
return false;
}
return true;
}
/**
* Return a {@link File} pointing to the storage location for map tiles.
*/
public static File getTileFile(Context context, String filename) {
File folder = new File(context.getFilesDir(), TILE_PATH);
if (!folder.exists()) {
folder.mkdirs();
}
return new File(folder, filename);
}
public static void removeUnusedTiles(Context mContext, final ArrayList<String> usedTiles) {
// remove all files are stored in the tile path but are not used
File folder = new File(mContext.getFilesDir(), TILE_PATH);
File[] unused = folder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
return !usedTiles.contains(filename);
}
});
for (File f : unused) {
f.delete();
}
}
public static boolean hasTile(Context mContext, String filename) {
return getTileFile(mContext, filename).exists();
}
public static boolean getMyLocationEnabled(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean(PREF_MYLOCATION_ENABLED,false);
}
public static void setMyLocationEnabled(final Context context, final boolean enableMyLocation) {
LogUtils.LOGD(TAG,"Set my location enabled: "+enableMyLocation);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putBoolean(PREF_MYLOCATION_ENABLED,enableMyLocation).commit();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.util;
import java.util.HashMap;
import java.util.LinkedHashMap;
/**
* Provides static methods for creating mutable {@code Maps} instances easily.
*/
public class Maps {
/**
* Creates a {@code HashMap} instance.
*
* @return a newly-created, initially-empty {@code HashMap}
*/
public static <K, V> HashMap<K, V> newHashMap() {
return new HashMap<K, V>();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.util;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.apps.iosched.Config;
import com.google.android.apps.iosched.R;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
public class WiFiUtils {
// Preference key and values associated with WiFi AP configuration.
public static final String PREF_WIFI_AP_CONFIG = "pref_wifi_ap_config";
public static final String WIFI_CONFIG_DONE = "done";
public static final String WIFI_CONFIG_REQUESTED = "requested";
private static final String TAG = makeLogTag(WiFiUtils.class);
public static void installConferenceWiFi(final Context context) {
// Create config
WifiConfiguration config = new WifiConfiguration();
// Must be in double quotes to tell system this is an ASCII SSID and passphrase.
config.SSID = String.format("\"%s\"", Config.WIFI_SSID);
config.preSharedKey = String.format("\"%s\"", Config.WIFI_PASSPHRASE);
// Store config
final WifiManager wifiManager =
(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
int netId = wifiManager.addNetwork(config);
if (netId != -1) {
wifiManager.enableNetwork(netId, false);
boolean result = wifiManager.saveConfiguration();
if (!result) {
Log.e(TAG, "Unknown error while calling WiFiManager.saveConfiguration()");
Toast.makeText(context,
context.getResources().getString(R.string.wifi_install_error_message),
Toast.LENGTH_SHORT).show();
}
} else {
Log.e(TAG, "Unknown error while calling WiFiManager.addNetwork()");
Toast.makeText(context,
context.getResources().getString(R.string.wifi_install_error_message),
Toast.LENGTH_SHORT).show();
}
}
/**
* Helper method to decide whether to bypass conference WiFi setup. Return true if
* WiFi AP is already configured (WiFi adapter enabled) or WiFi configuration is complete
* as per shared preference.
*/
public static boolean shouldBypassWiFiSetup(final Context context) {
final WifiManager wifiManager =
(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
// Is WiFi on?
if (wifiManager.isWifiEnabled()) {
// Check for existing APs.
final List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
final String conferenceSSID = String.format("\"%s\"", Config.WIFI_SSID);
for(WifiConfiguration config : configs) {
if (conferenceSSID.equalsIgnoreCase(config.SSID)) return true;
}
}
return WIFI_CONFIG_DONE.equals(getWiFiConfigStatus(context));
}
public static boolean isWiFiEnabled(final Context context) {
final WifiManager wifiManager =
(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
return wifiManager.isWifiEnabled();
}
public static boolean isWiFiApConfigured(final Context context) {
final WifiManager wifiManager =
(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
if (configs == null) return false;
// Check for existing APs.
final String conferenceSSID = String.format("\"%s\"", Config.WIFI_SSID);
for(WifiConfiguration config : configs) {
if (conferenceSSID.equalsIgnoreCase(config.SSID)) return true;
}
return false;
}
// Stored preferences associated with WiFi AP configuration.
public static String getWiFiConfigStatus(final Context context) {
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getString(PREF_WIFI_AP_CONFIG, null);
}
public static void setWiFiConfigStatus(final Context context, final String status) {
if (!WIFI_CONFIG_DONE.equals(status) && !WIFI_CONFIG_REQUESTED.equals(status))
throw new IllegalArgumentException("Invalid WiFi Config status: " + status);
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putString(PREF_WIFI_AP_CONFIG, status).commit();
}
public static boolean installWiFiIfRequested(final Context context) {
if (WIFI_CONFIG_REQUESTED.equals(getWiFiConfigStatus(context)) && isWiFiEnabled(context)) {
installConferenceWiFi(context);
if (isWiFiApConfigured(context)) {
setWiFiConfigStatus(context, WiFiUtils.WIFI_CONFIG_DONE);
return true;
}
}
return false;
}
public static void showWiFiDialog(FragmentActivity activity) {
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("dialog_wifi");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
new WiFiDialog(isWiFiEnabled(activity)).show(ft, "dialog_wifi");
}
public static class WiFiDialog extends DialogFragment {
private boolean mWiFiEnabled;
public WiFiDialog() {}
public WiFiDialog(boolean wifiEnabled) {
super();
mWiFiEnabled = wifiEnabled;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final int padding =
getResources().getDimensionPixelSize(R.dimen.content_padding_normal);
final TextView wifiTextView = new TextView(getActivity());
int dialogCallToActionText;
int dialogPositiveButtonText;
if (mWiFiEnabled) {
dialogCallToActionText = R.string.calltoaction_wifi_configure;
dialogPositiveButtonText = R.string.wifi_dialog_button_configure;
} else {
dialogCallToActionText = R.string.calltoaction_wifi_settings;
dialogPositiveButtonText = R.string.wifi_dialog_button_settings;
}
wifiTextView.setText(Html.fromHtml(getString(R.string.description_setup_wifi_body) +
getString(dialogCallToActionText)));
wifiTextView.setMovementMethod(LinkMovementMethod.getInstance());
wifiTextView.setPadding(padding, padding, padding, padding);
final Context context = getActivity();
return new AlertDialog.Builder(context)
.setTitle(R.string.description_configure_wifi)
.setView(wifiTextView)
.setPositiveButton(dialogPositiveButtonText,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Attempt to configure the Wi-Fi access point.
if (mWiFiEnabled) {
installConferenceWiFi(context);
if (WiFiUtils.isWiFiApConfigured(context)) {
WiFiUtils.setWiFiConfigStatus(
context,
WiFiUtils.WIFI_CONFIG_DONE);
}
// Launch Wi-Fi settings screen for user to enable Wi-Fi.
} else {
WiFiUtils.setWiFiConfigStatus(context,
WiFiUtils.WIFI_CONFIG_REQUESTED);
final Intent wifiIntent =
new Intent(Settings.ACTION_WIFI_SETTINGS);
wifiIntent.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(wifiIntent);
}
dialog.dismiss();
}
}
)
.create();
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.util;
import com.google.android.apps.iosched.provider.ScheduleContract;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Parcelable;
import android.preference.PreferenceManager;
/**
* Android Beam helper methods.
*/
public class BeamUtils {
/**
* Sets this activity's Android Beam message to one representing the given session.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void setBeamSessionUri(Activity activity, Uri sessionUri) {
if (UIUtils.hasICS()) {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
if (nfcAdapter == null) {
// No NFC :-(
return;
}
nfcAdapter.setNdefPushMessage(new NdefMessage(
new NdefRecord[]{
new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
ScheduleContract.Sessions.CONTENT_ITEM_TYPE.getBytes(),
new byte[0],
sessionUri.toString().getBytes())
}), activity);
}
}
/**
* Checks to see if the activity's intent ({@link android.app.Activity#getIntent()}) is
* an NFC intent that the app recognizes. If it is, then parse the NFC message and set the
* activity's intent (using {@link Activity#setIntent(android.content.Intent)}) to something
* the app can recognize (i.e. a normal {@link Intent#ACTION_VIEW} intent).
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void tryUpdateIntentFromBeam(Activity activity) {
if (UIUtils.hasICS()) {
Intent originalIntent = activity.getIntent();
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(originalIntent.getAction())) {
Parcelable[] rawMsgs = originalIntent.getParcelableArrayExtra(
NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage msg = (NdefMessage) rawMsgs[0];
// Record 0 contains the MIME type, record 1 is the AAR, if present.
// In iosched, AARs are not present.
NdefRecord mimeRecord = msg.getRecords()[0];
if (ScheduleContract.Sessions.CONTENT_ITEM_TYPE.equals(
new String(mimeRecord.getType()))) {
// Re-set the activity's intent to one that represents session details.
Intent sessionDetailIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(new String(mimeRecord.getPayload())));
activity.setIntent(sessionDetailIntent);
}
}
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.util;
import android.content.ContentProvider;
import android.net.Uri;
import android.text.format.Time;
import java.util.regex.Pattern;
/**
* Various utility methods used by {@link com.google.android.apps.iosched.io.JSONHandler}.
*/
public class ParserUtils {
/** Used to sanitize a string to be {@link Uri} safe. */
private static final Pattern sSanitizePattern = Pattern.compile("[^a-z0-9-_]");
private static final Time sTime = new Time();
/**
* Sanitize the given string to be {@link Uri} safe for building
* {@link ContentProvider} paths.
*/
public static String sanitizeId(String input) {
if (input == null) {
return null;
}
return sSanitizePattern.matcher(input.replace("+", "plus").toLowerCase()).replaceAll("");
}
/**
* Parse the given string as a RFC 3339 timestamp, returning the value as
* milliseconds since the epoch.
*/
public static long parseTime(String time) {
sTime.parse3339(time);
return sTime.toMillis(false);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.util;
import android.graphics.Rect;
import android.graphics.RectF;
import android.view.MotionEvent;
import android.view.TouchDelegate;
import android.view.View;
/**
* {@link TouchDelegate} that gates {@link MotionEvent} instances by comparing
* then against fractional dimensions of the source view.
* <p>
* This is particularly useful when you want to define a rectangle in terms of
* the source dimensions, but when those dimensions might change due to pending
* or future layout passes.
* <p>
* One example is catching touches that occur in the top-right quadrant of
* {@code sourceParent}, and relaying them to {@code targetChild}. This could be
* done with: <code>
* FractionalTouchDelegate.setupDelegate(sourceParent, targetChild, new RectF(0.5f, 0f, 1f, 0.5f));
* </code>
*/
public class FractionalTouchDelegate extends TouchDelegate {
private View mSource;
private View mTarget;
private RectF mSourceFraction;
private Rect mScrap = new Rect();
/** Cached full dimensions of {@link #mSource}. */
private Rect mSourceFull = new Rect();
/** Cached projection of {@link #mSourceFraction} onto {@link #mSource}. */
private Rect mSourcePartial = new Rect();
private boolean mDelegateTargeted;
public FractionalTouchDelegate(View source, View target, RectF sourceFraction) {
super(new Rect(0, 0, 0, 0), target);
mSource = source;
mTarget = target;
mSourceFraction = sourceFraction;
}
/**
* Helper to create and setup a {@link FractionalTouchDelegate} between the
* given {@link View}.
*
* @param source Larger source {@link View}, usually a parent, that will be
* assigned {@link View#setTouchDelegate(TouchDelegate)}.
* @param target Smaller target {@link View} which will receive
* {@link MotionEvent} that land in requested fractional area.
* @param sourceFraction Fractional area projected onto source {@link View}
* which determines when {@link MotionEvent} will be passed to
* target {@link View}.
*/
public static void setupDelegate(View source, View target, RectF sourceFraction) {
source.setTouchDelegate(new FractionalTouchDelegate(source, target, sourceFraction));
}
/**
* Consider updating {@link #mSourcePartial} when {@link #mSource}
* dimensions have changed.
*/
private void updateSourcePartial() {
mSource.getHitRect(mScrap);
if (!mScrap.equals(mSourceFull)) {
// Copy over and calculate fractional rectangle
mSourceFull.set(mScrap);
final int width = mSourceFull.width();
final int height = mSourceFull.height();
mSourcePartial.left = (int) (mSourceFraction.left * width);
mSourcePartial.top = (int) (mSourceFraction.top * height);
mSourcePartial.right = (int) (mSourceFraction.right * width);
mSourcePartial.bottom = (int) (mSourceFraction.bottom * height);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
updateSourcePartial();
// The logic below is mostly copied from the parent class, since we
// can't update private mBounds variable.
// http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;
// f=core/java/android/view/TouchDelegate.java;hb=eclair#l98
final Rect sourcePartial = mSourcePartial;
final View target = mTarget;
int x = (int)event.getX();
int y = (int)event.getY();
boolean sendToDelegate = false;
boolean hit = true;
boolean handled = false;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (sourcePartial.contains(x, y)) {
mDelegateTargeted = true;
sendToDelegate = true;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_MOVE:
sendToDelegate = mDelegateTargeted;
if (sendToDelegate) {
if (!sourcePartial.contains(x, y)) {
hit = false;
}
}
break;
case MotionEvent.ACTION_CANCEL:
sendToDelegate = mDelegateTargeted;
mDelegateTargeted = false;
break;
}
if (sendToDelegate) {
if (hit) {
event.setLocation(target.getWidth() / 2, target.getHeight() / 2);
} else {
event.setLocation(-1, -1);
}
handled = target.dispatchTouchEvent(event);
}
return handled;
}
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* 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 com.google.android.apps.iosched.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceManager;
import com.google.android.apps.iosched.Config;
import java.util.TimeZone;
/**
* Utilities and constants related to app preferences.
*/
public class PrefUtils {
/**
* Boolean preference that when checked, indicates that the user would like to see times
* in their local timezone throughout the app.
*/
public static final String PREF_LOCAL_TIMES = "pref_local_times";
/**
* Boolean preference that when checked, indicates that the user will be attending the
* conference.
*/
public static final String PREF_ATTENDEE_AT_VENUE = "pref_attendee_at_venue";
/**
* Boolean preference that when checked, indicates that the user has completed account
* authentication and the initial set up flow.
*/
public static final String PREF_SETUP_DONE = "pref_setup_done";
/**
* Integer preference that indicates what conference year the application is configured
* for. Typically, if this isn't an exact match, preferences should be wiped to re-run
* setup.
*/
public static final String PREF_CONFERENCE_YEAR = "pref_conference_year";
/**
* Boolean indicating whether a user's DevSite profile is available. Defaults to true.
*/
public static final String PREF_DEVSITE_PROFILE_AVAILABLE = "pref_devsite_profile_available";
private static int sIsUsingLocalTime = -1;
private static int sAttendeeAtVenue = -1;
public static TimeZone getDisplayTimeZone(Context context) {
return isUsingLocalTime(context)
? TimeZone.getDefault()
: UIUtils.CONFERENCE_TIME_ZONE;
}
public static boolean isUsingLocalTime(Context context) {
return isUsingLocalTime(context, false);
}
public static boolean isUsingLocalTime(Context context, boolean forceRequery) {
if (sIsUsingLocalTime == -1 || forceRequery) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sIsUsingLocalTime = sp.getBoolean(PREF_LOCAL_TIMES, false) ? 1 : 0;
}
return sIsUsingLocalTime == 1;
}
public static void setUsingLocalTime(final Context context, final boolean usingLocalTime) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putBoolean(PREF_LOCAL_TIMES, usingLocalTime).commit();
}
public static boolean isAttendeeAtVenue(final Context context) {
return isAttendeeAtVenue(context, false);
}
public static boolean isAttendeeAtVenue(final Context context, boolean forceRequery) {
if (sAttendeeAtVenue == -1 || forceRequery) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sAttendeeAtVenue = sp.getBoolean(PREF_ATTENDEE_AT_VENUE, false) ? 1 : 0;
}
return sAttendeeAtVenue == 1;
}
public static void markSetupDone(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putBoolean(PREF_SETUP_DONE, true).commit();
}
public static boolean isSetupDone(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
// Check what year we're configured for
int conferenceYear = sp.getInt(PREF_CONFERENCE_YEAR, 0);
if (conferenceYear != Config.CONFERENCE_YEAR) {
// Application is configured for a different conference year. Reset
// preferences and re-run setup.
sp.edit().clear().putInt(PREF_CONFERENCE_YEAR, Config.CONFERENCE_YEAR).commit();
}
return sp.getBoolean(PREF_SETUP_DONE, false);
}
public static void setAttendeeAtVenue(final Context context, final boolean isAtVenue) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putBoolean(PREF_ATTENDEE_AT_VENUE, isAtVenue).commit();
}
public static void markDevSiteProfileAvailable(final Context context, final boolean isAvailable) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putBoolean(PREF_DEVSITE_PROFILE_AVAILABLE, isAvailable).commit();
}
public static boolean isDevsiteProfileAvailable(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean(PREF_DEVSITE_PROFILE_AVAILABLE, true);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.io;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.database.Cursor;
import com.google.android.apps.iosched.Config;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.Lists;
import com.google.api.services.googledevelopers.Googledevelopers;
import com.google.api.services.googledevelopers.model.FeedbackResponse;
import com.google.api.services.googledevelopers.model.ModifyFeedbackRequest;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.*;
public class FeedbackHandler {
private static final String TAG = makeLogTag(FeedbackHandler.class);
private Context mContext;
public FeedbackHandler(Context context) {
mContext = context;
}
public ArrayList<ContentProviderOperation> uploadNew(Googledevelopers conferenceApi) {
// Collect rows of feedback
Cursor feedbackCursor = mContext.getContentResolver().query(
ScheduleContract.Feedback.CONTENT_URI,
null, null, null, null);
int sessionIdIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.SESSION_ID);
int ratingIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.SESSION_RATING);
int relIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.ANSWER_RELEVANCE);
int contentIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.ANSWER_CONTENT);
int speakerIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.ANSWER_SPEAKER);
int willUseIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.ANSWER_WILLUSE);
int commentsIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.COMMENTS);
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
while (feedbackCursor.moveToNext()) {
String sessionId = feedbackCursor.getString(sessionIdIndex);
LOGI(TAG, "Uploading feedback for: " + sessionId);
int rating = feedbackCursor.getInt(ratingIndex);
int answerRelevance = feedbackCursor.getInt(relIndex);
int answerContent = feedbackCursor.getInt(contentIndex);
int answerSpeaker = feedbackCursor.getInt(speakerIndex);
int answerWillUseRaw = feedbackCursor.getInt(willUseIndex);
boolean answerWillUse = (answerWillUseRaw != 0);
String comments = feedbackCursor.getString(commentsIndex);
ModifyFeedbackRequest feedbackRequest = new ModifyFeedbackRequest();
feedbackRequest.setOverallScore(rating);
feedbackRequest.setRelevancyScore(answerRelevance);
feedbackRequest.setContentScore(answerContent);
feedbackRequest.setSpeakerScore(answerSpeaker);
// In this case, -1 means the user didn't answer the question.
if (answerWillUseRaw != -1) {
feedbackRequest.setWillUse(answerWillUse);
}
// Only post something If the comments field isn't empty
if (comments != null && comments.length() > 0) {
feedbackRequest.setAdditionalFeedback(comments);
}
feedbackRequest.setSessionId(sessionId);
feedbackRequest.setEventId(Config.EVENT_ID);
try {
Googledevelopers.Events.Sessions.Feedback feedback = conferenceApi.events().sessions()
.feedback(Config.EVENT_ID, sessionId, feedbackRequest);
FeedbackResponse response = feedback.execute();
if (response != null) {
LOGI(TAG, "Successfully sent feedback for: " + sessionId + ", comment: " + comments);
} else {
LOGE(TAG, "Sending logs failed");
}
} catch (IOException ioe) {
LOGE(TAG, "Sending logs failed and caused IOE", ioe);
return batch;
}
}
feedbackCursor.close();
// Clear out feedback forms we've just uploaded
batch.add(ContentProviderOperation.newDelete(
ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Feedback.CONTENT_URI))
.build());
return batch;
}
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* 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 com.google.android.apps.iosched.io.map.model;
public class Tile {
public String filename;
public String url;
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* 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 com.google.android.apps.iosched.io.map.model;
public class MapConfig {
public boolean enableMyLocation;
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* 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 com.google.android.apps.iosched.io.map.model;
public class Marker {
public String id;
public String type;
public float lat;
public float lng;
public String title;
public String track;
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* 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 com.google.android.apps.iosched.io.map.model;
import java.util.Map;
public class MapResponse {
public MapConfig config;
public Map<String, Marker[]> markers;
public Map<String, Tile> tiles;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.Day;
import com.google.android.apps.iosched.io.model.EventSlots;
import com.google.android.apps.iosched.io.model.TimeSlot;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Blocks;
import com.google.android.apps.iosched.util.Lists;
import com.google.android.apps.iosched.util.ParserUtils;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
public class BlocksHandler extends JSONHandler {
private static final String TAG = makeLogTag(BlocksHandler.class);
public BlocksHandler(Context context) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json) throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
try {
Gson gson = new Gson();
EventSlots eventSlots = gson.fromJson(json, EventSlots.class);
int numDays = eventSlots.day.length;
//2011-05-10T07:00:00.000-07:00
for (int i = 0; i < numDays; i++) {
Day day = eventSlots.day[i];
String date = day.date;
TimeSlot[] timeSlots = day.slot;
for (TimeSlot timeSlot : timeSlots) {
parseSlot(date, timeSlot, batch);
}
}
} catch (Throwable e) {
LOGE(TAG, e.toString());
}
return batch;
}
private static void parseSlot(String date, TimeSlot slot,
ArrayList<ContentProviderOperation> batch) {
ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(ScheduleContract.addCallerIsSyncAdapterParameter(Blocks.CONTENT_URI));
//LOGD(TAG, "Inside parseSlot:" + date + ", " + slot);
String start = slot.start;
String end = slot.end;
String type = Blocks.BLOCK_TYPE_GENERIC;
if (slot.type != null) {
type = slot.type;
}
String title = "N_D";
if (slot.title != null) {
title = slot.title;
}
String startTime = date + "T" + start + ":00.000-07:00";
String endTime = date + "T" + end + ":00.000-07:00";
LOGV(TAG, "startTime:" + startTime);
long startTimeL = ParserUtils.parseTime(startTime);
long endTimeL = ParserUtils.parseTime(endTime);
final String blockId = Blocks.generateBlockId(startTimeL, endTimeL);
LOGV(TAG, "blockId:" + blockId);
LOGV(TAG, "title:" + title);
LOGV(TAG, "start:" + startTimeL);
builder.withValue(Blocks.BLOCK_ID, blockId);
builder.withValue(Blocks.BLOCK_TITLE, title);
builder.withValue(Blocks.BLOCK_START, startTimeL);
builder.withValue(Blocks.BLOCK_END, endTimeL);
builder.withValue(Blocks.BLOCK_TYPE, type);
builder.withValue(Blocks.BLOCK_META, slot.meta);
batch.add(builder.build());
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.Config;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Announcements;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.util.Lists;
import com.google.android.apps.iosched.util.NetUtils;
import com.google.android.apps.iosched.util.UIUtils;
import com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.plus.Plus;
import com.google.api.services.plus.model.Activity;
import com.google.api.services.plus.model.ActivityFeed;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.text.TextUtils;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
public class AnnouncementsFetcher {
private static final String TAG = makeLogTag(AnnouncementsFetcher.class);
private Context mContext;
public AnnouncementsFetcher(Context context) {
mContext = context;
}
public ArrayList<ContentProviderOperation> fetchAndParse() throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
// Set up the HTTP transport and JSON factory
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new GsonFactory();
// Set up the main Google+ class
Plus plus = new Plus.Builder(httpTransport, jsonFactory, null)
.setApplicationName(NetUtils.getUserAgent(mContext))
.setGoogleClientRequestInitializer(
new CommonGoogleClientRequestInitializer(Config.API_KEY))
.build();
ActivityFeed activities;
try {
activities = plus.activities().list(Config.ANNOUNCEMENTS_PLUS_ID, "public")
.setMaxResults(100l)
.execute();
if (activities == null || activities.getItems() == null) {
throw new IOException("Activities list was null.");
}
} catch (IOException e) {
LOGE(TAG, "Error fetching announcements", e);
return batch;
}
LOGI(TAG, "Updating announcements data");
// Clear out existing announcements
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
Announcements.CONTENT_URI))
.build());
StringBuilder sb = new StringBuilder();
for (Activity activity : activities.getItems()) {
// Filter out anything not including the conference hashtag.
sb.setLength(0);
appendIfNotEmpty(sb, activity.getAnnotation());
if (activity.getObject() != null) {
appendIfNotEmpty(sb, activity.getObject().getContent());
}
if (!sb.toString().contains(UIUtils.CONFERENCE_HASHTAG)) {
continue;
}
// Insert announcement info
batch.add(ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(Announcements.CONTENT_URI))
.withValue(SyncColumns.UPDATED, System.currentTimeMillis())
.withValue(Announcements.ANNOUNCEMENT_ID, activity.getId())
.withValue(Announcements.ANNOUNCEMENT_DATE, activity.getUpdated().getValue())
.withValue(Announcements.ANNOUNCEMENT_TITLE, activity.getTitle())
.withValue(Announcements.ANNOUNCEMENT_ACTIVITY_JSON, activity.toPrettyString())
.withValue(Announcements.ANNOUNCEMENT_URL, activity.getUrl())
.build());
}
return batch;
}
private static void appendIfNotEmpty(StringBuilder sb, String s) {
if (!TextUtils.isEmpty(s)) {
sb.append(s);
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.io;
import java.io.IOException;
/**
* General {@link IOException} that indicates a problem occurred while parsing or applying a {@link
* JSONHandler}.
*/
public class HandlerException extends IOException {
public HandlerException() {
super();
}
public HandlerException(String message) {
super(message);
}
public HandlerException(String message, Throwable cause) {
super(message);
initCause(cause);
}
@Override
public String toString() {
if (getCause() != null) {
return getLocalizedMessage() + ": " + getCause();
} else {
return getLocalizedMessage();
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.io;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.graphics.Color;
import com.google.android.apps.iosched.io.model.Track;
import com.google.android.apps.iosched.io.model.Tracks;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.Lists;
import com.google.android.apps.iosched.util.ParserUtils;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
public class TracksHandler extends JSONHandler {
private static final String TAG = makeLogTag(TracksHandler.class);
public TracksHandler(Context context) {
super(context);
}
@Override
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
batch.add(ContentProviderOperation.newDelete(
ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Tracks.CONTENT_URI)).build());
Tracks tracksJson = new Gson().fromJson(json, Tracks.class);
int noOfTracks = tracksJson.getTrack().length;
for (int i = 0; i < noOfTracks; i++) {
parseTrack(tracksJson.getTrack()[i], batch);
}
return batch;
}
private static void parseTrack(Track track, ArrayList<ContentProviderOperation> batch) {
ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(
ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Tracks.CONTENT_URI));
builder.withValue(ScheduleContract.Tracks.TRACK_ID, track.id);
builder.withValue(ScheduleContract.Tracks.TRACK_NAME, track.name);
builder.withValue(ScheduleContract.Tracks.TRACK_COLOR, Color.parseColor(track.color));
builder.withValue(ScheduleContract.Tracks.TRACK_ABSTRACT, track._abstract);
builder.withValue(ScheduleContract.Tracks.TRACK_LEVEL, track.level);
builder.withValue(ScheduleContract.Tracks.TRACK_ORDER_IN_LEVEL,
track.order_in_level);
builder.withValue(ScheduleContract.Tracks.TRACK_META, track.meta);
builder.withValue(ScheduleContract.Tracks.TRACK_HASHTAG, ParserUtils.sanitizeId(track.name));
batch.add(builder.build());
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.io;
import android.content.ContentProviderOperation;
import android.content.Context;
import com.google.android.apps.iosched.Config;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.util.Lists;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.googledevelopers.Googledevelopers;
import com.google.api.services.googledevelopers.model.PresenterResponse;
import com.google.api.services.googledevelopers.model.PresentersResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static com.google.android.apps.iosched.provider.ScheduleContract.Speakers;
import static com.google.android.apps.iosched.util.LogUtils.*;
public class SpeakersHandler {
private static final String TAG = makeLogTag(SpeakersHandler.class);
public SpeakersHandler(Context context) {}
public ArrayList<ContentProviderOperation> fetchAndParse(
Googledevelopers conferenceAPI)
throws IOException {
PresentersResponse presenters;
try {
presenters = conferenceAPI.events().presenters().list(Config.EVENT_ID).execute();
if (presenters == null || presenters.getPresenters() == null) {
throw new HandlerException("Speakers list was null.");
}
} catch (HandlerException e) {
LOGE(TAG, "Error fetching speakers", e);
return Lists.newArrayList();
}
return buildContentProviderOperations(presenters);
}
public ArrayList<ContentProviderOperation> parseString(String json) {
JsonFactory jsonFactory = new GsonFactory();
try {
PresentersResponse presenters = jsonFactory.fromString(json, PresentersResponse.class);
return buildContentProviderOperations(presenters);
} catch (IOException e) {
LOGE(TAG, "Error reading speakers from packaged data", e);
return Lists.newArrayList();
}
}
private ArrayList<ContentProviderOperation> buildContentProviderOperations(
PresentersResponse presenters) {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
if (presenters != null) {
List<PresenterResponse> presenterList = presenters.getPresenters();
int numSpeakers = presenterList.size();
if (numSpeakers > 0) {
LOGI(TAG, "Updating presenters data");
// Clear out existing speakers
batch.add(ContentProviderOperation.newDelete(
ScheduleContract.addCallerIsSyncAdapterParameter(
Speakers.CONTENT_URI))
.build());
// Insert latest speaker data
for (PresenterResponse presenter : presenterList) {
// Hack: Fix speaker URL so that it's not being resized
// Depends on thumbnail URL being exactly in the format we want
String thumbnail = presenter.getThumbnailUrl();
if (thumbnail != null) {
thumbnail = thumbnail.replace("?sz=50", "?sz=100");
}
batch.add(ContentProviderOperation.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(Speakers.CONTENT_URI))
.withValue(SyncColumns.UPDATED, System.currentTimeMillis())
.withValue(Speakers.SPEAKER_ID, presenter.getId())
.withValue(Speakers.SPEAKER_NAME, presenter.getName())
.withValue(Speakers.SPEAKER_ABSTRACT, presenter.getBio())
.withValue(Speakers.SPEAKER_IMAGE_URL, thumbnail)
.withValue(Speakers.SPEAKER_URL, presenter.getPlusoneUrl())
.build());
}
}
}
return batch;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.io;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import com.google.android.apps.iosched.Config;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.provider.ScheduleDatabase;
import com.google.android.apps.iosched.util.*;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.googledevelopers.Googledevelopers;
import com.google.api.services.googledevelopers.model.SessionResponse;
import com.google.api.services.googledevelopers.model.SessionsResponse;
import com.google.api.services.googledevelopers.model.TrackResponse;
import com.google.api.services.googledevelopers.model.TracksResponse;
import java.io.IOException;
import java.util.*;
import static com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers;
import static com.google.android.apps.iosched.util.LogUtils.*;
import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId;
public class SessionsHandler {
private static final String TAG = makeLogTag(SessionsHandler.class);
private static final String BASE_SESSION_URL
= "https://developers.google.com/events/io/sessions/";
private static final String EVENT_TYPE_KEYNOTE = Sessions.SESSION_TYPE_KEYNOTE;
private static final String EVENT_TYPE_OFFICE_HOURS = Sessions.SESSION_TYPE_OFFICE_HOURS;
private static final String EVENT_TYPE_CODELAB = Sessions.SESSION_TYPE_CODELAB;
private static final String EVENT_TYPE_SANDBOX = Sessions.SESSION_TYPE_SANDBOX;
private static final int PARSE_FLAG_FORCE_SCHEDULE_REMOVE = 1;
private static final int PARSE_FLAG_FORCE_SCHEDULE_ADD = 2;
private Context mContext;
public SessionsHandler(Context context) {
mContext = context;
}
public ArrayList<ContentProviderOperation> fetchAndParse(
Googledevelopers conferenceAPI)
throws IOException {
// Set up the HTTP transport and JSON factory
SessionsResponse sessions;
SessionsResponse starredSessions = null;
TracksResponse tracks;
try {
sessions = conferenceAPI.events().sessions().list(Config.EVENT_ID).setLimit(9999L).execute();
tracks = conferenceAPI.events().tracks().list(Config.EVENT_ID).execute();
if (sessions == null || sessions.getSessions() == null) {
throw new HandlerException("Sessions list was null.");
}
if (tracks == null || tracks.getTracks() == null) {
throw new HandlerException("trackDetails list was null.");
}
} catch (HandlerException e) {
LOGE(TAG, "Fatal: error fetching sessions/tracks", e);
return Lists.newArrayList();
}
final boolean profileAvailableBefore = PrefUtils.isDevsiteProfileAvailable(mContext);
boolean profileAvailableNow = false;
try {
starredSessions = conferenceAPI.users().events().sessions().list(Config.EVENT_ID).execute();
// If this succeeded, the user has a DevSite profile
PrefUtils.markDevSiteProfileAvailable(mContext, true);
profileAvailableNow = true;
} catch (GoogleJsonResponseException e) {
// Hack: If the user doesn't have a developers.google.com profile, the Conference API
// will respond with HTTP 401 and include something like
// "Provided user does not have a developers.google.com profile" in the message.
if (401 == e.getStatusCode()
&& e.getDetails() != null
&& e.getDetails().getMessage() != null
&& e.getDetails().getMessage().contains("developers.google.com")) {
LOGE(TAG, "User does not have a developers.google.com profile. Not syncing remote " +
"personalized schedule.");
starredSessions = null;
// Record that the user's profile is offline. If this changes later, we'll re-upload any local
// starred sessions.
PrefUtils.markDevSiteProfileAvailable(mContext, false);
} else {
LOGW(TAG, "Auth token invalid, requesting refresh", e);
AccountUtils.refreshAuthToken(mContext);
}
}
if (profileAvailableNow && !profileAvailableBefore) {
LOGI(TAG, "developers.google.com mode change: DEVSITE_PROFILE_AVAILABLE=false -> true");
// User's DevSite profile has come into existence. Re-upload tracks.
ContentResolver cr = mContext.getContentResolver();
String[] projection = new String[] {ScheduleContract.Sessions.SESSION_ID, Sessions.SESSION_TITLE};
Cursor c = cr.query(ScheduleContract.BASE_CONTENT_URI.buildUpon().
appendPath("sessions").appendPath("starred").build(), projection, null, null, null);
if (c != null) {
c.moveToFirst();
while (!c.isAfterLast()) {
String id = c.getString(0);
String title = c.getString(1);
LOGI(TAG, "Adding session: (" + id + ") " + title);
Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(id);
SessionsHelper.uploadStarredSession(mContext, sessionUri, true);
c.moveToNext();
}
}
// Hack: Use local starred sessions for now, to give the new sessions time to take effect
// TODO(trevorjohns): Upload starred sessions should be synchronous to avoid this hack
starredSessions = null;
}
return buildContentProviderOperations(sessions, starredSessions, tracks);
}
public ArrayList<ContentProviderOperation> parseString(String sessionsJson, String tracksJson) {
JsonFactory jsonFactory = new GsonFactory();
try {
SessionsResponse sessions = jsonFactory.fromString(sessionsJson, SessionsResponse.class);
TracksResponse tracks =
jsonFactory.fromString(tracksJson, TracksResponse.class);
return buildContentProviderOperations(sessions, null, tracks);
} catch (IOException e) {
LOGE(TAG, "Error reading speakers from packaged data", e);
return Lists.newArrayList();
}
}
private ArrayList<ContentProviderOperation> buildContentProviderOperations(
SessionsResponse sessions,
SessionsResponse starredSessions,
TracksResponse tracks) {
// If there was no starred sessions response (e.g. there was an auth issue,
// or this is a local sync), keep all the locally starred sessions.
boolean retainLocallyStarredSessions = (starredSessions == null);
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
// Build lookup table for starredSessions mappings
HashSet<String> starredSessionsMap = new HashSet<String>();
if (starredSessions != null) {
List<SessionResponse> starredSessionList =
starredSessions.getSessions();
if (starredSessionList != null) {
for (SessionResponse session : starredSessionList) {
String sessionId = session.getId();
starredSessionsMap.add(sessionId);
}
}
}
// Build lookup table for track mappings
// Assumes that sessions can only have one track. Not guarenteed by the Conference API,
// but is being enforced by conference organizer policy.
HashMap<String, TrackResponse> trackMap
= new HashMap<String, TrackResponse>();
if (tracks != null) {
for (TrackResponse track : tracks.getTracks()) {
List<String> sessionIds = track.getSessions();
if (sessionIds != null) {
for (String sessionId : sessionIds) {
trackMap.put(sessionId, track);
}
}
}
}
if (sessions != null) {
List<SessionResponse> sessionList = sessions.getSessions();
int numSessions = sessionList.size();
if (numSessions > 0) {
LOGI(TAG, "Updating sessions data");
Set<String> starredSessionIds = new HashSet<String>();
if (retainLocallyStarredSessions) {
Cursor starredSessionsCursor = mContext.getContentResolver().query(
Sessions.CONTENT_STARRED_URI,
new String[]{ScheduleContract.Sessions.SESSION_ID},
null, null, null);
while (starredSessionsCursor.moveToNext()) {
starredSessionIds.add(starredSessionsCursor.getString(0));
}
starredSessionsCursor.close();
}
// Clear out existing sessions
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
Sessions.CONTENT_URI))
.build());
// Maintain a list of created session block IDs
Set<String> blockIds = new HashSet<String>();
// Maintain a map of insert operations for sandbox-only blocks
HashMap<String, ContentProviderOperation> sandboxBlocks = new HashMap<String, ContentProviderOperation>();
for (SessionResponse session : sessionList) {
int flags = 0;
String sessionId = session.getId();
if (retainLocallyStarredSessions) {
flags = (starredSessionIds.contains(sessionId)
? PARSE_FLAG_FORCE_SCHEDULE_ADD
: PARSE_FLAG_FORCE_SCHEDULE_REMOVE);
}
if (TextUtils.isEmpty(sessionId)) {
LOGW(TAG, "Found session with empty ID in API response.");
continue;
}
// Session title
String sessionTitle = session.getTitle();
String sessionSubtype = session.getSubtype();
if (EVENT_TYPE_CODELAB.equals(sessionSubtype)) {
sessionTitle = mContext.getString(
R.string.codelab_title_template, sessionTitle);
}
// Whether or not it's in the schedule
boolean inSchedule = starredSessionsMap.contains(sessionId);
if ((flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0
|| (flags & PARSE_FLAG_FORCE_SCHEDULE_REMOVE) != 0) {
inSchedule = (flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0;
}
if (EVENT_TYPE_KEYNOTE.equals(sessionSubtype)) {
// Keynotes are always in your schedule.
inSchedule = true;
}
// Clean up session abstract
String sessionAbstract = session.getDescription();
if (sessionAbstract != null) {
sessionAbstract = sessionAbstract.replace('\r', '\n');
}
// Hashtags
TrackResponse track = trackMap.get(sessionId);
String hashtag = null;
if (track != null) {
hashtag = ParserUtils.sanitizeId(track.getTitle());
}
boolean isLivestream = false;
try {
isLivestream = session.getIsLivestream();
} catch (NullPointerException ignored) {
}
String youtubeUrl = session.getYoutubeUrl();
// Get block id
long sessionStartTime = session.getStartTimestamp().longValue() * 1000;
long sessionEndTime = session.getEndTimestamp().longValue() * 1000;
String blockId = ScheduleContract.Blocks.generateBlockId(
sessionStartTime, sessionEndTime);
if (!blockIds.contains(blockId) && !EVENT_TYPE_SANDBOX.equals(sessionSubtype)) {
// New non-sandbox block
if (sandboxBlocks.containsKey(blockId)) {
sandboxBlocks.remove(blockId);
}
String blockType;
String blockTitle;
if (EVENT_TYPE_KEYNOTE.equals(sessionSubtype)) {
blockType = ScheduleContract.Blocks.BLOCK_TYPE_KEYNOTE;
blockTitle = mContext.getString(R.string.schedule_block_title_keynote);
} else if (EVENT_TYPE_CODELAB.equals(sessionSubtype)) {
blockType = ScheduleContract.Blocks.BLOCK_TYPE_CODELAB;
blockTitle = mContext.getString(
R.string.schedule_block_title_code_labs);
} else if (EVENT_TYPE_OFFICE_HOURS.equals(sessionSubtype)) {
blockType = ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS;
blockTitle = mContext.getString(
R.string.schedule_block_title_office_hours);
} else {
blockType = ScheduleContract.Blocks.BLOCK_TYPE_SESSION;
blockTitle = mContext.getString(
R.string.schedule_block_title_sessions);
}
batch.add(ContentProviderOperation
.newInsert(ScheduleContract.Blocks.CONTENT_URI)
.withValue(ScheduleContract.Blocks.BLOCK_ID, blockId)
.withValue(ScheduleContract.Blocks.BLOCK_TYPE, blockType)
.withValue(ScheduleContract.Blocks.BLOCK_TITLE, blockTitle)
.withValue(ScheduleContract.Blocks.BLOCK_START, sessionStartTime)
.withValue(ScheduleContract.Blocks.BLOCK_END, sessionEndTime)
.build());
blockIds.add(blockId);
} else if (!sandboxBlocks.containsKey(blockId) && !blockIds.contains(blockId) && EVENT_TYPE_SANDBOX.equals(sessionSubtype)) {
// New sandbox-only block, add insert operation to map
String blockType = ScheduleContract.Blocks.BLOCK_TYPE_SANDBOX;
String blockTitle = mContext.getString(
R.string.schedule_block_title_sandbox);
sandboxBlocks.put(blockId,
ContentProviderOperation
.newInsert(ScheduleContract.Blocks.CONTENT_URI)
.withValue(ScheduleContract.Blocks.BLOCK_ID, blockId)
.withValue(ScheduleContract.Blocks.BLOCK_TYPE, blockType)
.withValue(ScheduleContract.Blocks.BLOCK_TITLE, blockTitle)
.withValue(ScheduleContract.Blocks.BLOCK_START, sessionStartTime)
.withValue(ScheduleContract.Blocks.BLOCK_END, sessionEndTime)
.build());
}
// Insert session info
final ContentProviderOperation.Builder builder;
if (EVENT_TYPE_SANDBOX.equals(sessionSubtype)) {
// Sandbox companies go in the special sandbox table
builder = ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(ScheduleContract.Sandbox.CONTENT_URI))
.withValue(SyncColumns.UPDATED, System.currentTimeMillis())
.withValue(ScheduleContract.Sandbox.COMPANY_ID, sessionId)
.withValue(ScheduleContract.Sandbox.COMPANY_NAME, sessionTitle)
.withValue(ScheduleContract.Sandbox.COMPANY_DESC, sessionAbstract)
.withValue(ScheduleContract.Sandbox.COMPANY_URL, makeSessionUrl(sessionId))
.withValue(ScheduleContract.Sandbox.COMPANY_LOGO_URL, session.getIconUrl())
.withValue(ScheduleContract.Sandbox.ROOM_ID, sanitizeId(session.getLocation()))
.withValue(ScheduleContract.Sandbox.TRACK_ID, (track != null ? track.getId() : null))
.withValue(ScheduleContract.Sandbox.BLOCK_ID, blockId);
batch.add(builder.build());
} else {
// All other fields go in the normal sessions table
builder = ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(Sessions.CONTENT_URI))
.withValue(SyncColumns.UPDATED, System.currentTimeMillis())
.withValue(Sessions.SESSION_ID, sessionId)
.withValue(Sessions.SESSION_TYPE, sessionSubtype)
.withValue(Sessions.SESSION_LEVEL, null) // Not available
.withValue(Sessions.SESSION_TITLE, sessionTitle)
.withValue(Sessions.SESSION_ABSTRACT, sessionAbstract)
.withValue(Sessions.SESSION_HASHTAGS, hashtag)
.withValue(Sessions.SESSION_TAGS, null) // Not available
.withValue(Sessions.SESSION_URL, makeSessionUrl(sessionId))
.withValue(Sessions.SESSION_LIVESTREAM_URL,
isLivestream ? youtubeUrl : null)
.withValue(Sessions.SESSION_MODERATOR_URL, null) // Not available
.withValue(Sessions.SESSION_REQUIREMENTS, null) // Not available
.withValue(Sessions.SESSION_STARRED, inSchedule)
.withValue(Sessions.SESSION_YOUTUBE_URL,
isLivestream ? null : youtubeUrl)
.withValue(Sessions.SESSION_PDF_URL, null) // Not available
.withValue(Sessions.SESSION_NOTES_URL, null) // Not available
.withValue(Sessions.ROOM_ID, sanitizeId(session.getLocation()))
.withValue(Sessions.BLOCK_ID, blockId);
batch.add(builder.build());
}
// Replace all session speakers
final Uri sessionSpeakersUri = Sessions.buildSpeakersDirUri(sessionId);
batch.add(ContentProviderOperation
.newDelete(ScheduleContract
.addCallerIsSyncAdapterParameter(sessionSpeakersUri))
.build());
List<String> presenterIds = session.getPresenterIds();
if (presenterIds != null) {
for (String presenterId : presenterIds) {
batch.add(ContentProviderOperation.newInsert(sessionSpeakersUri)
.withValue(SessionsSpeakers.SESSION_ID, sessionId)
.withValue(SessionsSpeakers.SPEAKER_ID, presenterId).build());
}
}
// Add track mapping
if (track != null) {
String trackId = track.getId();
if (trackId != null) {
final Uri sessionTracksUri = ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Sessions.buildTracksDirUri(sessionId));
batch.add(ContentProviderOperation.newInsert(sessionTracksUri)
.withValue(ScheduleDatabase.SessionsTracks.SESSION_ID, sessionId)
.withValue(ScheduleDatabase.SessionsTracks.TRACK_ID, trackId).build());
}
}
// Codelabs: Add mapping to codelab table
if (EVENT_TYPE_CODELAB.equals(sessionSubtype)) {
final Uri sessionTracksUri = ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Sessions.buildTracksDirUri(sessionId));
batch.add(ContentProviderOperation.newInsert(sessionTracksUri)
.withValue(ScheduleDatabase.SessionsTracks.SESSION_ID, sessionId)
.withValue(ScheduleDatabase.SessionsTracks.TRACK_ID, "CODE_LABS").build());
}
}
// Insert sandbox-only blocks
batch.addAll(sandboxBlocks.values());
}
}
return batch;
}
private String makeSessionUrl(String sessionId) {
if (TextUtils.isEmpty(sessionId)) {
return null;
}
return BASE_SESSION_URL + sessionId;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.Room;
import com.google.android.apps.iosched.io.model.Rooms;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
public class RoomsHandler extends JSONHandler {
private static final String TAG = makeLogTag(RoomsHandler.class);
public RoomsHandler(Context context) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json) throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
Rooms roomsJson = new Gson().fromJson(json, Rooms.class);
int noOfRooms = roomsJson.rooms.length;
for (int i = 0; i < noOfRooms; i++) {
parseRoom(roomsJson.rooms[i], batch);
}
return batch;
}
private static void parseRoom(Room room, ArrayList<ContentProviderOperation> batch) {
ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Rooms.CONTENT_URI));
builder.withValue(ScheduleContract.Rooms.ROOM_ID, room.id);
builder.withValue(ScheduleContract.Rooms.ROOM_NAME, room.name);
builder.withValue(ScheduleContract.Rooms.ROOM_FLOOR, room.floor);
batch.add(builder.build());
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.provider.ScheduleContract;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.OperationApplicationException;
import android.os.RemoteException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
public abstract class JSONHandler {
protected static Context mContext;
public JSONHandler(Context context) {
mContext = context;
}
public abstract ArrayList<ContentProviderOperation> parse(String json) throws IOException;
public final void parseAndApply(String json) throws IOException {
try {
final ContentResolver resolver = mContext.getContentResolver();
ArrayList<ContentProviderOperation> batch = parse(json);
resolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, batch);
} catch (RemoteException e) {
throw new RuntimeException("Problem applying batch operation", e);
} catch (OperationApplicationException e) {
throw new RuntimeException("Problem applying batch operation", e);
}
}
public static String parseResource(Context context, int resource) throws IOException {
InputStream is = context.getResources().openRawResource(resource);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.SearchSuggestions;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.app.SearchManager;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
public class SearchSuggestHandler extends JSONHandler {
public SearchSuggestHandler(Context context) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
SearchSuggestions suggestions = new Gson().fromJson(json, SearchSuggestions.class);
if (suggestions.words != null) {
// Clear out suggestions
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.SearchSuggest.CONTENT_URI))
.build());
// Rebuild suggestions
for (String word : suggestions.words) {
batch.add(ContentProviderOperation
.newInsert(ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.SearchSuggest.CONTENT_URI))
.withValue(SearchManager.SUGGEST_COLUMN_TEXT_1, word)
.build());
}
}
return batch;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.io;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.util.Log;
import com.google.android.apps.iosched.io.map.model.MapConfig;
import com.google.android.apps.iosched.io.map.model.MapResponse;
import com.google.android.apps.iosched.io.map.model.Marker;
import com.google.android.apps.iosched.io.map.model.Tile;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.Lists;
import com.google.android.apps.iosched.util.MapUtils;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class MapPropertyHandler extends JSONHandler {
private static final String TAG = makeLogTag(MapPropertyHandler.class);
private Collection<Tile> mTiles;
public MapPropertyHandler(Context context) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
MapResponse mapJson = new Gson().fromJson(json, MapResponse.class);
parseTileOverlays(mapJson.tiles, batch, mContext);
parseMarkers(mapJson.markers, batch);
parseConfig(mapJson.config, mContext);
mTiles = mapJson.tiles.values();
return batch;
}
private void parseConfig(MapConfig config, Context mContext) {
boolean enableMyLocation = config.enableMyLocation;
MapUtils.setMyLocationEnabled(mContext,enableMyLocation);
}
private void parseMarkers(Map<String, Marker[]> markers,
ArrayList<ContentProviderOperation> batch) {
for (Entry<String, Marker[]> entry : markers.entrySet()) {
String floor = entry.getKey();
// add each Marker
for (Marker marker : entry.getValue()) {
ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(ScheduleContract.MapMarkers.CONTENT_URI));
builder.withValue(ScheduleContract.MapMarkers.MARKER_ID, marker.id);
builder.withValue(ScheduleContract.MapMarkers.MARKER_FLOOR, floor);
builder.withValue(ScheduleContract.MapMarkers.MARKER_LABEL,
marker.title);
builder.withValue(ScheduleContract.MapMarkers.MARKER_LATITUDE,
marker.lat);
builder.withValue(ScheduleContract.MapMarkers.MARKER_LONGITUDE,
marker.lng);
builder.withValue(ScheduleContract.MapMarkers.MARKER_TYPE,
marker.type);
builder.withValue(ScheduleContract.MapMarkers.MARKER_TRACK, marker.track);
batch.add(builder.build());
}
}
}
private void parseTileOverlays(Map<String, Tile> tiles,
ArrayList<ContentProviderOperation> batch, Context context) {
for (Entry<String, Tile> entry : tiles.entrySet()) {
ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(ScheduleContract.MapTiles.CONTENT_URI));
String floor = entry.getKey();
Tile value = entry.getValue();
builder.withValue(
ScheduleContract.MapTiles.TILE_FLOOR, floor);
builder.withValue(
ScheduleContract.MapTiles.TILE_FILE, value.filename);
builder.withValue(
ScheduleContract.MapTiles.TILE_URL, value.url);
Log.d(TAG, "adding overlay: " + floor + ", " + value.filename);
/*
* Setup the tile overlay file. Copy it from the app assets or
* download it if it does not exist locally. This is done here to
* ensure that the data stored in the content provider always points
* to valid tile files.
*/
batch.add(builder.build());
}
}
public Collection<Tile> getTiles(){
return mTiles;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.io.model;
import com.google.gson.annotations.SerializedName;
public class Track {
public String id;
public String name;
public String color;
@SerializedName("abstract")
public String _abstract;
public int level;
public int order_in_level;
public int meta;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.io.model;
public class TimeSlot {
public String start;
public String end;
public String title;
public String type;
public String meta;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.io.model;
public class Rooms {
public Room[] rooms;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.io.model;
public class Day {
public String date;
public TimeSlot[] slot;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.io.model;
public class SearchSuggestions {
public String[] words;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.io.model;
public class Tracks {
Track[] track;
public Track[] getTrack() {
return track;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.io.model;
public class EventSlots {
public Day[] day;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.io.model;
public class Room {
public String id;
public String name;
public String floor;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.gcm.server;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Skeleton class for all servlets in this package.
*
* <p>Provides extra logging information when running in debug mode.
*/
@SuppressWarnings("serial")
public abstract class BaseServlet extends HttpServlet {
// change to true to allow GET calls
static final boolean DEBUG = true;
protected final Logger logger = Logger.getLogger(getClass().getName());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
if (DEBUG) {
doPost(req, resp);
} else {
super.doGet(req, resp);
}
}
protected String getParameter(HttpServletRequest req, String parameter)
throws ServletException {
String value = req.getParameter(parameter);
if (value == null || value.trim().isEmpty()) {
if (DEBUG) {
StringBuilder parameters = new StringBuilder();
@SuppressWarnings("unchecked")
Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String param = req.getParameter(name);
parameters.append(name).append("=").append(param).append("\n");
}
logger.fine("parameters: " + parameters);
}
throw new ServletException("Parameter " + parameter + " not found");
}
return value.trim();
}
protected String getParameter(HttpServletRequest req, String parameter,
String defaultValue) {
String value = req.getParameter(parameter);
if (value == null || value.trim().isEmpty()) {
value = defaultValue;
}
return value.trim();
}
protected void setSuccess(HttpServletResponse resp) {
setSuccess(resp, 0);
}
protected void setSuccess(HttpServletResponse resp, int size) {
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType("text/plain");
resp.setContentLength(size);
}
protected boolean checkUser() {
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
String authDomain = user.getAuthDomain();
if (authDomain.contains("google.com")) {
return true;
} else {
return false;
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.gcm.server.admin;
import com.google.android.apps.iosched.gcm.server.BaseServlet;
import com.google.android.apps.iosched.gcm.server.db.DeviceStore;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class AdminServlet extends BaseServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("<html><body>");
out.print("<head><title>IOSched GCM Server</title>");
out.print("</head>");
String status = (String) req.getAttribute("status");
if (status != null) {
out.print(status);
}
out.print("</body></html>");
out.print("<h2>" + DeviceStore.getDeviceCount() + " device(s) registered!</h2>");
out.print("<form method='POST' action='/scheduleupdate'>");
out.print("<table>");
out.print("<tr>");
out.print("<td>Key:</td>");
out.print("<td><input type='password' name='key' size='80'/></td>");
out.print("</tr>");
out.print("<tr>");
out.print("<td>Announcement:</td>");
out.print("<td><input type='text' name='announcement' size='80'/></td>");
out.print("</tr>");
out.print("</table>");
out.print("<br/>");
out.print("<input type='submit' value='Send Message' />");
out.print("</form>");
resp.addHeader("X-FRAME-OPTIONS", "DENY");
resp.setStatus(HttpServletResponse.SC_OK);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.gcm.server.device;
import com.google.android.apps.iosched.gcm.server.BaseServlet;
import com.google.android.apps.iosched.gcm.server.db.DeviceStore;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that unregisters a device, whose registration id is identified by
* {@link #PARAMETER_REG_ID}.
* <p>
* The client app should call this servlet everytime it receives a
* {@code com.google.android.c2dm.intent.REGISTRATION} with an
* {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class UnregisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "gcm_id";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
DeviceStore.unregister(regId);
setSuccess(resp);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.gcm.server.device;
import com.google.android.apps.iosched.gcm.server.BaseServlet;
import com.google.android.apps.iosched.gcm.server.db.DeviceStore;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that registers a device, whose registration id is identified by
* {@link #PARAMETER_REG_ID}.
*
* <p>
* The client app should call this servlet everytime it receives a
* {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an
* error or {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class RegisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "gcm_id";
private static final String PARAMETER_USER_ID = "gplus_id";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String gcmId = getParameter(req, PARAMETER_REG_ID);
String gPlusId = getParameter(req, PARAMETER_USER_ID);
DeviceStore.register(gcmId, gPlusId);
setSuccess(resp);
}
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* 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 com.google.android.apps.iosched.gcm.server.device;
import com.google.android.apps.iosched.gcm.server.db.ApiKeyInitializer;
import com.google.android.apps.iosched.gcm.server.db.MessageStore;
import com.google.android.apps.iosched.gcm.server.db.DeviceStore;
import com.google.android.apps.iosched.gcm.server.db.models.Device;
import com.google.android.apps.iosched.gcm.server.db.models.MulticastMessage;
import com.google.android.gcm.server.*;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import javax.servlet.ServletConfig;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
/** Utility class for sending individual messages to devices.
*
* This class is responsible for communication with the GCM server for purposes of sending
* messages.
*
* @return true if success, false if
*/
public class MessageSender {
private String mApiKey;
private Sender mGcmService;
private static final int TTL = (int) TimeUnit.MINUTES.toSeconds(300);
protected final Logger mLogger = Logger.getLogger(getClass().getName());
/** Maximum devices in a multicast message */
private static final int MAX_DEVICES = 1000;
public MessageSender(ServletConfig config) {
mApiKey = (String) config.getServletContext().getAttribute(
ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY);
mGcmService = new Sender(mApiKey);
}
public void multicastSend(List<Device> devices, String action,
String squelch, String extraData) {
Queue queue = QueueFactory.getQueue("MulticastMessagesQueue");
// Split messages into batches for multicast
// GCM limits maximum devices per multicast request. AppEngine also limits the size of
// lists stored in the datastore.
int total = devices.size();
List<String> partialDevices = new ArrayList<String>(total);
int counter = 0;
for (Device device : devices) {
counter ++;
// If squelch is set, device is the originator of this message,
// and has asked us to squelch itself. This prevents message echos.
if (!device.getGcmId().equals(squelch)) {
// Device not squelched.
partialDevices.add(device.getGcmId());
}
int partialSize = partialDevices.size();
if (partialSize == MAX_DEVICES || counter == total) {
// Send multicast message
Long multicastKey = MessageStore.createMulticast(partialDevices,
action,
extraData);
mLogger.fine("Queuing " + partialSize + " devices on multicast " + multicastKey);
TaskOptions taskOptions = TaskOptions.Builder
.withUrl("/queue/send")
.param("multicastKey", Long.toString(multicastKey))
.method(TaskOptions.Method.POST);
queue.add(taskOptions);
partialDevices.clear();
}
}
mLogger.fine("Queued message to " + total + " devices");
}
boolean sendMessage(Long multicastId) {
MulticastMessage msg = MessageStore.getMulticast(multicastId);
List<String> devices = msg.getDestinations();
String action = msg.getAction();
Message.Builder builder = new Message.Builder().delayWhileIdle(true);
if (action == null || action.length() == 0) {
throw new IllegalArgumentException("Message action cannot be empty.");
}
builder.collapseKey(action)
.addData("action", action)
.addData("extraData", msg.getExtraData())
.timeToLive(TTL);
Message message = builder.build();
MulticastResult multicastResult = null;
try {
// TODO(trevorjohns): We occasionally see null messages. (Maybe due to squelch?)
// We should these from entering the send queue in the first place. In the meantime,
// here's a hack to prevent this.
if (devices != null) {
multicastResult = mGcmService.sendNoRetry(message, devices);
mLogger.info("Result: " + multicastResult);
} else {
mLogger.info("Null device list detected. Aborting.");
return true;
}
} catch (IOException e) {
mLogger.log(Level.SEVERE, "Exception posting " + message, e);
return true;
}
boolean allDone = true;
// check if any registration id must be updated
if (multicastResult.getCanonicalIds() != 0) {
List<Result> results = multicastResult.getResults();
for (int i = 0; i < results.size(); i++) {
String canonicalRegId = results.get(i).getCanonicalRegistrationId();
if (canonicalRegId != null) {
String regId = devices.get(i);
DeviceStore.updateRegistration(regId, canonicalRegId);
}
}
}
if (multicastResult.getFailure() != 0) {
// there were failures, check if any could be retried
List<Result> results = multicastResult.getResults();
List<String> retriableRegIds = new ArrayList<String>();
for (int i = 0; i < results.size(); i++) {
String error = results.get(i).getErrorCodeName();
if (error != null) {
String regId = devices.get(i);
mLogger.warning("Got error (" + error + ") for regId " + regId);
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
DeviceStore.unregister(regId);
}
if (error.equals(Constants.ERROR_UNAVAILABLE)) {
retriableRegIds.add(regId);
}
}
}
if (!retriableRegIds.isEmpty()) {
// update task
MessageStore.updateMulticast(multicastId, retriableRegIds);
allDone = false;
return false;
}
}
if (allDone) {
return true;
} else {
return false;
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.gcm.server.device;
import com.google.android.apps.iosched.gcm.server.BaseServlet;
import com.google.android.apps.iosched.gcm.server.db.MessageStore;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that adds a new message and notifies all registered devices.
*
* <p>This class should not be called directly. Instead, it's used as a helper
* for the SendMessage task queue.
*/
@SuppressWarnings("serial")
public class MulticastQueueWorker extends BaseServlet {
private MessageSender mSender;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
mSender = new MessageSender(config);
}
/**
* Processes the request to add a new message.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
Long multicastId = new Long(req.getParameter("multicastKey"));
boolean success = mSender.sendMessage(multicastId);
if (success) {
taskDone(resp, multicastId);
} else {
retryTask(resp);
}
}
/**
* Indicates to App Engine that this task should be retried.
*/
private void retryTask(HttpServletResponse resp) {
resp.setStatus(500);
}
/**
* Indicates to App Engine that this task is done.
*/
private void taskDone(HttpServletResponse resp, Long multicastId) {
MessageStore.deleteMulticast(multicastId);
resp.setStatus(200);
}
}
| Java |
/**
* Copyright 2012 Google
*
* 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 com.google.android.apps.iosched.gcm.server.api;
import com.google.android.apps.iosched.gcm.server.BaseServlet;
import com.google.android.apps.iosched.gcm.server.db.DeviceStore;
import com.google.android.apps.iosched.gcm.server.db.models.Device;
import com.google.android.apps.iosched.gcm.server.device.MessageSender;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** Send message to all registered devices */
@SuppressWarnings("serial")
public class SendMessageServlet extends BaseServlet {
private static final Logger LOG = Logger.getLogger(SendMessageServlet.class.getName());
/** Authentication key for incoming message requests */
private static final String[][] AUTHORIZED_KEYS = {
{"YOUR_API_KEYS_HERE", "developers.google.com"},
{"YOUR_API_KEYS_HERE", "googleapis.com/googledevelopers"},
{"YOUR_API_KEYS_HERE", "Device Key"}
};
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Authenticate request
String authKey = null;
String authHeader = req.getHeader("Authorization");
String squelch = null;
if (authHeader != null) {
// Use 'Authorization: key=...' header
String splitHeader[] = authHeader.split("=");
if ("key".equals(splitHeader[0])) {
authKey = splitHeader[1];
}
}
if (authKey == null) {
// Valid auth key not found. Check for 'key' query parameter.
// Note: This is included for WebHooks support, but will consume message body!
authKey = req.getParameter("key");
squelch = req.getParameter("squelch");
}
String authorizedUser = null;
for (String[] candidateKey : AUTHORIZED_KEYS) {
if (candidateKey[0].equals(authKey)) {
authorizedUser = candidateKey[1];
break;
}
}
if (authorizedUser == null) {
send(resp, 403, "Not authorized");
return;
}
// Extract URL components
String result = req.getPathInfo();
if (result == null) {
send(resp, 400, "Bad request (check request format)");
return;
}
String[] components = result.split("/");
if (components.length != 3) {
send(resp, 400, "Bad request (check request format)");
return;
}
String target = components[1];
String action = components[2];
// Extract extraData
String payload = readBody(req);
// Override: add jitter for server update requests
// if ("sync_schedule".equals(action)) {
// payload = "{ \"sync_jitter\": 21600000 }";
// }
// Request decoding complete. Log request parameters
LOG.info("Authorized User: " + authorizedUser +
"\nTarget: " + target +
"\nAction: " + action +
"\nSquelch: " + (squelch != null ? squelch : "null") +
"\nExtra Data: " + payload);
// Send broadcast message
MessageSender sender = new MessageSender(getServletConfig());
if ("global".equals(target)) {
List<Device> allDevices = DeviceStore.getAllDevices();
if (allDevices == null || allDevices.isEmpty()) {
send(resp, 404, "No devices registered");
} else {
int resultCount = allDevices.size();
LOG.info("Selected " + resultCount + " devices");
sender.multicastSend(allDevices, action, squelch, payload);
send(resp, 200, "Message queued: " + resultCount + " devices");
}
} else {
// Send message to one device
List<Device> userDevices = DeviceStore.findDevicesByGPlusId(target);
if (userDevices == null || userDevices.isEmpty()) {
send(resp, 404, "User not found");
} else {
int resultCount = userDevices.size();
LOG.info("Selected " + resultCount + " devices");
sender.multicastSend(userDevices, action, squelch, payload);
send(resp, 200, "Message queued: " + resultCount + " devices");
}
}
}
private String readBody(HttpServletRequest req) throws IOException {
ServletInputStream inputStream = req.getInputStream();
java.util.Scanner s = new java.util.Scanner(inputStream).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
private static void send(HttpServletResponse resp, int status, String body)
throws IOException {
if (status >= 400) {
LOG.warning(body);
} else {
LOG.info(body);
}
// Prevent frame hijacking
resp.addHeader("X-FRAME-OPTIONS", "DENY");
// Write response data
resp.setContentType("text/plain");
PrintWriter out = resp.getWriter();
out.print(body);
resp.setStatus(status);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.gcm.server.cron;
import com.google.android.apps.iosched.gcm.server.BaseServlet;
import com.google.android.apps.iosched.gcm.server.db.DeviceStore;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class VacuumDbServlet extends BaseServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
resp.addHeader("X-FRAME-OPTIONS", "DENY");
// Print "OK" message
PrintWriter out = resp.getWriter();
out.print("OK");
resp.setStatus(HttpServletResponse.SC_OK);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.gcm.server.db;
import com.google.android.apps.iosched.gcm.server.db.models.MulticastMessage;
import java.util.List;
import java.util.logging.Logger;
import static com.google.android.apps.iosched.gcm.server.db.OfyService.ofy;
/**
* Simple implementation of a data store using standard Java collections.
* <p>
* This class is neither persistent (it will lost the data when the app is
* restarted) nor thread safe.
*/
public final class MessageStore {
private static final Logger LOG = Logger.getLogger(MessageStore.class.getName());
private MessageStore() {
throw new UnsupportedOperationException();
}
/**
* Creates a persistent record with the devices to be notified using a
* multicast message.
*
* @param devices registration ids of the devices
* @param type message type
* @param extraData additional message payload
* @return ID for the persistent record
*/
public static Long createMulticast(List<String> devices,
String type,
String extraData) {
LOG.info("Storing multicast for " + devices.size() + " devices. (type=" + type + ")");
MulticastMessage msg = new MulticastMessage();
msg.setDestinations(devices);
msg.setAction(type);
msg.setExtraData(extraData);
ofy().save().entity(msg).now();
Long id = msg.getId();
LOG.fine("Multicast ID: " + id);
return id;
}
/**
* Gets a persistent record with the devices to be notified using a
* multicast message.
*
* @param id ID for the persistent record
*/
public static MulticastMessage getMulticast(Long id) {
return ofy().load().type(MulticastMessage.class).id(id).get();
}
/**
* Updates a persistent record with the devices to be notified using a
* multicast message.
*
* @param id ID for the persistent record.
* @param devices new list of registration ids of the devices.
*/
public static void updateMulticast(Long id, List<String> devices) {
MulticastMessage msg = ofy().load().type(MulticastMessage.class).id(id).get();
if (msg == null) {
LOG.severe("No entity for multicast ID: " + id);
return;
}
msg.setDestinations(devices);
ofy().save().entity(msg);
}
/**
* Deletes a persistent record with the devices to be notified using a
* multicast message.
*
* @param id ID for the persistent record.
*/
public static void deleteMulticast(Long id) {
ofy().delete().type(MulticastMessage.class).id(id);
}
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* 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 com.google.android.apps.iosched.gcm.server.db;
import com.google.android.apps.iosched.gcm.server.db.models.Device;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import java.util.List;
import java.util.logging.Logger;
import static com.google.android.apps.iosched.gcm.server.db.OfyService.ofy;
public class DeviceStore {
private static final Logger LOG = Logger.getLogger(DeviceStore.class.getName());
/**
* Registers a device.
*
* @param gcmId device's registration id.
*/
public static void register(String gcmId, String gPlusId) {
LOG.info("Registering device.\nG+ ID: " + gPlusId + "\nGCM ID: " + gcmId);
Device oldDevice = findDeviceByGcmId(gcmId);
if (oldDevice == null) {
// Existing device not found (as expected)
Device newDevice = new Device();
newDevice.setGcmId(gcmId);
newDevice.setGPlusId(gPlusId);
ofy().save().entity(newDevice);
} else {
// Existing device found
LOG.warning(gcmId + " is already registered");
if (!gPlusId.equals(oldDevice.getGPlusId())) {
LOG.info("gPlusId has changed from '" + oldDevice.getGPlusId() + "' to '"
+ gPlusId + "'");
oldDevice.setGPlusId(gPlusId);
ofy().save().entity(oldDevice);
}
}
}
/**
* Unregisters a device.
*
* @param gcmId device's registration id.
*/
public static void unregister(String gcmId) {
Device device = findDeviceByGcmId(gcmId);
if (device == null) {
LOG.warning("Device " + gcmId + " already unregistered");
return;
}
LOG.info("Unregistering " + gcmId);
ofy().delete().entity(device);
}
/**
* Updates the registration id of a device.
*/
public static void updateRegistration(String oldGcmId, String newGcmId) {
LOG.info("Updating " + oldGcmId + " to " + newGcmId);
Device oldDevice = findDeviceByGcmId(oldGcmId);
if (oldDevice == null) {
LOG.warning("No device for registration id " + oldGcmId);
return;
}
// Device exists. Since we use the GCM key as the (immutable) primary key,
// we must create a new entity.
Device newDevice = new Device();
newDevice.setGcmId(newGcmId);
newDevice.setGPlusId(oldDevice.getGPlusId());
ofy().save().entity(newDevice);
ofy().delete().entity(oldDevice);
}
/**
* Gets registered device count.
*/
public static int getDeviceCount() {
return ofy().load().type(Device.class).count();
}
public static List<Device> getAllDevices() {
return ofy().load().type(Device.class).list();
}
public static Device findDeviceByGcmId(String regId) {
return ofy().load().type(Device.class).id(regId).get();
}
public static List<Device> findDevicesByGPlusId(String target) {
return ofy().load().type(Device.class).filter("gPlusId", target).list();
}
} | Java |
/*
* Copyright 2013 Google Inc.
*
* 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 com.google.android.apps.iosched.gcm.server.db.models;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Index;
@Entity
public class Device {
@Id private String gcmId;
@Index private String gPlusId;
public String getGcmId() {
return gcmId;
}
public void setGcmId(String gcmId) {
this.gcmId = gcmId;
}
public String getGPlusId () {
return gPlusId;
}
public void setGPlusId(String gPlusId) {
this.gPlusId = gPlusId;
}
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* 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 com.google.android.apps.iosched.gcm.server.db.models;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import java.util.List;
@Entity
public class MulticastMessage {
@Id private Long id;
private String action;
private String extraData;
private List<String> destinations;
public Key<MulticastMessage> getKey() {
return Key.create(MulticastMessage.class, id);
}
public Long getId() {
return id;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getExtraData() {
return extraData;
}
public void setExtraData(String extraData) {
this.extraData = extraData;
}
public List<String> getDestinations() {
return destinations;
}
public void setDestinations(List<String> destinations) {
this.destinations = destinations;
}
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* 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 com.google.android.apps.iosched.gcm.server.db;
import com.google.android.apps.iosched.gcm.server.db.models.Device;
import com.google.android.apps.iosched.gcm.server.db.models.MulticastMessage;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyFactory;
import com.googlecode.objectify.ObjectifyService;
/** Static initializer for Objectify ORM service.
*
* <p>To use this class: com.google.android.apps.iosched.gcm.server.db.OfyService.ofy;
*
* <p>This is responsible for registering model classes with Objectify before any references
* access to the ObjectifyService takes place. All models *must* be registered here, as Objectify
* doesn't do classpath scanning (by design).
*/
public class OfyService {
static {
factory().register(Device.class);
factory().register(MulticastMessage.class);
}
public static Objectify ofy() {
return ObjectifyService.ofy();
}
public static ObjectifyFactory factory() {
return ObjectifyService.factory();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* 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 com.google.android.apps.iosched.gcm.server.db;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.DatastoreService;
/**
* Context initializer that loads the API key from a
* {@value #PATH} file located in the classpath (typically under
* {@code WEB-INF/classes}).
*/
public class ApiKeyInitializer implements ServletContextListener {
public static final String API_KEY = "<ENTER_YOUR_KEY>";
public static final String ATTRIBUTE_ACCESS_KEY = "apiKey";
private static final String ENTITY_KIND = "Settings";
private static final String ENTITY_KEY = "MyKey";
private static final String ACCESS_KEY_FIELD = "ApiKey";
private final Logger mLogger = Logger.getLogger(getClass().getName());
@Override
public void contextInitialized(ServletContextEvent event) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY);
Entity entity;
try {
entity = datastore.get(key);
} catch(EntityNotFoundException e) {
entity = new Entity(key);
// NOTE: it's not possible to change entities in the local server, so
// it will be necessary to hardcode the API key below if you are running
// it locally.
entity.setProperty(ACCESS_KEY_FIELD,
API_KEY);
datastore.put(entity);
mLogger.severe("Created fake key. Please go to App Engine admin "
+ "console, change its value to your API Key (the entity "
+ "type is '" + ENTITY_KIND + "' and its field to be changed is '"
+ ACCESS_KEY_FIELD + "'), then restart the server!");
}
String accessKey = (String) entity.getProperty(ACCESS_KEY_FIELD);
event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, accessKey);
}
/**
* Gets the access key.
*/
protected String getKey() {
com.google.appengine.api.datastore.DatastoreService datastore = DatastoreServiceFactory
.getDatastoreService();
Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY);
String apiKey = "";
try {
Entity entity = datastore.get(key);
apiKey = (String) entity.getProperty(ACCESS_KEY_FIELD);
} catch (EntityNotFoundException e) {
mLogger.severe("Exception will retrieving the API Key"
+ e.toString());
}
return apiKey;
}
@Override
public void contextDestroyed(ServletContextEvent event) {
}
}
| Java |
package com.joshclemm.android.tutorial;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.location.Location;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Projection;
/**
* Fixes bug with some phone's location overlay class (ie Droid X).
* Essentially, it attempts to use the default MyLocationOverlay class,
* but if it fails, we override the drawMyLocation method to provide
* an icon and accuracy circle to mimic showing user's location. Right
* now the icon is a static image. If you want to have it animate, modify
* the drawMyLocation method.
*/
public class FixedMyLocationOverlay extends MyLocationOverlay {
private boolean bugged = false;
private Drawable drawable;
private Paint accuracyPaint;
private Point center;
private Point left;
private int width;
private int height;
public FixedMyLocationOverlay(Context context, MapView mapView) {
super(context, mapView);
}
@Override
protected void drawMyLocation(Canvas canvas, MapView mapView,
Location lastFix, GeoPoint myLocation, long when) {
if(!bugged) {
try {
super.drawMyLocation(canvas, mapView, lastFix, myLocation, when);
} catch (Exception e) {
// we found a buggy phone, draw the location icons ourselves
bugged = true;
}
}
if(bugged) {
if(drawable == null) {
accuracyPaint = new Paint();
accuracyPaint.setAntiAlias(true);
accuracyPaint.setStrokeWidth(2.0f);
drawable = mapView.getContext().getResources().getDrawable(R.drawable.ic_maps_indicator_current_position);
width = drawable.getIntrinsicWidth();
height = drawable.getIntrinsicHeight();
center = new Point();
left = new Point();
}
Projection projection = mapView.getProjection();
double latitude = lastFix.getLatitude();
double longitude = lastFix.getLongitude();
float accuracy = lastFix.getAccuracy();
float[] result = new float[1];
Location.distanceBetween(latitude, longitude, latitude, longitude + 1, result);
float longitudeLineDistance = result[0];
GeoPoint leftGeo = new GeoPoint((int)(latitude*1e6), (int)((longitude-accuracy/longitudeLineDistance)*1e6));
projection.toPixels(leftGeo, left);
projection.toPixels(myLocation, center);
int radius = center.x - left.x;
accuracyPaint.setColor(0xff6666ff);
accuracyPaint.setStyle(Style.STROKE);
canvas.drawCircle(center.x, center.y, radius, accuracyPaint);
accuracyPaint.setColor(0x186666ff);
accuracyPaint.setStyle(Style.FILL);
canvas.drawCircle(center.x, center.y, radius, accuracyPaint);
drawable.setBounds(center.x - width/2, center.y - height/2, center.x + width/2, center.y + height/2);
drawable.draw(canvas);
}
}
}
| Java |
package com.joshclemm.android.tutorial;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
public class MyMapLocationActivity extends MapActivity {
private MapView mapView;
private MyLocationOverlay myLocationOverlay;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// main.xml contains a MapView
setContentView(R.layout.main);
// extract MapView from layout
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
// create an overlay that shows our current location
myLocationOverlay = new FixedMyLocationOverlay(this, mapView);
// add this overlay to the MapView and refresh it
mapView.getOverlays().add(myLocationOverlay);
mapView.postInvalidate();
// call convenience method that zooms map on our location
zoomToMyLocation();
}
@Override
protected void onResume() {
super.onResume();
// when our activity resumes, we want to register for location updates
myLocationOverlay.enableMyLocation();
}
@Override
protected void onPause() {
super.onPause();
// when our activity pauses, we want to remove listening for location updates
myLocationOverlay.disableMyLocation();
}
/**
* This method zooms to the user's location with a zoom level of 10.
*/
private void zoomToMyLocation() {
GeoPoint myLocationGeoPoint = myLocationOverlay.getMyLocation();
if(myLocationGeoPoint != null) {
mapView.getController().animateTo(myLocationGeoPoint);
mapView.getController().setZoom(10);
}
else {
Toast.makeText(this, "Cannot determine location", Toast.LENGTH_SHORT).show();
}
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
} | Java |
/*
* Copyright (C) 2009 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 com.android.spritemethodtest;
import android.graphics.Bitmap;
import android.graphics.Canvas;
/**
* The Canvas version of a sprite. This class keeps a pointer to a bitmap
* and draws it at the Sprite's current location.
*/
public class CanvasSprite extends Renderable {
private Bitmap mBitmap;
public CanvasSprite(Bitmap bitmap) {
mBitmap = bitmap;
}
public void draw(Canvas canvas) {
// The Canvas system uses a screen-space coordinate system, that is,
// 0,0 is the top-left point of the canvas. But in order to align
// with OpenGL's coordinate space (which places 0,0 and the lower-left),
// for this test I flip the y coordinate.
canvas.drawBitmap(mBitmap, x, canvas.getHeight() - (y + height), null);
}
}
| Java |
/*
* Copyright (C) 2009 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 com.android.spritemethodtest;
import android.os.SystemClock;
/**
* Implements a simple runtime profiler. The profiler records start and stop
* times for several different types of profiles and can then return min, max
* and average execution times per type. Profile types are independent and may
* be nested in calling code. This object is a singleton for convenience.
*/
public class ProfileRecorder {
// A type for recording actual draw command time.
public static final int PROFILE_DRAW = 0;
// A type for recording the time it takes to display the scene.
public static final int PROFILE_PAGE_FLIP = 1;
// A type for recording the time it takes to run a single simulation step.
public static final int PROFILE_SIM = 2;
// A type for recording the total amount of time spent rendering a frame.
public static final int PROFILE_FRAME = 3;
private static final int PROFILE_COUNT = PROFILE_FRAME + 1;
private ProfileRecord[] mProfiles;
private int mFrameCount;
public static ProfileRecorder sSingleton = new ProfileRecorder();
public ProfileRecorder() {
mProfiles = new ProfileRecord[PROFILE_COUNT];
for (int x = 0; x < PROFILE_COUNT; x++) {
mProfiles[x] = new ProfileRecord();
}
}
/** Starts recording execution time for a specific profile type.*/
public void start(int profileType) {
if (profileType < PROFILE_COUNT) {
mProfiles[profileType].start(SystemClock.uptimeMillis());
}
}
/** Stops recording time for this profile type. */
public void stop(int profileType) {
if (profileType < PROFILE_COUNT) {
mProfiles[profileType].stop(SystemClock.uptimeMillis());
}
}
/** Indicates the end of the frame.*/
public void endFrame() {
mFrameCount++;
}
/* Flushes all recorded timings from the profiler. */
public void resetAll() {
for (int x = 0; x < PROFILE_COUNT; x++) {
mProfiles[x].reset();
}
mFrameCount = 0;
}
/* Returns the average execution time, in milliseconds, for a given type. */
public long getAverageTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getAverageTime(mFrameCount);
}
return time;
}
/* Returns the minimum execution time in milliseconds for a given type. */
public long getMinTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getMinTime();
}
return time;
}
/* Returns the maximum execution time in milliseconds for a given type. */
public long getMaxTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getMaxTime();
}
return time;
}
/**
* A simple class for storing timing information about a single profile
* type.
*/
protected class ProfileRecord {
private long mStartTime;
private long mTotalTime;
private long mMinTime;
private long mMaxTime;
public void start(long time) {
mStartTime = time;
}
public void stop(long time) {
final long timeDelta = time - mStartTime;
mTotalTime += timeDelta;
if (mMinTime == 0 || timeDelta < mMinTime) {
mMinTime = timeDelta;
}
if (mMaxTime == 0 || timeDelta > mMaxTime) {
mMaxTime = timeDelta;
}
}
public long getAverageTime(int frameCount) {
long time = frameCount > 0 ? mTotalTime / frameCount : 0;
return time;
}
public long getMinTime() {
return mMinTime;
}
public long getMaxTime() {
return mMaxTime;
}
public void startNewProfilePeriod() {
mTotalTime = 0;
}
public void reset() {
mTotalTime = 0;
mStartTime = 0;
mMinTime = 0;
mMaxTime = 0;
}
}
}
| Java |
/*
* Copyright (C) 2009 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 com.android.spritemethodtest;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* Implements a surface view which writes updates to the surface's canvas using
* a separate rendering thread. This class is based heavily on GLSurfaceView.
*/
public class CanvasSurfaceView extends SurfaceView
implements SurfaceHolder.Callback {
private boolean mSizeChanged = true;
private SurfaceHolder mHolder;
private CanvasThread mCanvasThread;
public CanvasSurfaceView(Context context) {
super(context);
init();
}
public CanvasSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
}
public SurfaceHolder getSurfaceHolder() {
return mHolder;
}
/** Sets the user's renderer and kicks off the rendering thread. */
public void setRenderer(Renderer renderer) {
mCanvasThread = new CanvasThread(mHolder, renderer);
mCanvasThread.start();
}
public void surfaceCreated(SurfaceHolder holder) {
mCanvasThread.surfaceCreated();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return
mCanvasThread.surfaceDestroyed();
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Surface size or format has changed. This should not happen in this
// example.
mCanvasThread.onWindowResize(w, h);
}
/** Inform the view that the activity is paused.*/
public void onPause() {
mCanvasThread.onPause();
}
/** Inform the view that the activity is resumed. */
public void onResume() {
mCanvasThread.onResume();
}
/** Inform the view that the window focus has changed. */
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
mCanvasThread.onWindowFocusChanged(hasFocus);
}
/**
* Set an "event" to be run on the rendering thread.
* @param r the runnable to be run on the rendering thread.
*/
public void setEvent(Runnable r) {
mCanvasThread.setEvent(r);
}
/** Clears the runnable event, if any, from the rendering thread. */
public void clearEvent() {
mCanvasThread.clearEvent();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mCanvasThread.requestExitAndWait();
}
protected void stopDrawing() {
mCanvasThread.requestExitAndWait();
}
// ----------------------------------------------------------------------
/** A generic renderer interface. */
public interface Renderer {
/**
* Surface changed size.
* Called after the surface is created and whenever
* the surface size changes. Set your viewport here.
* @param width
* @param height
*/
void sizeChanged(int width, int height);
/**
* Draw the current frame.
* @param canvas The target canvas to draw into.
*/
void drawFrame(Canvas canvas);
}
/**
* A generic Canvas rendering Thread. Delegates to a Renderer instance to do
* the actual drawing.
*/
class CanvasThread extends Thread {
private boolean mDone;
private boolean mPaused;
private boolean mHasFocus;
private boolean mHasSurface;
private boolean mContextLost;
private int mWidth;
private int mHeight;
private Renderer mRenderer;
private Runnable mEvent;
private SurfaceHolder mSurfaceHolder;
CanvasThread(SurfaceHolder holder, Renderer renderer) {
super();
mDone = false;
mWidth = 0;
mHeight = 0;
mRenderer = renderer;
mSurfaceHolder = holder;
setName("CanvasThread");
}
@Override
public void run() {
boolean tellRendererSurfaceChanged = true;
/*
* This is our main activity thread's loop, we go until
* asked to quit.
*/
final ProfileRecorder profiler = ProfileRecorder.sSingleton;
while (!mDone) {
profiler.start(ProfileRecorder.PROFILE_FRAME);
/*
* Update the asynchronous state (window size)
*/
int w;
int h;
synchronized (this) {
// If the user has set a runnable to run in this thread,
// execute it and record the amount of time it takes to
// run.
if (mEvent != null) {
profiler.start(ProfileRecorder.PROFILE_SIM);
mEvent.run();
profiler.stop(ProfileRecorder.PROFILE_SIM);
}
if(needToWait()) {
while (needToWait()) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
if (mDone) {
break;
}
tellRendererSurfaceChanged = mSizeChanged;
w = mWidth;
h = mHeight;
mSizeChanged = false;
}
if (tellRendererSurfaceChanged) {
mRenderer.sizeChanged(w, h);
tellRendererSurfaceChanged = false;
}
if ((w > 0) && (h > 0)) {
// Get ready to draw.
// We record both lockCanvas() and unlockCanvasAndPost()
// as part of "page flip" time because either may block
// until the previous frame is complete.
profiler.start(ProfileRecorder.PROFILE_PAGE_FLIP);
Canvas canvas = mSurfaceHolder.lockCanvas();
profiler.start(ProfileRecorder.PROFILE_PAGE_FLIP);
if (canvas != null) {
// Draw a frame!
profiler.start(ProfileRecorder.PROFILE_DRAW);
mRenderer.drawFrame(canvas);
profiler.stop(ProfileRecorder.PROFILE_DRAW);
profiler.start(ProfileRecorder.PROFILE_PAGE_FLIP);
mSurfaceHolder.unlockCanvasAndPost(canvas);
profiler.stop(ProfileRecorder.PROFILE_PAGE_FLIP);
}
}
profiler.stop(ProfileRecorder.PROFILE_FRAME);
profiler.endFrame();
}
}
private boolean needToWait() {
return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost)
&& (! mDone);
}
public void surfaceCreated() {
synchronized(this) {
mHasSurface = true;
mContextLost = false;
notify();
}
}
public void surfaceDestroyed() {
synchronized(this) {
mHasSurface = false;
notify();
}
}
public void onPause() {
synchronized (this) {
mPaused = true;
}
}
public void onResume() {
synchronized (this) {
mPaused = false;
notify();
}
}
public void onWindowFocusChanged(boolean hasFocus) {
synchronized (this) {
mHasFocus = hasFocus;
if (mHasFocus == true) {
notify();
}
}
}
public void onWindowResize(int w, int h) {
synchronized (this) {
mWidth = w;
mHeight = h;
mSizeChanged = true;
}
}
public void requestExitAndWait() {
// don't call this from CanvasThread thread or it is a guaranteed
// deadlock!
synchronized(this) {
mDone = true;
notify();
}
try {
join();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
/**
* Queue an "event" to be run on the rendering thread.
* @param r the runnable to be run on the rendering thread.
*/
public void setEvent(Runnable r) {
synchronized(this) {
mEvent = r;
}
}
public void clearEvent() {
synchronized(this) {
mEvent = null;
}
}
}
}
| Java |
/*
* Copyright (C) 2009 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 com.android.spritemethodtest;
/**
* Base class defining the core set of information necessary to render (and move
* an object on the screen. This is an abstract type and must be derived to
* add methods to actually draw (see CanvasSprite and GLSprite).
*/
public abstract class Renderable {
// Position.
public float x;
public float y;
public float z;
// Velocity.
public float velocityX;
public float velocityY;
public float velocityZ;
// Size.
public float width;
public float height;
}
| Java |
/*
* Copyright (C) 2009 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 com.android.spritemethodtest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
/**
* Activity for testing OpenGL ES drawing speed. This activity sets up sprites
* and passes them off to an OpenGLSurfaceView for rendering and movement.
*/
public class OpenGLTestActivity extends Activity {
private final static int SPRITE_WIDTH = 64;
private final static int SPRITE_HEIGHT = 64;
private GLSurfaceView mGLSurfaceView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGLSurfaceView = new GLSurfaceView(this);
SimpleGLRenderer spriteRenderer = new SimpleGLRenderer(this);
// Clear out any old profile results.
ProfileRecorder.sSingleton.resetAll();
final Intent callingIntent = getIntent();
// Allocate our sprites and add them to an array.
final int robotCount = callingIntent.getIntExtra("spriteCount", 10);
final boolean animate = callingIntent.getBooleanExtra("animate", true);
final boolean useVerts =
callingIntent.getBooleanExtra("useVerts", false);
final boolean useHardwareBuffers =
callingIntent.getBooleanExtra("useHardwareBuffers", false);
// Allocate space for the robot sprites + one background sprite.
GLSprite[] spriteArray = new GLSprite[robotCount + 1];
// We need to know the width and height of the display pretty soon,
// so grab the information now.
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
GLSprite background = new GLSprite(R.drawable.background);
BitmapDrawable backgroundImage = (BitmapDrawable)getResources().getDrawable(R.drawable.background);
Bitmap backgoundBitmap = backgroundImage.getBitmap();
background.width = backgoundBitmap.getWidth();
background.height = backgoundBitmap.getHeight();
if (useVerts) {
// Setup the background grid. This is just a quad.
Grid backgroundGrid = new Grid(2, 2, false);
backgroundGrid.set(0, 0, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, null);
backgroundGrid.set(1, 0, background.width, 0.0f, 0.0f, 1.0f, 1.0f, null);
backgroundGrid.set(0, 1, 0.0f, background.height, 0.0f, 0.0f, 0.0f, null);
backgroundGrid.set(1, 1, background.width, background.height, 0.0f,
1.0f, 0.0f, null );
background.setGrid(backgroundGrid);
}
spriteArray[0] = background;
Grid spriteGrid = null;
if (useVerts) {
// Setup a quad for the sprites to use. All sprites will use the
// same sprite grid intance.
spriteGrid = new Grid(2, 2, false);
spriteGrid.set(0, 0, 0.0f, 0.0f, 0.0f, 0.0f , 1.0f, null);
spriteGrid.set(1, 0, SPRITE_WIDTH, 0.0f, 0.0f, 1.0f, 1.0f, null);
spriteGrid.set(0, 1, 0.0f, SPRITE_HEIGHT, 0.0f, 0.0f, 0.0f, null);
spriteGrid.set(1, 1, SPRITE_WIDTH, SPRITE_HEIGHT, 0.0f, 1.0f, 0.0f, null);
}
// This list of things to move. It points to the same content as the
// sprite list except for the background.
Renderable[] renderableArray = new Renderable[robotCount];
final int robotBucketSize = robotCount / 3;
for (int x = 0; x < robotCount; x++) {
GLSprite robot;
// Our robots come in three flavors. Split them up accordingly.
if (x < robotBucketSize) {
robot = new GLSprite(R.drawable.skate1);
} else if (x < robotBucketSize * 2) {
robot = new GLSprite(R.drawable.skate2);
} else {
robot = new GLSprite(R.drawable.skate3);
}
robot.width = SPRITE_WIDTH;
robot.height = SPRITE_HEIGHT;
// Pick a random location for this sprite.
robot.x = (float)(Math.random() * dm.widthPixels);
robot.y = (float)(Math.random() * dm.heightPixels);
// All sprites can reuse the same grid. If we're running the
// DrawTexture extension test, this is null.
robot.setGrid(spriteGrid);
// Add this robot to the spriteArray so it gets drawn and to the
// renderableArray so that it gets moved.
spriteArray[x + 1] = robot;
renderableArray[x] = robot;
}
// Now's a good time to run the GC. Since we won't do any explicit
// allocation during the test, the GC should stay dormant and not
// influence our results.
Runtime r = Runtime.getRuntime();
r.gc();
spriteRenderer.setSprites(spriteArray);
spriteRenderer.setVertMode(useVerts, useHardwareBuffers);
mGLSurfaceView.setRenderer(spriteRenderer);
if (animate) {
Mover simulationRuntime = new Mover();
simulationRuntime.setRenderables(renderableArray);
simulationRuntime.setViewSize(dm.widthPixels, dm.heightPixels);
mGLSurfaceView.setEvent(simulationRuntime);
}
setContentView(mGLSurfaceView);
}
}
| Java |
/*
* Copyright (C) 2009 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 com.android.spritemethodtest;
import android.graphics.Canvas;
import com.android.spritemethodtest.CanvasSurfaceView.Renderer;
/**
* An extremely simple renderer based on the CanvasSurfaceView drawing
* framework. Simply draws a list of sprites to a canvas every frame.
*/
public class SimpleCanvasRenderer implements Renderer {
private CanvasSprite[] mSprites;
public void setSprites(CanvasSprite[] sprites) {
mSprites = sprites;
}
public void drawFrame(Canvas canvas) {
if (mSprites != null) {
for (int x = 0; x < mSprites.length; x++) {
mSprites[x].draw(canvas);
}
}
}
public void sizeChanged(int width, int height) {
}
}
| Java |
/*
* Copyright (C) 2009 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.
*/
// This file was lifted from the APIDemos sample. See:
// http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/index.html
package com.android.spritemethodtest;
import java.util.concurrent.Semaphore;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGL11;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import javax.microedition.khronos.opengles.GL;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* An implementation of SurfaceView that uses the dedicated surface for
* displaying an OpenGL animation. This allows the animation to run in a
* separate thread, without requiring that it be driven by the update mechanism
* of the view hierarchy.
*
* The application-specific rendering code is delegated to a GLView.Renderer
* instance.
*/
public class GLSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
public GLSurfaceView(Context context) {
super(context);
init();
}
public GLSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
}
public SurfaceHolder getSurfaceHolder() {
return mHolder;
}
public void setGLWrapper(GLWrapper glWrapper) {
mGLWrapper = glWrapper;
}
public void setRenderer(Renderer renderer) {
mGLThread = new GLThread(renderer);
mGLThread.start();
}
public void surfaceCreated(SurfaceHolder holder) {
mGLThread.surfaceCreated();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return
mGLThread.surfaceDestroyed();
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Surface size or format has changed. This should not happen in this
// example.
mGLThread.onWindowResize(w, h);
}
/**
* Inform the view that the activity is paused.
*/
public void onPause() {
mGLThread.onPause();
}
/**
* Inform the view that the activity is resumed.
*/
public void onResume() {
mGLThread.onResume();
}
/**
* Inform the view that the window focus has changed.
*/
@Override public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
mGLThread.onWindowFocusChanged(hasFocus);
}
/**
* Set an "event" to be run on the GL rendering thread.
* @param r the runnable to be run on the GL rendering thread.
*/
public void setEvent(Runnable r) {
mGLThread.setEvent(r);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mGLThread.requestExitAndWait();
}
// ----------------------------------------------------------------------
public interface GLWrapper {
GL wrap(GL gl);
}
// ----------------------------------------------------------------------
/**
* A generic renderer interface.
*/
public interface Renderer {
/**
* @return the EGL configuration specification desired by the renderer.
*/
int[] getConfigSpec();
/**
* Surface created.
* Called when the surface is created. Called when the application
* starts, and whenever the GPU is reinitialized. This will
* typically happen when the device awakes after going to sleep.
* Set your textures here.
*/
void surfaceCreated(GL10 gl);
/**
* Called when the rendering thread is about to shut down. This is a
* good place to release OpenGL ES resources (textures, buffers, etc).
* @param gl
*/
void shutdown(GL10 gl);
/**
* Surface changed size.
* Called after the surface is created and whenever
* the OpenGL ES surface size changes. Set your viewport here.
* @param gl
* @param width
* @param height
*/
void sizeChanged(GL10 gl, int width, int height);
/**
* Draw the current frame.
* @param gl
*/
void drawFrame(GL10 gl);
}
/**
* An EGL helper class.
*/
private class EglHelper {
public EglHelper() {
}
/**
* Initialize EGL for a given configuration spec.
* @param configSpec
*/
public void start(int[] configSpec){
/*
* Get an EGL instance
*/
mEgl = (EGL10) EGLContext.getEGL();
/*
* Get to the default display.
*/
mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
/*
* We can now initialize EGL for that display
*/
int[] version = new int[2];
mEgl.eglInitialize(mEglDisplay, version);
EGLConfig[] configs = new EGLConfig[1];
int[] num_config = new int[1];
mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1,
num_config);
mEglConfig = configs[0];
/*
* Create an OpenGL ES context. This must be done only once, an
* OpenGL context is a somewhat heavy object.
*/
mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig,
EGL10.EGL_NO_CONTEXT, null);
mEglSurface = null;
}
/*
* Create and return an OpenGL surface
*/
public GL createSurface(SurfaceHolder holder) {
/*
* The window size has changed, so we need to create a new
* surface.
*/
if (mEglSurface != null) {
/*
* Unbind and destroy the old EGL surface, if
* there is one.
*/
mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
}
/*
* Create an EGL surface we can render into.
*/
mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay,
mEglConfig, holder, null);
/*
* Before we can issue GL commands, we need to make sure
* the context is current and bound to a surface.
*/
mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
mEglContext);
GL gl = mEglContext.getGL();
if (mGLWrapper != null) {
gl = mGLWrapper.wrap(gl);
}
return gl;
}
/**
* Display the current render surface.
* @return false if the context has been lost.
*/
public boolean swap() {
mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
/*
* Always check for EGL_CONTEXT_LOST, which means the context
* and all associated data were lost (For instance because
* the device went to sleep). We need to sleep until we
* get a new surface.
*/
return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST;
}
public void finish() {
if (mEglSurface != null) {
mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_CONTEXT);
mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
mEglSurface = null;
}
if (mEglContext != null) {
mEgl.eglDestroyContext(mEglDisplay, mEglContext);
mEglContext = null;
}
if (mEglDisplay != null) {
mEgl.eglTerminate(mEglDisplay);
mEglDisplay = null;
}
}
EGL10 mEgl;
EGLDisplay mEglDisplay;
EGLSurface mEglSurface;
EGLConfig mEglConfig;
EGLContext mEglContext;
}
/**
* A generic GL Thread. Takes care of initializing EGL and GL. Delegates
* to a Renderer instance to do the actual drawing.
*
*/
class GLThread extends Thread {
GLThread(Renderer renderer) {
super();
mDone = false;
mWidth = 0;
mHeight = 0;
mRenderer = renderer;
setName("GLThread");
}
@Override
public void run() {
/*
* When the android framework launches a second instance of
* an activity, the new instance's onCreate() method may be
* called before the first instance returns from onDestroy().
*
* This semaphore ensures that only one instance at a time
* accesses EGL.
*/
try {
try {
sEglSemaphore.acquire();
} catch (InterruptedException e) {
return;
}
guardedRun();
} catch (InterruptedException e) {
// fall thru and exit normally
} finally {
sEglSemaphore.release();
}
}
private void guardedRun() throws InterruptedException {
mEglHelper = new EglHelper();
/*
* Specify a configuration for our opengl session
* and grab the first configuration that matches is
*/
int[] configSpec = mRenderer.getConfigSpec();
mEglHelper.start(configSpec);
GL10 gl = null;
boolean tellRendererSurfaceCreated = true;
boolean tellRendererSurfaceChanged = true;
/*
* This is our main activity thread's loop, we go until
* asked to quit.
*/
while (!mDone) {
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_FRAME);
/*
* Update the asynchronous state (window size)
*/
int w, h;
boolean changed;
boolean needStart = false;
synchronized (this) {
if (mEvent != null) {
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_SIM);
mEvent.run();
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_SIM);
}
if (mPaused) {
mEglHelper.finish();
needStart = true;
}
if(needToWait()) {
while (needToWait()) {
wait();
}
}
if (mDone) {
break;
}
changed = mSizeChanged;
w = mWidth;
h = mHeight;
mSizeChanged = false;
}
if (needStart) {
mEglHelper.start(configSpec);
tellRendererSurfaceCreated = true;
changed = true;
}
if (changed) {
gl = (GL10) mEglHelper.createSurface(mHolder);
tellRendererSurfaceChanged = true;
}
if (tellRendererSurfaceCreated) {
mRenderer.surfaceCreated(gl);
tellRendererSurfaceCreated = false;
}
if (tellRendererSurfaceChanged) {
mRenderer.sizeChanged(gl, w, h);
tellRendererSurfaceChanged = false;
}
if ((w > 0) && (h > 0)) {
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_DRAW);
/* draw a frame here */
mRenderer.drawFrame(gl);
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_DRAW);
/*
* Once we're done with GL, we need to call swapBuffers()
* to instruct the system to display the rendered frame
*/
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_PAGE_FLIP);
mEglHelper.swap();
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_PAGE_FLIP);
}
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_FRAME);
ProfileRecorder.sSingleton.endFrame();
}
/*
* clean-up everything...
*/
if (gl != null) {
mRenderer.shutdown(gl);
}
mEglHelper.finish();
}
private boolean needToWait() {
return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost)
&& (! mDone);
}
public void surfaceCreated() {
synchronized(this) {
mHasSurface = true;
mContextLost = false;
notify();
}
}
public void surfaceDestroyed() {
synchronized(this) {
mHasSurface = false;
notify();
}
}
public void onPause() {
synchronized (this) {
mPaused = true;
}
}
public void onResume() {
synchronized (this) {
mPaused = false;
notify();
}
}
public void onWindowFocusChanged(boolean hasFocus) {
synchronized (this) {
mHasFocus = hasFocus;
if (mHasFocus == true) {
notify();
}
}
}
public void onWindowResize(int w, int h) {
synchronized (this) {
mWidth = w;
mHeight = h;
mSizeChanged = true;
}
}
public void requestExitAndWait() {
// don't call this from GLThread thread or it is a guaranteed
// deadlock!
synchronized(this) {
mDone = true;
notify();
}
try {
join();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
/**
* Queue an "event" to be run on the GL rendering thread.
* @param r the runnable to be run on the GL rendering thread.
*/
public void setEvent(Runnable r) {
synchronized(this) {
mEvent = r;
}
}
public void clearEvent() {
synchronized(this) {
mEvent = null;
}
}
private boolean mDone;
private boolean mPaused;
private boolean mHasFocus;
private boolean mHasSurface;
private boolean mContextLost;
private int mWidth;
private int mHeight;
private Renderer mRenderer;
private Runnable mEvent;
private EglHelper mEglHelper;
}
private static final Semaphore sEglSemaphore = new Semaphore(1);
private boolean mSizeChanged = true;
private SurfaceHolder mHolder;
private GLThread mGLThread;
private GLWrapper mGLWrapper;
}
| Java |
/*
* Copyright (C) 2008 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 com.android.spritemethodtest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
/**
* Main entry point for the SpriteMethodTest application. This application
* provides a simple interface for testing the relative speed of 2D rendering
* systems available on Android, namely the Canvas system and OpenGL ES. It
* also serves as an example of how SurfaceHolders can be used to create an
* efficient rendering thread for drawing.
*/
public class SpriteMethodTest extends Activity {
private static final int ACTIVITY_TEST = 0;
private static final int RESULTS_DIALOG = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Sets up a click listener for the Run Test button.
Button button;
button = (Button) findViewById(R.id.runTest);
button.setOnClickListener(mRunTestListener);
// Turns on one item by default in our radio groups--as it should be!
RadioGroup group = (RadioGroup)findViewById(R.id.renderMethod);
group.setOnCheckedChangeListener(mMethodChangedListener);
group.check(R.id.methodCanvas);
RadioGroup glSettings = (RadioGroup)findViewById(R.id.GLSettings);
glSettings.check(R.id.settingVerts);
}
/** Passes preferences about the test via its intent. */
protected void initializeIntent(Intent i) {
final CheckBox checkBox = (CheckBox) findViewById(R.id.animateSprites);
final boolean animate = checkBox.isChecked();
final EditText editText = (EditText) findViewById(R.id.spriteCount);
final String spriteCountText = editText.getText().toString();
final int stringCount = Integer.parseInt(spriteCountText);
i.putExtra("animate", animate);
i.putExtra("spriteCount", stringCount);
}
/**
* Responds to a click on the Run Test button by launching a new test
* activity.
*/
View.OnClickListener mRunTestListener = new OnClickListener() {
public void onClick(View v) {
RadioGroup group = (RadioGroup)findViewById(R.id.renderMethod);
Intent i;
if (group.getCheckedRadioButtonId() == R.id.methodCanvas) {
i = new Intent(v.getContext(), CanvasTestActivity.class);
} else {
i = new Intent(v.getContext(), OpenGLTestActivity.class);
RadioGroup glSettings =
(RadioGroup)findViewById(R.id.GLSettings);
if (glSettings.getCheckedRadioButtonId() == R.id.settingVerts) {
i.putExtra("useVerts", true);
} else if (glSettings.getCheckedRadioButtonId()
== R.id.settingVBO) {
i.putExtra("useVerts", true);
i.putExtra("useHardwareBuffers", true);
}
}
initializeIntent(i);
startActivityForResult(i, ACTIVITY_TEST);
}
};
/**
* Enables or disables OpenGL ES-specific settings controls when the render
* method option changes.
*/
RadioGroup.OnCheckedChangeListener mMethodChangedListener
= new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.methodCanvas) {
findViewById(R.id.settingDrawTexture).setEnabled(false);
findViewById(R.id.settingVerts).setEnabled(false);
findViewById(R.id.settingVBO).setEnabled(false);
} else {
findViewById(R.id.settingDrawTexture).setEnabled(true);
findViewById(R.id.settingVerts).setEnabled(true);
findViewById(R.id.settingVBO).setEnabled(true);
}
}
};
/** Creates the test results dialog and fills in a dummy message. */
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
if (id == RESULTS_DIALOG) {
String dummy = "No results yet.";
CharSequence sequence = dummy.subSequence(0, dummy.length() -1);
dialog = new AlertDialog.Builder(this)
.setTitle(R.string.dialog_title)
.setPositiveButton(R.string.dialog_ok, null)
.setMessage(sequence)
.create();
}
return dialog;
}
/**
* Replaces the dummy message in the test results dialog with a string that
* describes the actual test results.
*/
protected void onPrepareDialog (int id, Dialog dialog) {
if (id == RESULTS_DIALOG) {
// Extract final timing information from the profiler.
final ProfileRecorder profiler = ProfileRecorder.sSingleton;
final long frameTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_FRAME);
final long frameMin =
profiler.getMinTime(ProfileRecorder.PROFILE_FRAME);
final long frameMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_FRAME);
final long drawTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_DRAW);
final long drawMin =
profiler.getMinTime(ProfileRecorder.PROFILE_DRAW);
final long drawMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_DRAW);
final long flipTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_PAGE_FLIP);
final long flipMin =
profiler.getMinTime(ProfileRecorder.PROFILE_PAGE_FLIP);
final long flipMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_PAGE_FLIP);
final long simTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_SIM);
final long simMin =
profiler.getMinTime(ProfileRecorder.PROFILE_SIM);
final long simMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_SIM);
final float fps = frameTime > 0 ? 1000.0f / frameTime : 0.0f;
String result = "Frame: " + frameTime + "ms (" + fps + " fps)\n"
+ "\t\tMin: " + frameMin + "ms\t\tMax: " + frameMax + "\n"
+ "Draw: " + drawTime + "ms\n"
+ "\t\tMin: " + drawMin + "ms\t\tMax: " + drawMax + "\n"
+ "Page Flip: " + flipTime + "ms\n"
+ "\t\tMin: " + flipMin + "ms\t\tMax: " + flipMax + "\n"
+ "Sim: " + simTime + "ms\n"
+ "\t\tMin: " + simMin + "ms\t\tMax: " + simMax + "\n";
CharSequence sequence = result.subSequence(0, result.length() -1);
AlertDialog alertDialog = (AlertDialog)dialog;
alertDialog.setMessage(sequence);
}
}
/** Shows the results dialog when the test activity closes. */
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
showDialog(RESULTS_DIALOG);
}
} | Java |
/*
* Copyright (C) 2009 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 com.android.spritemethodtest;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11Ext;
/**
* This is the OpenGL ES version of a sprite. It is more complicated than the
* CanvasSprite class because it can be used in more than one way. This class
* can draw using a grid of verts, a grid of verts stored in VBO objects, or
* using the DrawTexture extension.
*/
public class GLSprite extends Renderable {
// The OpenGL ES texture handle to draw.
private int mTextureName;
// The id of the original resource that mTextureName is based on.
private int mResourceId;
// If drawing with verts or VBO verts, the grid object defining those verts.
private Grid mGrid;
public GLSprite(int resourceId) {
super();
mResourceId = resourceId;
}
public void setTextureName(int name) {
mTextureName = name;
}
public int getTextureName() {
return mTextureName;
}
public void setResourceId(int id) {
mResourceId = id;
}
public int getResourceId() {
return mResourceId;
}
public void setGrid(Grid grid) {
mGrid = grid;
}
public Grid getGrid() {
return mGrid;
}
public void draw(GL10 gl) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureName);
if (mGrid == null) {
// Draw using the DrawTexture extension.
((GL11Ext) gl).glDrawTexfOES(x, y, z, width, height);
} else {
// Draw using verts or VBO verts.
gl.glPushMatrix();
gl.glLoadIdentity();
gl.glTranslatef(
x,
y,
z);
mGrid.draw(gl, true, false);
gl.glPopMatrix();
}
}
}
| Java |
/*
* Copyright (C) 2009 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 com.android.spritemethodtest;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.DisplayMetrics;
/**
* Activity for testing Canvas drawing speed. This activity sets up sprites and
* passes them off to a CanvasSurfaceView for rendering and movement. It is
* very similar to OpenGLTestActivity. Note that Bitmap objects come out of a
* pool and must be explicitly recycled on shutdown. See onDestroy().
*/
public class CanvasTestActivity extends Activity {
private CanvasSurfaceView mCanvasSurfaceView;
// Describes the image format our bitmaps should be converted to.
private static BitmapFactory.Options sBitmapOptions
= new BitmapFactory.Options();
private Bitmap[] mBitmaps;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCanvasSurfaceView = new CanvasSurfaceView(this);
SimpleCanvasRenderer spriteRenderer = new SimpleCanvasRenderer();
// Sets our preferred image format to 16-bit, 565 format.
sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
// Clear out any old profile results.
ProfileRecorder.sSingleton.resetAll();
final Intent callingIntent = getIntent();
// Allocate our sprites and add them to an array.
final int robotCount = callingIntent.getIntExtra("spriteCount", 10);
final boolean animate = callingIntent.getBooleanExtra("animate", true);
// Allocate space for the robot sprites + one background sprite.
CanvasSprite[] spriteArray = new CanvasSprite[robotCount + 1];
mBitmaps = new Bitmap[4];
mBitmaps[0] = loadBitmap(this, R.drawable.background);
mBitmaps[1] = loadBitmap(this, R.drawable.skate1);
mBitmaps[2] = loadBitmap(this, R.drawable.skate2);
mBitmaps[3] = loadBitmap(this, R.drawable.skate3);
// We need to know the width and height of the display pretty soon,
// so grab the information now.
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
// Make the background.
// Note that the background image is larger than the screen,
// so some clipping will occur when it is drawn.
CanvasSprite background = new CanvasSprite(mBitmaps[0]);
background.width = mBitmaps[0].getWidth();
background.height = mBitmaps[0].getHeight();
spriteArray[0] = background;
// This list of things to move. It points to the same content as
// spriteArray except for the background.
Renderable[] renderableArray = new Renderable[robotCount];
final int robotBucketSize = robotCount / 3;
for (int x = 0; x < robotCount; x++) {
CanvasSprite robot;
// Our robots come in three flavors. Split them up accordingly.
if (x < robotBucketSize) {
robot = new CanvasSprite(mBitmaps[1]);
} else if (x < robotBucketSize * 2) {
robot = new CanvasSprite(mBitmaps[2]);
} else {
robot = new CanvasSprite(mBitmaps[3]);
}
robot.width = 64;
robot.height = 64;
// Pick a random location for this sprite.
robot.x = (float)(Math.random() * dm.widthPixels);
robot.y = (float)(Math.random() * dm.heightPixels);
// Add this robot to the spriteArray so it gets drawn and to the
// renderableArray so that it gets moved.
spriteArray[x + 1] = robot;
renderableArray[x] = robot;
}
// Now's a good time to run the GC. Since we won't do any explicit
// allocation during the test, the GC should stay dormant and not
// influence our results.
Runtime r = Runtime.getRuntime();
r.gc();
spriteRenderer.setSprites(spriteArray);
mCanvasSurfaceView.setRenderer(spriteRenderer);
if (animate) {
Mover simulationRuntime = new Mover();
simulationRuntime.setRenderables(renderableArray);
simulationRuntime.setViewSize(dm.widthPixels, dm.heightPixels);
mCanvasSurfaceView.setEvent(simulationRuntime);
}
setContentView(mCanvasSurfaceView);
}
/** Recycles all of the bitmaps loaded in onCreate(). */
@Override
protected void onDestroy() {
super.onDestroy();
mCanvasSurfaceView.clearEvent();
mCanvasSurfaceView.stopDrawing();
for (int x = 0; x < mBitmaps.length; x++) {
mBitmaps[x].recycle();
mBitmaps[x] = null;
}
}
/**
* Loads a bitmap from a resource and converts it to a bitmap. This is
* a much-simplified version of the loadBitmap() that appears in
* SimpleGLRenderer.
* @param context The application context.
* @param resourceId The id of the resource to load.
* @return A bitmap containing the image contents of the resource, or null
* if there was an error.
*/
protected Bitmap loadBitmap(Context context, int resourceId) {
Bitmap bitmap = null;
if (context != null) {
InputStream is = context.getResources().openRawResource(resourceId);
try {
bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions);
} finally {
try {
is.close();
} catch (IOException e) {
// Ignore.
}
}
}
return bitmap;
}
}
| Java |
/*
* Copyright (C) 2009 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 com.android.spritemethodtest;
import android.os.SystemClock;
/**
* A simple runnable that updates the position of each sprite on the screen
* every frame by applying a very simple gravity and bounce simulation. The
* sprites are jumbled with random velocities every once and a while.
*/
public class Mover implements Runnable {
private Renderable[] mRenderables;
private long mLastTime;
private long mLastJumbleTime;
private int mViewWidth;
private int mViewHeight;
static final float COEFFICIENT_OF_RESTITUTION = 0.75f;
static final float SPEED_OF_GRAVITY = 150.0f;
static final long JUMBLE_EVERYTHING_DELAY = 15 * 1000;
static final float MAX_VELOCITY = 8000.0f;
public void run() {
// Perform a single simulation step.
if (mRenderables != null) {
final long time = SystemClock.uptimeMillis();
final long timeDelta = time - mLastTime;
final float timeDeltaSeconds =
mLastTime > 0.0f ? timeDelta / 1000.0f : 0.0f;
mLastTime = time;
// Check to see if it's time to jumble again.
final boolean jumble =
(time - mLastJumbleTime > JUMBLE_EVERYTHING_DELAY);
if (jumble) {
mLastJumbleTime = time;
}
for (int x = 0; x < mRenderables.length; x++) {
Renderable object = mRenderables[x];
// Jumble! Apply random velocities.
if (jumble) {
object.velocityX += (MAX_VELOCITY / 2.0f)
- (float)(Math.random() * MAX_VELOCITY);
object.velocityY += (MAX_VELOCITY / 2.0f)
- (float)(Math.random() * MAX_VELOCITY);
}
// Move.
object.x = object.x + (object.velocityX * timeDeltaSeconds);
object.y = object.y + (object.velocityY * timeDeltaSeconds);
object.z = object.z + (object.velocityZ * timeDeltaSeconds);
// Apply Gravity.
object.velocityY -= SPEED_OF_GRAVITY * timeDeltaSeconds;
// Bounce.
if ((object.x < 0.0f && object.velocityX < 0.0f)
|| (object.x > mViewWidth - object.width
&& object.velocityX > 0.0f)) {
object.velocityX =
-object.velocityX * COEFFICIENT_OF_RESTITUTION;
object.x = Math.max(0.0f,
Math.min(object.x, mViewWidth - object.width));
if (Math.abs(object.velocityX) < 0.1f) {
object.velocityX = 0.0f;
}
}
if ((object.y < 0.0f && object.velocityY < 0.0f)
|| (object.y > mViewHeight - object.height
&& object.velocityY > 0.0f)) {
object.velocityY =
-object.velocityY * COEFFICIENT_OF_RESTITUTION;
object.y = Math.max(0.0f,
Math.min(object.y, mViewHeight - object.height));
if (Math.abs(object.velocityY) < 0.1f) {
object.velocityY = 0.0f;
}
}
}
}
}
public void setRenderables(Renderable[] renderables) {
mRenderables = renderables;
}
public void setViewSize(int width, int height) {
mViewHeight = height;
mViewWidth = width;
}
}
| Java |
/*
* Copyright (C) 2008 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 com.android.spritemethodtest;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;
import android.util.Log;
/**
* An OpenGL ES renderer based on the GLSurfaceView rendering framework. This
* class is responsible for drawing a list of renderables to the screen every
* frame. It also manages loading of textures and (when VBOs are used) the
* allocation of vertex buffer objects.
*/
public class SimpleGLRenderer implements GLSurfaceView.Renderer {
// Specifies the format our textures should be converted to upon load.
private static BitmapFactory.Options sBitmapOptions
= new BitmapFactory.Options();
// An array of things to draw every frame.
private GLSprite[] mSprites;
// Pre-allocated arrays to use at runtime so that allocation during the
// test can be avoided.
private int[] mTextureNameWorkspace;
private int[] mCropWorkspace;
// A reference to the application context.
private Context mContext;
// Determines the use of vertex arrays.
private boolean mUseVerts;
// Determines the use of vertex buffer objects.
private boolean mUseHardwareBuffers;
public SimpleGLRenderer(Context context) {
// Pre-allocate and store these objects so we can use them at runtime
// without allocating memory mid-frame.
mTextureNameWorkspace = new int[1];
mCropWorkspace = new int[4];
// Set our bitmaps to 16-bit, 565 format.
sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
mContext = context;
}
public int[] getConfigSpec() {
// We don't need a depth buffer, and don't care about our
// color depth.
int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_NONE };
return configSpec;
}
public void setSprites(GLSprite[] sprites) {
mSprites = sprites;
}
/**
* Changes the vertex mode used for drawing.
* @param useVerts Specifies whether to use a vertex array. If false, the
* DrawTexture extension is used.
* @param useHardwareBuffers Specifies whether to store vertex arrays in
* main memory or on the graphics card. Ignored if useVerts is false.
*/
public void setVertMode(boolean useVerts, boolean useHardwareBuffers) {
mUseVerts = useVerts;
mUseHardwareBuffers = useVerts ? useHardwareBuffers : false;
}
/** Draws the sprites. */
public void drawFrame(GL10 gl) {
if (mSprites != null) {
gl.glMatrixMode(GL10.GL_MODELVIEW);
if (mUseVerts) {
Grid.beginDrawing(gl, true, false);
}
for (int x = 0; x < mSprites.length; x++) {
mSprites[x].draw(gl);
}
if (mUseVerts) {
Grid.endDrawing(gl);
}
}
}
/* Called when the size of the window changes. */
public void sizeChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
/*
* Set our projection matrix. This doesn't have to be done each time we
* draw, but usually a new projection needs to be set when the viewport
* is resized.
*/
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrthof(0.0f, width, 0.0f, height, 0.0f, 1.0f);
gl.glShadeModel(GL10.GL_FLAT);
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000);
gl.glEnable(GL10.GL_TEXTURE_2D);
}
/**
* Called whenever the surface is created. This happens at startup, and
* may be called again at runtime if the device context is lost (the screen
* goes to sleep, etc). This function must fill the contents of vram with
* texture data and (when using VBOs) hardware vertex arrays.
*/
public void surfaceCreated(GL10 gl) {
/*
* Some one-time OpenGL initialization can be made here probably based
* on features of this particular context
*/
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
gl.glClearColor(0.5f, 0.5f, 0.5f, 1);
gl.glShadeModel(GL10.GL_FLAT);
gl.glDisable(GL10.GL_DEPTH_TEST);
gl.glEnable(GL10.GL_TEXTURE_2D);
/*
* By default, OpenGL enables features that improve quality but reduce
* performance. One might want to tweak that especially on software
* renderer.
*/
gl.glDisable(GL10.GL_DITHER);
gl.glDisable(GL10.GL_LIGHTING);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
if (mSprites != null) {
// If we are using hardware buffers and the screen lost context
// then the buffer indexes that we recorded previously are now
// invalid. Forget them here and recreate them below.
if (mUseHardwareBuffers) {
for (int x = 0; x < mSprites.length; x++) {
// Ditch old buffer indexes.
mSprites[x].getGrid().invalidateHardwareBuffers();
}
}
// Load our texture and set its texture name on all sprites.
// To keep this sample simple we will assume that sprites that share
// the same texture are grouped together in our sprite list. A real
// app would probably have another level of texture management,
// like a texture hash.
int lastLoadedResource = -1;
int lastTextureId = -1;
for (int x = 0; x < mSprites.length; x++) {
int resource = mSprites[x].getResourceId();
if (resource != lastLoadedResource) {
lastTextureId = loadBitmap(mContext, gl, resource);
lastLoadedResource = resource;
}
mSprites[x].setTextureName(lastTextureId);
if (mUseHardwareBuffers) {
Grid currentGrid = mSprites[x].getGrid();
if (!currentGrid.usingHardwareBuffers()) {
currentGrid.generateHardwareBuffers(gl);
}
//mSprites[x].getGrid().generateHardwareBuffers(gl);
}
}
}
}
/**
* Called when the rendering thread shuts down. This is a good place to
* release OpenGL ES resources.
* @param gl
*/
public void shutdown(GL10 gl) {
if (mSprites != null) {
int lastFreedResource = -1;
int[] textureToDelete = new int[1];
for (int x = 0; x < mSprites.length; x++) {
int resource = mSprites[x].getResourceId();
if (resource != lastFreedResource) {
textureToDelete[0] = mSprites[x].getTextureName();
gl.glDeleteTextures(1, textureToDelete, 0);
mSprites[x].setTextureName(0);
}
if (mUseHardwareBuffers) {
mSprites[x].getGrid().releaseHardwareBuffers(gl);
}
}
}
}
/**
* Loads a bitmap into OpenGL and sets up the common parameters for
* 2D texture maps.
*/
protected int loadBitmap(Context context, GL10 gl, int resourceId) {
int textureName = -1;
if (context != null && gl != null) {
gl.glGenTextures(1, mTextureNameWorkspace, 0);
textureName = mTextureNameWorkspace[0];
gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE);
InputStream is = context.getResources().openRawResource(resourceId);
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions);
} finally {
try {
is.close();
} catch (IOException e) {
// Ignore.
}
}
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
mCropWorkspace[0] = 0;
mCropWorkspace[1] = bitmap.getHeight();
mCropWorkspace[2] = bitmap.getWidth();
mCropWorkspace[3] = -bitmap.getHeight();
bitmap.recycle();
((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D,
GL11Ext.GL_TEXTURE_CROP_RECT_OES, mCropWorkspace, 0);
int error = gl.glGetError();
if (error != GL10.GL_NO_ERROR) {
Log.e("SpriteMethodTest", "Texture Load GLError: " + error);
}
}
return textureName;
}
}
| Java |
/*
* Copyright (C) 2009 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 com.android.spritemethodtest;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
/**
* A 2D rectangular mesh. Can be drawn textured or untextured.
* This version is modified from the original Grid.java (found in
* the SpriteText package in the APIDemos Android sample) to support hardware
* vertex buffers.
*/
class Grid {
private FloatBuffer mFloatVertexBuffer;
private FloatBuffer mFloatTexCoordBuffer;
private FloatBuffer mFloatColorBuffer;
private IntBuffer mFixedVertexBuffer;
private IntBuffer mFixedTexCoordBuffer;
private IntBuffer mFixedColorBuffer;
private CharBuffer mIndexBuffer;
private Buffer mVertexBuffer;
private Buffer mTexCoordBuffer;
private Buffer mColorBuffer;
private int mCoordinateSize;
private int mCoordinateType;
private int mW;
private int mH;
private int mIndexCount;
private boolean mUseHardwareBuffers;
private int mVertBufferIndex;
private int mIndexBufferIndex;
private int mTextureCoordBufferIndex;
private int mColorBufferIndex;
public Grid(int vertsAcross, int vertsDown, boolean useFixedPoint) {
if (vertsAcross < 0 || vertsAcross >= 65536) {
throw new IllegalArgumentException("vertsAcross");
}
if (vertsDown < 0 || vertsDown >= 65536) {
throw new IllegalArgumentException("vertsDown");
}
if (vertsAcross * vertsDown >= 65536) {
throw new IllegalArgumentException("vertsAcross * vertsDown >= 65536");
}
mUseHardwareBuffers = false;
mW = vertsAcross;
mH = vertsDown;
int size = vertsAcross * vertsDown;
final int FLOAT_SIZE = 4;
final int FIXED_SIZE = 4;
final int CHAR_SIZE = 2;
if (useFixedPoint) {
mFixedVertexBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 3)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mFixedTexCoordBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 2)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mFixedColorBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 4)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mVertexBuffer = mFixedVertexBuffer;
mTexCoordBuffer = mFixedTexCoordBuffer;
mColorBuffer = mFixedColorBuffer;
mCoordinateSize = FIXED_SIZE;
mCoordinateType = GL10.GL_FIXED;
} else {
mFloatVertexBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 3)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mFloatTexCoordBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mFloatColorBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 4)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mVertexBuffer = mFloatVertexBuffer;
mTexCoordBuffer = mFloatTexCoordBuffer;
mColorBuffer = mFloatColorBuffer;
mCoordinateSize = FLOAT_SIZE;
mCoordinateType = GL10.GL_FLOAT;
}
int quadW = mW - 1;
int quadH = mH - 1;
int quadCount = quadW * quadH;
int indexCount = quadCount * 6;
mIndexCount = indexCount;
mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount)
.order(ByteOrder.nativeOrder()).asCharBuffer();
/*
* Initialize triangle list mesh.
*
* [0]-----[ 1] ...
* | / |
* | / |
* | / |
* [w]-----[w+1] ...
* | |
*
*/
{
int i = 0;
for (int y = 0; y < quadH; y++) {
for (int x = 0; x < quadW; x++) {
char a = (char) (y * mW + x);
char b = (char) (y * mW + x + 1);
char c = (char) ((y + 1) * mW + x);
char d = (char) ((y + 1) * mW + x + 1);
mIndexBuffer.put(i++, a);
mIndexBuffer.put(i++, b);
mIndexBuffer.put(i++, c);
mIndexBuffer.put(i++, b);
mIndexBuffer.put(i++, c);
mIndexBuffer.put(i++, d);
}
}
}
mVertBufferIndex = 0;
}
void set(int i, int j, float x, float y, float z, float u, float v, float[] color) {
if (i < 0 || i >= mW) {
throw new IllegalArgumentException("i");
}
if (j < 0 || j >= mH) {
throw new IllegalArgumentException("j");
}
final int index = mW * j + i;
final int posIndex = index * 3;
final int texIndex = index * 2;
final int colorIndex = index * 4;
if (mCoordinateType == GL10.GL_FLOAT) {
mFloatVertexBuffer.put(posIndex, x);
mFloatVertexBuffer.put(posIndex + 1, y);
mFloatVertexBuffer.put(posIndex + 2, z);
mFloatTexCoordBuffer.put(texIndex, u);
mFloatTexCoordBuffer.put(texIndex + 1, v);
if (color != null) {
mFloatColorBuffer.put(colorIndex, color[0]);
mFloatColorBuffer.put(colorIndex + 1, color[1]);
mFloatColorBuffer.put(colorIndex + 2, color[2]);
mFloatColorBuffer.put(colorIndex + 3, color[3]);
}
} else {
mFixedVertexBuffer.put(posIndex, (int)(x * (1 << 16)));
mFixedVertexBuffer.put(posIndex + 1, (int)(y * (1 << 16)));
mFixedVertexBuffer.put(posIndex + 2, (int)(z * (1 << 16)));
mFixedTexCoordBuffer.put(texIndex, (int)(u * (1 << 16)));
mFixedTexCoordBuffer.put(texIndex + 1, (int)(v * (1 << 16)));
if (color != null) {
mFixedColorBuffer.put(colorIndex, (int)(color[0] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 1, (int)(color[1] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 2, (int)(color[2] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 3, (int)(color[3] * (1 << 16)));
}
}
}
public static void beginDrawing(GL10 gl, boolean useTexture, boolean useColor) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
if (useTexture) {
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glEnable(GL10.GL_TEXTURE_2D);
} else {
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisable(GL10.GL_TEXTURE_2D);
}
if (useColor) {
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
} else {
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
}
}
public void draw(GL10 gl, boolean useTexture, boolean useColor) {
if (!mUseHardwareBuffers) {
gl.glVertexPointer(3, mCoordinateType, 0, mVertexBuffer);
if (useTexture) {
gl.glTexCoordPointer(2, mCoordinateType, 0, mTexCoordBuffer);
}
if (useColor) {
gl.glColorPointer(4, mCoordinateType, 0, mColorBuffer);
}
gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount,
GL10.GL_UNSIGNED_SHORT, mIndexBuffer);
} else {
GL11 gl11 = (GL11)gl;
// draw using hardware buffers
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
gl11.glVertexPointer(3, mCoordinateType, 0, 0);
if (useTexture) {
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTextureCoordBufferIndex);
gl11.glTexCoordPointer(2, mCoordinateType, 0, 0);
}
if (useColor) {
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mColorBufferIndex);
gl11.glColorPointer(4, mCoordinateType, 0, 0);
}
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex);
gl11.glDrawElements(GL11.GL_TRIANGLES, mIndexCount,
GL11.GL_UNSIGNED_SHORT, 0);
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
}
}
public static void endDrawing(GL10 gl) {
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
public boolean usingHardwareBuffers() {
return mUseHardwareBuffers;
}
/**
* When the OpenGL ES device is lost, GL handles become invalidated.
* In that case, we just want to "forget" the old handles (without
* explicitly deleting them) and make new ones.
*/
public void invalidateHardwareBuffers() {
mVertBufferIndex = 0;
mIndexBufferIndex = 0;
mTextureCoordBufferIndex = 0;
mColorBufferIndex = 0;
mUseHardwareBuffers = false;
}
/**
* Deletes the hardware buffers allocated by this object (if any).
*/
public void releaseHardwareBuffers(GL10 gl) {
if (mUseHardwareBuffers) {
if (gl instanceof GL11) {
GL11 gl11 = (GL11)gl;
int[] buffer = new int[1];
buffer[0] = mVertBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mTextureCoordBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mColorBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mIndexBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
}
invalidateHardwareBuffers();
}
}
/**
* Allocates hardware buffers on the graphics card and fills them with
* data if a buffer has not already been previously allocated. Note that
* this function uses the GL_OES_vertex_buffer_object extension, which is
* not guaranteed to be supported on every device.
* @param gl A pointer to the OpenGL ES context.
*/
public void generateHardwareBuffers(GL10 gl) {
if (!mUseHardwareBuffers) {
if (gl instanceof GL11) {
GL11 gl11 = (GL11)gl;
int[] buffer = new int[1];
// Allocate and fill the vertex buffer.
gl11.glGenBuffers(1, buffer, 0);
mVertBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
final int vertexSize = mVertexBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, vertexSize,
mVertexBuffer, GL11.GL_STATIC_DRAW);
// Allocate and fill the texture coordinate buffer.
gl11.glGenBuffers(1, buffer, 0);
mTextureCoordBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER,
mTextureCoordBufferIndex);
final int texCoordSize =
mTexCoordBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, texCoordSize,
mTexCoordBuffer, GL11.GL_STATIC_DRAW);
// Allocate and fill the color buffer.
gl11.glGenBuffers(1, buffer, 0);
mColorBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER,
mColorBufferIndex);
final int colorSize =
mColorBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, colorSize,
mColorBuffer, GL11.GL_STATIC_DRAW);
// Unbind the array buffer.
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
// Allocate and fill the index buffer.
gl11.glGenBuffers(1, buffer, 0);
mIndexBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER,
mIndexBufferIndex);
// A char is 2 bytes.
final int indexSize = mIndexBuffer.capacity() * 2;
gl11.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, indexSize, mIndexBuffer,
GL11.GL_STATIC_DRAW);
// Unbind the element array buffer.
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
mUseHardwareBuffers = true;
assert mVertBufferIndex != 0;
assert mTextureCoordBufferIndex != 0;
assert mIndexBufferIndex != 0;
assert gl11.glGetError() == 0;
}
}
}
// These functions exposed to patch Grid info into native code.
public final int getVertexBuffer() {
return mVertBufferIndex;
}
public final int getTextureBuffer() {
return mTextureCoordBufferIndex;
}
public final int getIndexBuffer() {
return mIndexBufferIndex;
}
public final int getColorBuffer() {
return mColorBufferIndex;
}
public final int getIndexCount() {
return mIndexCount;
}
public boolean getFixedPoint() {
return (mCoordinateType == GL10.GL_FIXED);
}
}
| Java |
/*
* Copyright (C) 2008 Google Inc.
*
* 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 com.google.android.radar;
import com.google.android.maps.GeoPoint;
/**
* Library for some use useful latitude/longitude math
*/
public class GeoUtils {
private static int EARTH_RADIUS_KM = 6371;
public static int MILLION = 1000000;
/**
* Computes the distance in kilometers between two points on Earth.
*
* @param lat1 Latitude of the first point
* @param lon1 Longitude of the first point
* @param lat2 Latitude of the second point
* @param lon2 Longitude of the second point
* @return Distance between the two points in kilometers.
*/
public static double distanceKm(double lat1, double lon1, double lat2, double lon2) {
double lat1Rad = Math.toRadians(lat1);
double lat2Rad = Math.toRadians(lat2);
double deltaLonRad = Math.toRadians(lon2 - lon1);
return Math.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad) * Math.cos(lat2Rad)
* Math.cos(deltaLonRad))
* EARTH_RADIUS_KM;
}
/**
* Computes the distance in kilometers between two points on Earth.
*
* @param p1 First point
* @param p2 Second point
* @return Distance between the two points in kilometers.
*/
public static double distanceKm(GeoPoint p1, GeoPoint p2) {
double lat1 = p1.getLatitudeE6() / (double)MILLION;
double lon1 = p1.getLongitudeE6() / (double)MILLION;
double lat2 = p2.getLatitudeE6() / (double)MILLION;
double lon2 = p2.getLongitudeE6() / (double)MILLION;
return distanceKm(lat1, lon1, lat2, lon2);
}
/**
* Computes the bearing in degrees between two points on Earth.
*
* @param p1 First point
* @param p2 Second point
* @return Bearing between the two points in degrees. A value of 0 means due
* north.
*/
public static double bearing(GeoPoint p1, GeoPoint p2) {
double lat1 = p1.getLatitudeE6() / (double) MILLION;
double lon1 = p1.getLongitudeE6() / (double) MILLION;
double lat2 = p2.getLatitudeE6() / (double) MILLION;
double lon2 = p2.getLongitudeE6() / (double) MILLION;
return bearing(lat1, lon1, lat2, lon2);
}
/**
* Computes the bearing in degrees between two points on Earth.
*
* @param lat1 Latitude of the first point
* @param lon1 Longitude of the first point
* @param lat2 Latitude of the second point
* @param lon2 Longitude of the second point
* @return Bearing between the two points in degrees. A value of 0 means due
* north.
*/
public static double bearing(double lat1, double lon1, double lat2, double lon2) {
double lat1Rad = Math.toRadians(lat1);
double lat2Rad = Math.toRadians(lat2);
double deltaLonRad = Math.toRadians(lon2 - lon1);
double y = Math.sin(deltaLonRad) * Math.cos(lat2Rad);
double x = Math.cos(lat1Rad) * Math.sin(lat2Rad) - Math.sin(lat1Rad) * Math.cos(lat2Rad)
* Math.cos(deltaLonRad);
return radToBearing(Math.atan2(y, x));
}
/**
* Converts an angle in radians to degrees
*/
public static double radToBearing(double rad) {
return (Math.toDegrees(rad) + 360) % 360;
}
} | Java |
/*
* Copyright (C) 2008 Google Inc.
*
* 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 com.google.android.radar;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.SensorListener;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
public class RadarView extends View implements SensorListener, LocationListener {
private static final long RETAIN_GPS_MILLIS = 10000L;
private Paint mGridPaint;
private Paint mErasePaint;
private float mOrientation;
private double mTargetLat;
private double mTargetLon;
private double mMyLocationLat;
private double mMyLocationLon;
private int mLastScale = -1;
private String[] mDistanceScale = new String[4];
private static float KM_PER_METERS = 0.001f;
private static float METERS_PER_KM = 1000f;
/**
* These are the list of choices for the radius of the outer circle on the
* screen when using metric units. All items are in kilometers. This array is
* used to choose the scale of the radar display.
*/
private static double mMetricScaleChoices[] = {
100 * KM_PER_METERS,
200 * KM_PER_METERS,
400 * KM_PER_METERS,
1,
2,
4,
8,
20,
40,
100,
200,
400,
1000,
2000,
4000,
10000,
20000,
40000,
80000 };
/**
* Once the scale is chosen, this array is used to convert the number of
* kilometers on the screen to an integer. (Note that for short distances we
* use meters, so we multiply the distance by {@link #METERS_PER_KM}. (This
* array is for metric measurements.)
*/
private static float mMetricDisplayUnitsPerKm[] = {
METERS_PER_KM,
METERS_PER_KM,
METERS_PER_KM,
METERS_PER_KM,
METERS_PER_KM,
1.0f,
1.0f,
1.0f,
1.0f,
1.0f,
1.0f,
1.0f,
1.0f,
1.0f,
1.0f,
1.0f,
1.0f,
1.0f,
1.0f };
/**
* This array holds the formatting string used to display the distance to
* the target. (This array is for metric measurements.)
*/
private static String mMetricDisplayFormats[] = {
"%.0fm",
"%.0fm",
"%.0fm",
"%.0fm",
"%.0fm",
"%.1fkm",
"%.1fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm" };
/**
* This array holds the formatting string used to display the distance on
* each ring of the radar screen. (This array is for metric measurements.)
*/
private static String mMetricScaleFormats[] = {
"%.0fm",
"%.0fm",
"%.0fm",
"%.0fm",
"%.0fm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm",
"%.0fkm" };
private static float KM_PER_YARDS = 0.0009144f;
private static float KM_PER_MILES = 1.609344f;
private static float YARDS_PER_KM = 1093.6133f;
private static float MILES_PER_KM = 0.621371192f;
/**
* These are the list of choices for the radius of the outer circle on the
* screen when using standard units. All items are in kilometers. This array is
* used to choose the scale of the radar display.
*/
private static double mEnglishScaleChoices[] = {
100 * KM_PER_YARDS,
200 * KM_PER_YARDS,
400 * KM_PER_YARDS,
1000 * KM_PER_YARDS,
1 * KM_PER_MILES,
2 * KM_PER_MILES,
4 * KM_PER_MILES,
8 * KM_PER_MILES,
20 * KM_PER_MILES,
40 * KM_PER_MILES,
100 * KM_PER_MILES,
200 * KM_PER_MILES,
400 * KM_PER_MILES,
1000 * KM_PER_MILES,
2000 * KM_PER_MILES,
4000 * KM_PER_MILES,
10000 * KM_PER_MILES,
20000 * KM_PER_MILES,
40000 * KM_PER_MILES,
80000 * KM_PER_MILES };
/**
* Once the scale is chosen, this array is used to convert the number of
* kilometers on the screen to an integer. (Note that for short distances we
* use meters, so we multiply the distance by {@link #YARDS_PER_KM}. (This
* array is for standard measurements.)
*/
private static float mEnglishDisplayUnitsPerKm[] = {
YARDS_PER_KM,
YARDS_PER_KM,
YARDS_PER_KM,
YARDS_PER_KM,
MILES_PER_KM,
MILES_PER_KM,
MILES_PER_KM,
MILES_PER_KM,
MILES_PER_KM,
MILES_PER_KM,
MILES_PER_KM,
MILES_PER_KM,
MILES_PER_KM,
MILES_PER_KM,
MILES_PER_KM,
MILES_PER_KM,
MILES_PER_KM,
MILES_PER_KM,
MILES_PER_KM,
MILES_PER_KM };
/**
* This array holds the formatting string used to display the distance to
* the target. (This array is for standard measurements.)
*/
private static String mEnglishDisplayFormats[] = {
"%.0fyd",
"%.0fyd",
"%.0fyd",
"%.0fyd",
"%.1fmi",
"%.1fmi",
"%.1fmi",
"%.1fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi" };
/**
* This array holds the formatting string used to display the distance on
* each ring of the radar screen. (This array is for standard measurements.)
*/
private static String mEnglishScaleFormats[] = {
"%.0fyd",
"%.0fyd",
"%.0fyd",
"%.0fyd",
"%.2fmi",
"%.1fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi",
"%.0fmi" };
/**
* True when we have know our own location
*/
private boolean mHaveLocation = false;
/**
* The view that will display the distance text
*/
private TextView mDistanceView;
/**
* Distance to target, in KM
*/
private double mDistance;
/**
* Bearing to target, in degrees
*/
private double mBearing;
/**
* Ratio of the distance to the target to the radius of the outermost ring on the radar screen
*/
private float mDistanceRatio;
/**
* Utility rect for calculating the ring labels
*/
private Rect mTextBounds = new Rect();
/**
* The bitmap used to draw the target
*/
private Bitmap mBlip;
/**
* Used to draw the animated ring that sweeps out from the center
*/
private Paint mSweepPaint0;
/**
* Used to draw the animated ring that sweeps out from the center
*/
private Paint mSweepPaint1;
/**
* Used to draw the animated ring that sweeps out from the center
*/
private Paint mSweepPaint2;
/**
* Time in millis when the most recent sweep began
*/
private long mSweepTime;
/**
* True if the sweep has not yet intersected the blip
*/
private boolean mSweepBefore;
/**
* Time in millis when the sweep last crossed the blip
*/
private long mBlipTime;
/**
* True if the display should use metric units; false if the display should use standard
* units
*/
private boolean mUseMetric;
/**
* Time in millis for the last time GPS reported a location
*/
private long mLastGpsFixTime = 0L;
/**
* The last location reported by the network provider. Use this if we can't get a location from
* GPS
*/
private Location mNetworkLocation;
/**
* True if GPS is reporting a location
*/
private boolean mGpsAvailable;
/**
* True if the network provider is reporting a location
*/
private boolean mNetworkAvailable;
public RadarView(Context context) {
this(context, null);
}
public RadarView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RadarView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Paint used for the rings and ring text
mGridPaint = new Paint();
mGridPaint.setColor(0xFF00FF00);
mGridPaint.setAntiAlias(true);
mGridPaint.setStyle(Style.STROKE);
mGridPaint.setStrokeWidth(1.0f);
mGridPaint.setTextSize(10.0f);
mGridPaint.setTextAlign(Align.CENTER);
// Paint used to erase the rectangle behing the ring text
mErasePaint = new Paint();
mErasePaint.setColor(0xFF191919);
mErasePaint.setStyle(Style.FILL);
// Outer ring of the sweep
mSweepPaint0 = new Paint();
mSweepPaint0.setColor(0xFF33FF33);
mSweepPaint0.setAntiAlias(true);
mSweepPaint0.setStyle(Style.STROKE);
mSweepPaint0.setStrokeWidth(2f);
// Middle ring of the sweep
mSweepPaint1 = new Paint();
mSweepPaint1.setColor(0x7733FF33);
mSweepPaint1.setAntiAlias(true);
mSweepPaint1.setStyle(Style.STROKE);
mSweepPaint1.setStrokeWidth(2f);
// Inner ring of the sweep
mSweepPaint2 = new Paint();
mSweepPaint2.setColor(0x3333FF33);
mSweepPaint2.setAntiAlias(true);
mSweepPaint2.setStyle(Style.STROKE);
mSweepPaint2.setStrokeWidth(2f);
mBlip = ((BitmapDrawable)getResources().getDrawable(R.drawable.blip)).getBitmap();
}
/**
* Sets the target to track on the radar
* @param latE6 Latitude of the target, multiplied by 1,000,000
* @param lonE6 Longitude of the target, multiplied by 1,000,000
*/
public void setTarget(int latE6, int lonE6) {
mTargetLat = latE6 / (double) GeoUtils.MILLION;
mTargetLon = lonE6 / (double) GeoUtils.MILLION;
}
/**
* Sets the view that we will use to report distance
*
* @param t The text view used to report distance
*/
public void setDistanceView(TextView t) {
mDistanceView = t;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int center = getWidth() / 2;
int radius = center - 8;
// Draw the rings
final Paint gridPaint = mGridPaint;
canvas.drawCircle(center, center, radius, gridPaint);
canvas.drawCircle(center, center, radius * 3 / 4, gridPaint);
canvas.drawCircle(center, center, radius >> 1, gridPaint);
canvas.drawCircle(center, center, radius >> 2, gridPaint);
int blipRadius = (int) (mDistanceRatio * radius);
final long now = SystemClock.uptimeMillis();
if (mSweepTime > 0 && mHaveLocation) {
// Draw the sweep. Radius is determined by how long ago it started
long sweepDifference = now - mSweepTime;
if (sweepDifference < 512L) {
int sweepRadius = (int) (((radius + 6) * sweepDifference) >> 9);
canvas.drawCircle(center, center, sweepRadius, mSweepPaint0);
canvas.drawCircle(center, center, sweepRadius - 2, mSweepPaint1);
canvas.drawCircle(center, center, sweepRadius - 4, mSweepPaint2);
// Note when the sweep has passed the blip
boolean before = sweepRadius < blipRadius;
if (!before && mSweepBefore) {
mSweepBefore = false;
mBlipTime = now;
}
} else {
mSweepTime = now + 1000;
mSweepBefore = true;
}
postInvalidate();
}
// Draw horizontal and vertical lines
canvas.drawLine(center, center - (radius >> 2) + 6, center, center - radius - 6, gridPaint);
canvas.drawLine(center, center + (radius >> 2) - 6 , center, center + radius + 6, gridPaint);
canvas.drawLine(center - (radius >> 2) + 6, center, center - radius - 6, center, gridPaint);
canvas.drawLine(center + (radius >> 2) - 6, center, center + radius + 6, center, gridPaint);
// Draw X in the center of the screen
canvas.drawLine(center - 4, center - 4, center + 4, center + 4, gridPaint);
canvas.drawLine(center - 4, center + 4, center + 4, center - 4, gridPaint);
if (mHaveLocation) {
double bearingToTarget = mBearing - mOrientation;
double drawingAngle = Math.toRadians(bearingToTarget) - (Math.PI / 2);
float cos = (float) Math.cos(drawingAngle);
float sin = (float) Math.sin(drawingAngle);
// Draw the text for the rings
final String[] distanceScale = mDistanceScale;
addText(canvas, distanceScale[0], center, center + (radius >> 2));
addText(canvas, distanceScale[1], center, center + (radius >> 1));
addText(canvas, distanceScale[2], center, center + radius * 3 / 4);
addText(canvas, distanceScale[3], center, center + radius);
// Draw the blip. Alpha is based on how long ago the sweep crossed the blip
long blipDifference = now - mBlipTime;
gridPaint.setAlpha(255 - (int)((128 * blipDifference) >> 10));
canvas.drawBitmap(mBlip, center + (cos * blipRadius) - 8 ,
center + (sin * blipRadius) - 8, gridPaint);
gridPaint.setAlpha(255);
}
}
private void addText(Canvas canvas, String str, int x, int y) {
mGridPaint.getTextBounds(str, 0, str.length(), mTextBounds);
mTextBounds.offset(x - (mTextBounds.width() >> 1), y);
mTextBounds.inset(-2, -2);
canvas.drawRect(mTextBounds, mErasePaint);
canvas.drawText(str, x, y, mGridPaint);
}
public void onAccuracyChanged(int sensor, int accuracy) {
}
/**
* Called when we get a new value from the compass
*
* @see android.hardware.SensorListener#onSensorChanged(int, float[])
*/
public void onSensorChanged(int sensor, float[] values) {
mOrientation = values[0];
postInvalidate();
}
/**
* Called when a location provider has a new location to report
*
* @see android.location.LocationListener#onLocationChanged(android.location.Location)
*/
public void onLocationChanged(Location location) {
if (!mHaveLocation) {
mHaveLocation = true;
}
final long now = SystemClock.uptimeMillis();
boolean useLocation = false;
final String provider = location.getProvider();
if (LocationManager.GPS_PROVIDER.equals(provider)) {
// Use GPS if available
mLastGpsFixTime = SystemClock.uptimeMillis();
useLocation = true;
} else if (LocationManager.NETWORK_PROVIDER.equals(provider)) {
// Use network provider if GPS is getting stale
useLocation = now - mLastGpsFixTime > RETAIN_GPS_MILLIS;
if (mNetworkLocation == null) {
mNetworkLocation = new Location(location);
} else {
mNetworkLocation.set(location);
}
mLastGpsFixTime = 0L;
}
if (useLocation) {
mMyLocationLat = location.getLatitude();
mMyLocationLon = location.getLongitude();
mDistance = GeoUtils.distanceKm(mMyLocationLat, mMyLocationLon, mTargetLat,
mTargetLon);
mBearing = GeoUtils.bearing(mMyLocationLat, mMyLocationLon, mTargetLat,
mTargetLon);
updateDistance(mDistance);
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
/**
* Called when a location provider has changed its availability.
*
* @see android.location.LocationListener#onStatusChanged(java.lang.String, int, android.os.Bundle)
*/
public void onStatusChanged(String provider, int status, Bundle extras) {
if (LocationManager.GPS_PROVIDER.equals(provider)) {
switch (status) {
case LocationProvider.AVAILABLE:
mGpsAvailable = true;
break;
case LocationProvider.OUT_OF_SERVICE:
case LocationProvider.TEMPORARILY_UNAVAILABLE:
mGpsAvailable = false;
if (mNetworkLocation != null && mNetworkAvailable) {
// Fallback to network location
mLastGpsFixTime = 0L;
onLocationChanged(mNetworkLocation);
} else {
handleUnknownLocation();
}
break;
}
} else if (LocationManager.NETWORK_PROVIDER.equals(provider)) {
switch (status) {
case LocationProvider.AVAILABLE:
mNetworkAvailable = true;
break;
case LocationProvider.OUT_OF_SERVICE:
case LocationProvider.TEMPORARILY_UNAVAILABLE:
mNetworkAvailable = false;
if (!mGpsAvailable) {
handleUnknownLocation();
}
break;
}
}
}
/**
* Called when we no longer have a valid lcoation.
*/
private void handleUnknownLocation() {
mHaveLocation = false;
mDistanceView.setText(R.string.scanning);
}
/**
* Update state to reflect whether we are using metric or standard units.
*
* @param useMetric True if the display should use metric units
*/
public void setUseMetric(boolean useMetric) {
mUseMetric = useMetric;
mLastScale = -1;
if (mHaveLocation) {
updateDistance(mDistance);
}
invalidate();
}
/**
* Update our state to reflect a new distance to the target. This may require
* choosing a new scale for the radar rings.
*
* @param distanceKm The new distance to the target
*/
private void updateDistance(double distanceKm) {
final double[] scaleChoices;
final float[] displayUnitsPerKm;
final String[] displayFormats;
final String[] scaleFormats;
String distanceStr = null;
if (mUseMetric) {
scaleChoices = mMetricScaleChoices;
displayUnitsPerKm = mMetricDisplayUnitsPerKm;
displayFormats = mMetricDisplayFormats;
scaleFormats = mMetricScaleFormats;
} else {
scaleChoices = mEnglishScaleChoices;
displayUnitsPerKm = mEnglishDisplayUnitsPerKm;
displayFormats = mEnglishDisplayFormats;
scaleFormats = mEnglishScaleFormats;
}
int count = scaleChoices.length;
for (int i = 0; i < count; i++) {
if (distanceKm < scaleChoices[i] || i == (count - 1)) {
String format = displayFormats[i];
double distanceDisplay = distanceKm * displayUnitsPerKm[i];
if (mLastScale != i) {
mLastScale = i;
String scaleFormat = scaleFormats[i];
float scaleDistance = (float) (scaleChoices[i] * displayUnitsPerKm[i]);
mDistanceScale[0] = String.format(scaleFormat, (scaleDistance / 4));
mDistanceScale[1] = String.format(scaleFormat, (scaleDistance / 2));
mDistanceScale[2] = String.format(scaleFormat, (scaleDistance * 3 / 4));
mDistanceScale[3] = String.format(scaleFormat, scaleDistance);
}
mDistanceRatio = (float) (mDistance / scaleChoices[mLastScale]);
distanceStr = String.format(format, distanceDisplay);
break;
}
}
mDistanceView.setText(distanceStr);
}
/**
* Turn on the sweep animation starting with the next draw
*/
public void startSweep() {
mSweepTime = SystemClock.uptimeMillis();
mSweepBefore = true;
}
/**
* Turn off the sweep animation
*/
public void stopSweep() {
mSweepTime = 0L;
}
} | Java |
/*
* Copyright (C) 2008 Google Inc.
*
* 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 com.google.android.radar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.SensorManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.TextView;
/**
* Simple Activity wrapper that hosts a {@link RadarView}
*
*/
public class RadarActivity extends Activity {
private static final int LOCATION_UPDATE_INTERVAL_MILLIS = 1000;
private static final int MENU_STANDARD = Menu.FIRST + 1;
private static final int MENU_METRIC = Menu.FIRST + 2;
private static final String RADAR = "radar";
private static final String PREF_METRIC = "metric";
private SensorManager mSensorManager;
private RadarView mRadar;
private LocationManager mLocationManager;
private SharedPreferences mPrefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.radar);
mRadar = (RadarView) findViewById(R.id.radar);
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// Metric or standard units?
mPrefs = getSharedPreferences(RADAR, MODE_PRIVATE);
boolean useMetric = mPrefs.getBoolean(PREF_METRIC, false);
mRadar.setUseMetric(useMetric);
// Read the target from our intent
Intent i = getIntent();
int latE6 = (int)(i.getFloatExtra("latitude", 0) * GeoUtils.MILLION);
int lonE6 = (int)(i.getFloatExtra("longitude", 0) * GeoUtils.MILLION);
mRadar.setTarget(latE6, lonE6);
mRadar.setDistanceView((TextView) findViewById(R.id.distance));
}
@Override
protected void onResume()
{
super.onResume();
mSensorManager.registerListener(mRadar, SensorManager.SENSOR_ORIENTATION,
SensorManager.SENSOR_DELAY_GAME);
// Start animating the radar screen
mRadar.startSweep();
// Register for location updates
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
LOCATION_UPDATE_INTERVAL_MILLIS, 1, mRadar);
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
LOCATION_UPDATE_INTERVAL_MILLIS, 1, mRadar);
}
@Override
protected void onPause()
{
mSensorManager.unregisterListener(mRadar);
mLocationManager.removeUpdates(mRadar);
// Stop animating the radar screen
mRadar.stopSweep();
super.onStop();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_STANDARD, 0, R.string.menu_standard)
.setIcon(R.drawable.ic_menu_standard)
.setAlphabeticShortcut('A');
menu.add(0, MENU_METRIC, 0, R.string.menu_metric)
.setIcon(R.drawable.ic_menu_metric)
.setAlphabeticShortcut('C');
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_STANDARD: {
setUseMetric(false);
return true;
}
case MENU_METRIC: {
setUseMetric(true);
return true;
}
}
return super.onOptionsItemSelected(item);
}
private void setUseMetric(boolean useMetric) {
SharedPreferences.Editor e = mPrefs.edit();
e.putBoolean(PREF_METRIC, useMetric);
e.commit();
mRadar.setUseMetric(useMetric);
}
} | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.