code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (C) 2010 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.actionbarsherlock.internal.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.view.animation.DecelerateInterpolator; import android.widget.LinearLayout; import android.widget.TextView; import com.actionbarsherlock.R; import com.actionbarsherlock.internal.nineoldandroids.animation.Animator; import com.actionbarsherlock.internal.nineoldandroids.animation.Animator.AnimatorListener; import com.actionbarsherlock.internal.nineoldandroids.animation.AnimatorSet; import com.actionbarsherlock.internal.nineoldandroids.animation.ObjectAnimator; import com.actionbarsherlock.internal.nineoldandroids.view.animation.AnimatorProxy; import com.actionbarsherlock.internal.nineoldandroids.widget.NineLinearLayout; import com.actionbarsherlock.internal.view.menu.ActionMenuPresenter; import com.actionbarsherlock.internal.view.menu.ActionMenuView; import com.actionbarsherlock.internal.view.menu.MenuBuilder; import com.actionbarsherlock.view.ActionMode; /** * @hide */ public class ActionBarContextView extends AbsActionBarView implements AnimatorListener { //UNUSED private static final String TAG = "ActionBarContextView"; private CharSequence mTitle; private CharSequence mSubtitle; private NineLinearLayout mClose; private View mCustomView; private LinearLayout mTitleLayout; private TextView mTitleView; private TextView mSubtitleView; private int mTitleStyleRes; private int mSubtitleStyleRes; private Drawable mSplitBackground; private Animator mCurrentAnimation; private boolean mAnimateInOnLayout; private int mAnimationMode; private static final int ANIMATE_IDLE = 0; private static final int ANIMATE_IN = 1; private static final int ANIMATE_OUT = 2; public ActionBarContextView(Context context) { this(context, null); } public ActionBarContextView(Context context, AttributeSet attrs) { this(context, attrs, R.attr.actionModeStyle); } public ActionBarContextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SherlockActionMode, defStyle, 0); setBackgroundDrawable(a.getDrawable( R.styleable.SherlockActionMode_background)); mTitleStyleRes = a.getResourceId( R.styleable.SherlockActionMode_titleTextStyle, 0); mSubtitleStyleRes = a.getResourceId( R.styleable.SherlockActionMode_subtitleTextStyle, 0); mContentHeight = a.getLayoutDimension( R.styleable.SherlockActionMode_height, 0); mSplitBackground = a.getDrawable( R.styleable.SherlockActionMode_backgroundSplit); a.recycle(); } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mActionMenuPresenter != null) { mActionMenuPresenter.hideOverflowMenu(); mActionMenuPresenter.hideSubMenus(); } } @Override public void setSplitActionBar(boolean split) { if (mSplitActionBar != split) { if (mActionMenuPresenter != null) { // Mode is already active; move everything over and adjust the menu itself. final LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); if (!split) { mMenuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); mMenuView.setBackgroundDrawable(null); final ViewGroup oldParent = (ViewGroup) mMenuView.getParent(); if (oldParent != null) oldParent.removeView(mMenuView); addView(mMenuView, layoutParams); } else { // Allow full screen width in split mode. mActionMenuPresenter.setWidthLimit( getContext().getResources().getDisplayMetrics().widthPixels, true); // No limit to the item count; use whatever will fit. mActionMenuPresenter.setItemLimit(Integer.MAX_VALUE); // Span the whole width layoutParams.width = LayoutParams.MATCH_PARENT; layoutParams.height = mContentHeight; mMenuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); mMenuView.setBackgroundDrawable(mSplitBackground); final ViewGroup oldParent = (ViewGroup) mMenuView.getParent(); if (oldParent != null) oldParent.removeView(mMenuView); mSplitView.addView(mMenuView, layoutParams); } } super.setSplitActionBar(split); } } public void setContentHeight(int height) { mContentHeight = height; } public void setCustomView(View view) { if (mCustomView != null) { removeView(mCustomView); } mCustomView = view; if (mTitleLayout != null) { removeView(mTitleLayout); mTitleLayout = null; } if (view != null) { addView(view); } requestLayout(); } public void setTitle(CharSequence title) { mTitle = title; initTitle(); } public void setSubtitle(CharSequence subtitle) { mSubtitle = subtitle; initTitle(); } public CharSequence getTitle() { return mTitle; } public CharSequence getSubtitle() { return mSubtitle; } private void initTitle() { if (mTitleLayout == null) { LayoutInflater inflater = LayoutInflater.from(getContext()); inflater.inflate(R.layout.abs__action_bar_title_item, this); mTitleLayout = (LinearLayout) getChildAt(getChildCount() - 1); mTitleView = (TextView) mTitleLayout.findViewById(R.id.abs__action_bar_title); mSubtitleView = (TextView) mTitleLayout.findViewById(R.id.abs__action_bar_subtitle); if (mTitleStyleRes != 0) { mTitleView.setTextAppearance(mContext, mTitleStyleRes); } if (mSubtitleStyleRes != 0) { mSubtitleView.setTextAppearance(mContext, mSubtitleStyleRes); } } mTitleView.setText(mTitle); mSubtitleView.setText(mSubtitle); final boolean hasTitle = !TextUtils.isEmpty(mTitle); final boolean hasSubtitle = !TextUtils.isEmpty(mSubtitle); mSubtitleView.setVisibility(hasSubtitle ? VISIBLE : GONE); mTitleLayout.setVisibility(hasTitle || hasSubtitle ? VISIBLE : GONE); if (mTitleLayout.getParent() == null) { addView(mTitleLayout); } } public void initForMode(final ActionMode mode) { if (mClose == null) { LayoutInflater inflater = LayoutInflater.from(mContext); mClose = (NineLinearLayout)inflater.inflate(R.layout.abs__action_mode_close_item, this, false); addView(mClose); } else if (mClose.getParent() == null) { addView(mClose); } View closeButton = mClose.findViewById(R.id.abs__action_mode_close_button); closeButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mode.finish(); } }); final MenuBuilder menu = (MenuBuilder) mode.getMenu(); if (mActionMenuPresenter != null) { mActionMenuPresenter.dismissPopupMenus(); } mActionMenuPresenter = new ActionMenuPresenter(mContext); mActionMenuPresenter.setReserveOverflow(true); final LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); if (!mSplitActionBar) { menu.addMenuPresenter(mActionMenuPresenter); mMenuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); mMenuView.setBackgroundDrawable(null); addView(mMenuView, layoutParams); } else { // Allow full screen width in split mode. mActionMenuPresenter.setWidthLimit( getContext().getResources().getDisplayMetrics().widthPixels, true); // No limit to the item count; use whatever will fit. mActionMenuPresenter.setItemLimit(Integer.MAX_VALUE); // Span the whole width layoutParams.width = LayoutParams.MATCH_PARENT; layoutParams.height = mContentHeight; menu.addMenuPresenter(mActionMenuPresenter); mMenuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); mMenuView.setBackgroundDrawable(mSplitBackground); mSplitView.addView(mMenuView, layoutParams); } mAnimateInOnLayout = true; } public void closeMode() { if (mAnimationMode == ANIMATE_OUT) { // Called again during close; just finish what we were doing. return; } if (mClose == null) { killMode(); return; } finishAnimation(); mAnimationMode = ANIMATE_OUT; mCurrentAnimation = makeOutAnimation(); mCurrentAnimation.start(); } private void finishAnimation() { final Animator a = mCurrentAnimation; if (a != null) { mCurrentAnimation = null; a.end(); } } public void killMode() { finishAnimation(); removeAllViews(); if (mSplitView != null) { mSplitView.removeView(mMenuView); } mCustomView = null; mMenuView = null; mAnimateInOnLayout = false; } @Override public boolean showOverflowMenu() { if (mActionMenuPresenter != null) { return mActionMenuPresenter.showOverflowMenu(); } return false; } @Override public boolean hideOverflowMenu() { if (mActionMenuPresenter != null) { return mActionMenuPresenter.hideOverflowMenu(); } return false; } @Override public boolean isOverflowMenuShowing() { if (mActionMenuPresenter != null) { return mActionMenuPresenter.isOverflowMenuShowing(); } return false; } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { // Used by custom views if they don't supply layout params. Everything else // added to an ActionBarContextView should have them already. return new MarginLayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); } @Override public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { return new MarginLayoutParams(getContext(), attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int widthMode = MeasureSpec.getMode(widthMeasureSpec); if (widthMode != MeasureSpec.EXACTLY) { throw new IllegalStateException(getClass().getSimpleName() + " can only be used " + "with android:layout_width=\"match_parent\" (or fill_parent)"); } final int heightMode = MeasureSpec.getMode(heightMeasureSpec); if (heightMode == MeasureSpec.UNSPECIFIED) { throw new IllegalStateException(getClass().getSimpleName() + " can only be used " + "with android:layout_height=\"wrap_content\""); } final int contentWidth = MeasureSpec.getSize(widthMeasureSpec); int maxHeight = mContentHeight > 0 ? mContentHeight : MeasureSpec.getSize(heightMeasureSpec); final int verticalPadding = getPaddingTop() + getPaddingBottom(); int availableWidth = contentWidth - getPaddingLeft() - getPaddingRight(); final int height = maxHeight - verticalPadding; final int childSpecHeight = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST); if (mClose != null) { availableWidth = measureChildView(mClose, availableWidth, childSpecHeight, 0); MarginLayoutParams lp = (MarginLayoutParams) mClose.getLayoutParams(); availableWidth -= lp.leftMargin + lp.rightMargin; } if (mMenuView != null && mMenuView.getParent() == this) { availableWidth = measureChildView(mMenuView, availableWidth, childSpecHeight, 0); } if (mTitleLayout != null && mCustomView == null) { availableWidth = measureChildView(mTitleLayout, availableWidth, childSpecHeight, 0); } if (mCustomView != null) { ViewGroup.LayoutParams lp = mCustomView.getLayoutParams(); final int customWidthMode = lp.width != LayoutParams.WRAP_CONTENT ? MeasureSpec.EXACTLY : MeasureSpec.AT_MOST; final int customWidth = lp.width >= 0 ? Math.min(lp.width, availableWidth) : availableWidth; final int customHeightMode = lp.height != LayoutParams.WRAP_CONTENT ? MeasureSpec.EXACTLY : MeasureSpec.AT_MOST; final int customHeight = lp.height >= 0 ? Math.min(lp.height, height) : height; mCustomView.measure(MeasureSpec.makeMeasureSpec(customWidth, customWidthMode), MeasureSpec.makeMeasureSpec(customHeight, customHeightMode)); } if (mContentHeight <= 0) { int measuredHeight = 0; final int count = getChildCount(); for (int i = 0; i < count; i++) { View v = getChildAt(i); int paddedViewHeight = v.getMeasuredHeight() + verticalPadding; if (paddedViewHeight > measuredHeight) { measuredHeight = paddedViewHeight; } } setMeasuredDimension(contentWidth, measuredHeight); } else { setMeasuredDimension(contentWidth, maxHeight); } } private Animator makeInAnimation() { mClose.setTranslationX(-mClose.getWidth() - ((MarginLayoutParams) mClose.getLayoutParams()).leftMargin); ObjectAnimator buttonAnimator = ObjectAnimator.ofFloat(mClose, "translationX", 0); buttonAnimator.setDuration(200); buttonAnimator.addListener(this); buttonAnimator.setInterpolator(new DecelerateInterpolator()); AnimatorSet set = new AnimatorSet(); AnimatorSet.Builder b = set.play(buttonAnimator); if (mMenuView != null) { final int count = mMenuView.getChildCount(); if (count > 0) { for (int i = count - 1, j = 0; i >= 0; i--, j++) { AnimatorProxy child = AnimatorProxy.wrap(mMenuView.getChildAt(i)); child.setScaleY(0); ObjectAnimator a = ObjectAnimator.ofFloat(child, "scaleY", 0, 1); a.setDuration(100); a.setStartDelay(j * 70); b.with(a); } } } return set; } private Animator makeOutAnimation() { ObjectAnimator buttonAnimator = ObjectAnimator.ofFloat(mClose, "translationX", -mClose.getWidth() - ((MarginLayoutParams) mClose.getLayoutParams()).leftMargin); buttonAnimator.setDuration(200); buttonAnimator.addListener(this); buttonAnimator.setInterpolator(new DecelerateInterpolator()); AnimatorSet set = new AnimatorSet(); AnimatorSet.Builder b = set.play(buttonAnimator); if (mMenuView != null) { final int count = mMenuView.getChildCount(); if (count > 0) { for (int i = 0; i < 0; i++) { AnimatorProxy child = AnimatorProxy.wrap(mMenuView.getChildAt(i)); child.setScaleY(0); ObjectAnimator a = ObjectAnimator.ofFloat(child, "scaleY", 0); a.setDuration(100); a.setStartDelay(i * 70); b.with(a); } } } return set; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int x = getPaddingLeft(); final int y = getPaddingTop(); final int contentHeight = b - t - getPaddingTop() - getPaddingBottom(); if (mClose != null && mClose.getVisibility() != GONE) { MarginLayoutParams lp = (MarginLayoutParams) mClose.getLayoutParams(); x += lp.leftMargin; x += positionChild(mClose, x, y, contentHeight); x += lp.rightMargin; if (mAnimateInOnLayout) { mAnimationMode = ANIMATE_IN; mCurrentAnimation = makeInAnimation(); mCurrentAnimation.start(); mAnimateInOnLayout = false; } } if (mTitleLayout != null && mCustomView == null) { x += positionChild(mTitleLayout, x, y, contentHeight); } if (mCustomView != null) { x += positionChild(mCustomView, x, y, contentHeight); } x = r - l - getPaddingRight(); if (mMenuView != null) { x -= positionChildInverse(mMenuView, x, y, contentHeight); } } @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { if (mAnimationMode == ANIMATE_OUT) { killMode(); } mAnimationMode = ANIMATE_IDLE; } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } @Override public boolean shouldDelayChildPressedState() { return false; } @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) { // Action mode started //TODO event.setSource(this); event.setClassName(getClass().getName()); event.setPackageName(getContext().getPackageName()); event.setContentDescription(mTitle); } else { //TODO super.onInitializeAccessibilityEvent(event); } } }
Java
/* * Copyright (C) 2006 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.actionbarsherlock.internal.widget; import android.content.Context; import android.database.DataSetObserver; import android.os.Parcelable; import android.os.SystemClock; import android.util.AttributeSet; import android.util.SparseArray; import android.view.ContextMenu; import android.view.SoundEffectConstants; import android.view.View; import android.view.ViewDebug; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.Adapter; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; /** * An AdapterView is a view whose children are determined by an {@link Adapter}. * * <p> * See {@link ListView}, {@link GridView}, {@link Spinner} and * {@link Gallery} for commonly used subclasses of AdapterView. * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For more information about using AdapterView, read the * <a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a> * developer guide.</p></div> */ public abstract class IcsAdapterView<T extends Adapter> extends ViewGroup { /** * The item view type returned by {@link Adapter#getItemViewType(int)} when * the adapter does not want the item's view recycled. */ public static final int ITEM_VIEW_TYPE_IGNORE = -1; /** * The item view type returned by {@link Adapter#getItemViewType(int)} when * the item is a header or footer. */ public static final int ITEM_VIEW_TYPE_HEADER_OR_FOOTER = -2; /** * The position of the first child displayed */ @ViewDebug.ExportedProperty(category = "scrolling") int mFirstPosition = 0; /** * The offset in pixels from the top of the AdapterView to the top * of the view to select during the next layout. */ int mSpecificTop; /** * Position from which to start looking for mSyncRowId */ int mSyncPosition; /** * Row id to look for when data has changed */ long mSyncRowId = INVALID_ROW_ID; /** * Height of the view when mSyncPosition and mSyncRowId where set */ long mSyncHeight; /** * True if we need to sync to mSyncRowId */ boolean mNeedSync = false; /** * Indicates whether to sync based on the selection or position. Possible * values are {@link #SYNC_SELECTED_POSITION} or * {@link #SYNC_FIRST_POSITION}. */ int mSyncMode; /** * Our height after the last layout */ private int mLayoutHeight; /** * Sync based on the selected child */ static final int SYNC_SELECTED_POSITION = 0; /** * Sync based on the first child displayed */ static final int SYNC_FIRST_POSITION = 1; /** * Maximum amount of time to spend in {@link #findSyncPosition()} */ static final int SYNC_MAX_DURATION_MILLIS = 100; /** * Indicates that this view is currently being laid out. */ boolean mInLayout = false; /** * The listener that receives notifications when an item is selected. */ OnItemSelectedListener mOnItemSelectedListener; /** * The listener that receives notifications when an item is clicked. */ OnItemClickListener mOnItemClickListener; /** * The listener that receives notifications when an item is long clicked. */ OnItemLongClickListener mOnItemLongClickListener; /** * True if the data has changed since the last layout */ boolean mDataChanged; /** * The position within the adapter's data set of the item to select * during the next layout. */ @ViewDebug.ExportedProperty(category = "list") int mNextSelectedPosition = INVALID_POSITION; /** * The item id of the item to select during the next layout. */ long mNextSelectedRowId = INVALID_ROW_ID; /** * The position within the adapter's data set of the currently selected item. */ @ViewDebug.ExportedProperty(category = "list") int mSelectedPosition = INVALID_POSITION; /** * The item id of the currently selected item. */ long mSelectedRowId = INVALID_ROW_ID; /** * View to show if there are no items to show. */ private View mEmptyView; /** * The number of items in the current adapter. */ @ViewDebug.ExportedProperty(category = "list") int mItemCount; /** * The number of items in the adapter before a data changed event occurred. */ int mOldItemCount; /** * Represents an invalid position. All valid positions are in the range 0 to 1 less than the * number of items in the current adapter. */ public static final int INVALID_POSITION = -1; /** * Represents an empty or invalid row id */ public static final long INVALID_ROW_ID = Long.MIN_VALUE; /** * The last selected position we used when notifying */ int mOldSelectedPosition = INVALID_POSITION; /** * The id of the last selected position we used when notifying */ long mOldSelectedRowId = INVALID_ROW_ID; /** * Indicates what focusable state is requested when calling setFocusable(). * In addition to this, this view has other criteria for actually * determining the focusable state (such as whether its empty or the text * filter is shown). * * @see #setFocusable(boolean) * @see #checkFocus() */ private boolean mDesiredFocusableState; private boolean mDesiredFocusableInTouchModeState; private SelectionNotifier mSelectionNotifier; /** * When set to true, calls to requestLayout() will not propagate up the parent hierarchy. * This is used to layout the children during a layout pass. */ boolean mBlockLayoutRequests = false; public IcsAdapterView(Context context) { super(context); } public IcsAdapterView(Context context, AttributeSet attrs) { super(context, attrs); } public IcsAdapterView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } /** * Register a callback to be invoked when an item in this AdapterView has * been clicked. * * @param listener The callback that will be invoked. */ public void setOnItemClickListener(OnItemClickListener listener) { mOnItemClickListener = listener; } /** * @return The callback to be invoked with an item in this AdapterView has * been clicked, or null id no callback has been set. */ public final OnItemClickListener getOnItemClickListener() { return mOnItemClickListener; } /** * Call the OnItemClickListener, if it is defined. * * @param view The view within the AdapterView that was clicked. * @param position The position of the view in the adapter. * @param id The row id of the item that was clicked. * @return True if there was an assigned OnItemClickListener that was * called, false otherwise is returned. */ public boolean performItemClick(View view, int position, long id) { if (mOnItemClickListener != null) { playSoundEffect(SoundEffectConstants.CLICK); if (view != null) { view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); } mOnItemClickListener.onItemClick(/*this*/null, view, position, id); return true; } return false; } /** * Interface definition for a callback to be invoked when an item in this * view has been clicked and held. */ public interface OnItemLongClickListener { /** * Callback method to be invoked when an item in this view has been * clicked and held. * * Implementers can call getItemAtPosition(position) if they need to access * the data associated with the selected item. * * @param parent The AbsListView where the click happened * @param view The view within the AbsListView that was clicked * @param position The position of the view in the list * @param id The row id of the item that was clicked * * @return true if the callback consumed the long click, false otherwise */ boolean onItemLongClick(IcsAdapterView<?> parent, View view, int position, long id); } /** * Register a callback to be invoked when an item in this AdapterView has * been clicked and held * * @param listener The callback that will run */ public void setOnItemLongClickListener(OnItemLongClickListener listener) { if (!isLongClickable()) { setLongClickable(true); } mOnItemLongClickListener = listener; } /** * @return The callback to be invoked with an item in this AdapterView has * been clicked and held, or null id no callback as been set. */ public final OnItemLongClickListener getOnItemLongClickListener() { return mOnItemLongClickListener; } /** * Interface definition for a callback to be invoked when * an item in this view has been selected. */ public interface OnItemSelectedListener { /** * <p>Callback method to be invoked when an item in this view has been * selected. This callback is invoked only when the newly selected * position is different from the previously selected position or if * there was no selected item.</p> * * Impelmenters can call getItemAtPosition(position) if they need to access the * data associated with the selected item. * * @param parent The AdapterView where the selection happened * @param view The view within the AdapterView that was clicked * @param position The position of the view in the adapter * @param id The row id of the item that is selected */ void onItemSelected(IcsAdapterView<?> parent, View view, int position, long id); /** * Callback method to be invoked when the selection disappears from this * view. The selection can disappear for instance when touch is activated * or when the adapter becomes empty. * * @param parent The AdapterView that now contains no selected item. */ void onNothingSelected(IcsAdapterView<?> parent); } /** * Register a callback to be invoked when an item in this AdapterView has * been selected. * * @param listener The callback that will run */ public void setOnItemSelectedListener(OnItemSelectedListener listener) { mOnItemSelectedListener = listener; } public final OnItemSelectedListener getOnItemSelectedListener() { return mOnItemSelectedListener; } /** * Extra menu information provided to the * {@link android.view.View.OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo) } * callback when a context menu is brought up for this AdapterView. * */ public static class AdapterContextMenuInfo implements ContextMenu.ContextMenuInfo { public AdapterContextMenuInfo(View targetView, int position, long id) { this.targetView = targetView; this.position = position; this.id = id; } /** * The child view for which the context menu is being displayed. This * will be one of the children of this AdapterView. */ public View targetView; /** * The position in the adapter for which the context menu is being * displayed. */ public int position; /** * The row id of the item for which the context menu is being displayed. */ public long id; } /** * Returns the adapter currently associated with this widget. * * @return The adapter used to provide this view's content. */ public abstract T getAdapter(); /** * Sets the adapter that provides the data and the views to represent the data * in this widget. * * @param adapter The adapter to use to create this view's content. */ public abstract void setAdapter(T adapter); /** * This method is not supported and throws an UnsupportedOperationException when called. * * @param child Ignored. * * @throws UnsupportedOperationException Every time this method is invoked. */ @Override public void addView(View child) { throw new UnsupportedOperationException("addView(View) is not supported in AdapterView"); } /** * This method is not supported and throws an UnsupportedOperationException when called. * * @param child Ignored. * @param index Ignored. * * @throws UnsupportedOperationException Every time this method is invoked. */ @Override public void addView(View child, int index) { throw new UnsupportedOperationException("addView(View, int) is not supported in AdapterView"); } /** * This method is not supported and throws an UnsupportedOperationException when called. * * @param child Ignored. * @param params Ignored. * * @throws UnsupportedOperationException Every time this method is invoked. */ @Override public void addView(View child, LayoutParams params) { throw new UnsupportedOperationException("addView(View, LayoutParams) " + "is not supported in AdapterView"); } /** * This method is not supported and throws an UnsupportedOperationException when called. * * @param child Ignored. * @param index Ignored. * @param params Ignored. * * @throws UnsupportedOperationException Every time this method is invoked. */ @Override public void addView(View child, int index, LayoutParams params) { throw new UnsupportedOperationException("addView(View, int, LayoutParams) " + "is not supported in AdapterView"); } /** * This method is not supported and throws an UnsupportedOperationException when called. * * @param child Ignored. * * @throws UnsupportedOperationException Every time this method is invoked. */ @Override public void removeView(View child) { throw new UnsupportedOperationException("removeView(View) is not supported in AdapterView"); } /** * This method is not supported and throws an UnsupportedOperationException when called. * * @param index Ignored. * * @throws UnsupportedOperationException Every time this method is invoked. */ @Override public void removeViewAt(int index) { throw new UnsupportedOperationException("removeViewAt(int) is not supported in AdapterView"); } /** * This method is not supported and throws an UnsupportedOperationException when called. * * @throws UnsupportedOperationException Every time this method is invoked. */ @Override public void removeAllViews() { throw new UnsupportedOperationException("removeAllViews() is not supported in AdapterView"); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { mLayoutHeight = getHeight(); } /** * Return the position of the currently selected item within the adapter's data set * * @return int Position (starting at 0), or {@link #INVALID_POSITION} if there is nothing selected. */ @ViewDebug.CapturedViewProperty public int getSelectedItemPosition() { return mNextSelectedPosition; } /** * @return The id corresponding to the currently selected item, or {@link #INVALID_ROW_ID} * if nothing is selected. */ @ViewDebug.CapturedViewProperty public long getSelectedItemId() { return mNextSelectedRowId; } /** * @return The view corresponding to the currently selected item, or null * if nothing is selected */ public abstract View getSelectedView(); /** * @return The data corresponding to the currently selected item, or * null if there is nothing selected. */ public Object getSelectedItem() { T adapter = getAdapter(); int selection = getSelectedItemPosition(); if (adapter != null && adapter.getCount() > 0 && selection >= 0) { return adapter.getItem(selection); } else { return null; } } /** * @return The number of items owned by the Adapter associated with this * AdapterView. (This is the number of data items, which may be * larger than the number of visible views.) */ @ViewDebug.CapturedViewProperty public int getCount() { return mItemCount; } /** * Get the position within the adapter's data set for the view, where view is a an adapter item * or a descendant of an adapter item. * * @param view an adapter item, or a descendant of an adapter item. This must be visible in this * AdapterView at the time of the call. * @return the position within the adapter's data set of the view, or {@link #INVALID_POSITION} * if the view does not correspond to a list item (or it is not currently visible). */ public int getPositionForView(View view) { View listItem = view; try { View v; while (!(v = (View) listItem.getParent()).equals(this)) { listItem = v; } } catch (ClassCastException e) { // We made it up to the window without find this list view return INVALID_POSITION; } // Search the children for the list item final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { if (getChildAt(i).equals(listItem)) { return mFirstPosition + i; } } // Child not found! return INVALID_POSITION; } /** * Returns the position within the adapter's data set for the first item * displayed on screen. * * @return The position within the adapter's data set */ public int getFirstVisiblePosition() { return mFirstPosition; } /** * Returns the position within the adapter's data set for the last item * displayed on screen. * * @return The position within the adapter's data set */ public int getLastVisiblePosition() { return mFirstPosition + getChildCount() - 1; } /** * Sets the currently selected item. To support accessibility subclasses that * override this method must invoke the overriden super method first. * * @param position Index (starting at 0) of the data item to be selected. */ public abstract void setSelection(int position); /** * Sets the view to show if the adapter is empty */ public void setEmptyView(View emptyView) { mEmptyView = emptyView; final T adapter = getAdapter(); final boolean empty = ((adapter == null) || adapter.isEmpty()); updateEmptyStatus(empty); } /** * When the current adapter is empty, the AdapterView can display a special view * call the empty view. The empty view is used to provide feedback to the user * that no data is available in this AdapterView. * * @return The view to show if the adapter is empty. */ public View getEmptyView() { return mEmptyView; } /** * Indicates whether this view is in filter mode. Filter mode can for instance * be enabled by a user when typing on the keyboard. * * @return True if the view is in filter mode, false otherwise. */ boolean isInFilterMode() { return false; } @Override public void setFocusable(boolean focusable) { final T adapter = getAdapter(); final boolean empty = adapter == null || adapter.getCount() == 0; mDesiredFocusableState = focusable; if (!focusable) { mDesiredFocusableInTouchModeState = false; } super.setFocusable(focusable && (!empty || isInFilterMode())); } @Override public void setFocusableInTouchMode(boolean focusable) { final T adapter = getAdapter(); final boolean empty = adapter == null || adapter.getCount() == 0; mDesiredFocusableInTouchModeState = focusable; if (focusable) { mDesiredFocusableState = true; } super.setFocusableInTouchMode(focusable && (!empty || isInFilterMode())); } void checkFocus() { final T adapter = getAdapter(); final boolean empty = adapter == null || adapter.getCount() == 0; final boolean focusable = !empty || isInFilterMode(); // The order in which we set focusable in touch mode/focusable may matter // for the client, see View.setFocusableInTouchMode() comments for more // details super.setFocusableInTouchMode(focusable && mDesiredFocusableInTouchModeState); super.setFocusable(focusable && mDesiredFocusableState); if (mEmptyView != null) { updateEmptyStatus((adapter == null) || adapter.isEmpty()); } } /** * Update the status of the list based on the empty parameter. If empty is true and * we have an empty view, display it. In all the other cases, make sure that the listview * is VISIBLE and that the empty view is GONE (if it's not null). */ private void updateEmptyStatus(boolean empty) { if (isInFilterMode()) { empty = false; } if (empty) { if (mEmptyView != null) { mEmptyView.setVisibility(View.VISIBLE); setVisibility(View.GONE); } else { // If the caller just removed our empty view, make sure the list view is visible setVisibility(View.VISIBLE); } // We are now GONE, so pending layouts will not be dispatched. // Force one here to make sure that the state of the list matches // the state of the adapter. if (mDataChanged) { this.onLayout(false, getLeft(), getTop(), getRight(), getBottom()); } } else { if (mEmptyView != null) mEmptyView.setVisibility(View.GONE); setVisibility(View.VISIBLE); } } /** * Gets the data associated with the specified position in the list. * * @param position Which data to get * @return The data associated with the specified position in the list */ public Object getItemAtPosition(int position) { T adapter = getAdapter(); return (adapter == null || position < 0) ? null : adapter.getItem(position); } public long getItemIdAtPosition(int position) { T adapter = getAdapter(); return (adapter == null || position < 0) ? INVALID_ROW_ID : adapter.getItemId(position); } @Override public void setOnClickListener(OnClickListener l) { throw new RuntimeException("Don't call setOnClickListener for an AdapterView. " + "You probably want setOnItemClickListener instead"); } /** * Override to prevent freezing of any views created by the adapter. */ @Override protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { dispatchFreezeSelfOnly(container); } /** * Override to prevent thawing of any views created by the adapter. */ @Override protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { dispatchThawSelfOnly(container); } class AdapterDataSetObserver extends DataSetObserver { private Parcelable mInstanceState = null; @Override public void onChanged() { mDataChanged = true; mOldItemCount = mItemCount; mItemCount = getAdapter().getCount(); // Detect the case where a cursor that was previously invalidated has // been repopulated with new data. if (IcsAdapterView.this.getAdapter().hasStableIds() && mInstanceState != null && mOldItemCount == 0 && mItemCount > 0) { IcsAdapterView.this.onRestoreInstanceState(mInstanceState); mInstanceState = null; } else { rememberSyncState(); } checkFocus(); requestLayout(); } @Override public void onInvalidated() { mDataChanged = true; if (IcsAdapterView.this.getAdapter().hasStableIds()) { // Remember the current state for the case where our hosting activity is being // stopped and later restarted mInstanceState = IcsAdapterView.this.onSaveInstanceState(); } // Data is invalid so we should reset our state mOldItemCount = mItemCount; mItemCount = 0; mSelectedPosition = INVALID_POSITION; mSelectedRowId = INVALID_ROW_ID; mNextSelectedPosition = INVALID_POSITION; mNextSelectedRowId = INVALID_ROW_ID; mNeedSync = false; checkFocus(); requestLayout(); } public void clearSavedState() { mInstanceState = null; } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); removeCallbacks(mSelectionNotifier); } private class SelectionNotifier implements Runnable { public void run() { if (mDataChanged) { // Data has changed between when this SelectionNotifier // was posted and now. We need to wait until the AdapterView // has been synched to the new data. if (getAdapter() != null) { post(this); } } else { fireOnSelected(); } } } void selectionChanged() { if (mOnItemSelectedListener != null) { if (mInLayout || mBlockLayoutRequests) { // If we are in a layout traversal, defer notification // by posting. This ensures that the view tree is // in a consistent state and is able to accomodate // new layout or invalidate requests. if (mSelectionNotifier == null) { mSelectionNotifier = new SelectionNotifier(); } post(mSelectionNotifier); } else { fireOnSelected(); } } // we fire selection events here not in View if (mSelectedPosition != ListView.INVALID_POSITION && isShown() && !isInTouchMode()) { sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); } } private void fireOnSelected() { if (mOnItemSelectedListener == null) return; int selection = this.getSelectedItemPosition(); if (selection >= 0) { View v = getSelectedView(); mOnItemSelectedListener.onItemSelected(this, v, selection, getAdapter().getItemId(selection)); } else { mOnItemSelectedListener.onNothingSelected(this); } } @Override public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { View selectedView = getSelectedView(); if (selectedView != null && selectedView.getVisibility() == VISIBLE && selectedView.dispatchPopulateAccessibilityEvent(event)) { return true; } return false; } @Override public boolean onRequestSendAccessibilityEvent(View child, AccessibilityEvent event) { if (super.onRequestSendAccessibilityEvent(child, event)) { // Add a record for ourselves as well. AccessibilityEvent record = AccessibilityEvent.obtain(); onInitializeAccessibilityEvent(record); // Populate with the text of the requesting child. child.dispatchPopulateAccessibilityEvent(record); event.appendRecord(record); return true; } return false; } @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setScrollable(isScrollableForAccessibility()); View selectedView = getSelectedView(); if (selectedView != null) { info.setEnabled(selectedView.isEnabled()); } } @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); event.setScrollable(isScrollableForAccessibility()); View selectedView = getSelectedView(); if (selectedView != null) { event.setEnabled(selectedView.isEnabled()); } event.setCurrentItemIndex(getSelectedItemPosition()); event.setFromIndex(getFirstVisiblePosition()); event.setToIndex(getLastVisiblePosition()); event.setItemCount(getCount()); } private boolean isScrollableForAccessibility() { T adapter = getAdapter(); if (adapter != null) { final int itemCount = adapter.getCount(); return itemCount > 0 && (getFirstVisiblePosition() > 0 || getLastVisiblePosition() < itemCount - 1); } return false; } @Override protected boolean canAnimate() { return super.canAnimate() && mItemCount > 0; } void handleDataChanged() { final int count = mItemCount; boolean found = false; if (count > 0) { int newPos; // Find the row we are supposed to sync to if (mNeedSync) { // Update this first, since setNextSelectedPositionInt inspects // it mNeedSync = false; // See if we can find a position in the new data with the same // id as the old selection newPos = findSyncPosition(); if (newPos >= 0) { // Verify that new selection is selectable int selectablePos = lookForSelectablePosition(newPos, true); if (selectablePos == newPos) { // Same row id is selected setNextSelectedPositionInt(newPos); found = true; } } } if (!found) { // Try to use the same position if we can't find matching data newPos = getSelectedItemPosition(); // Pin position to the available range if (newPos >= count) { newPos = count - 1; } if (newPos < 0) { newPos = 0; } // Make sure we select something selectable -- first look down int selectablePos = lookForSelectablePosition(newPos, true); if (selectablePos < 0) { // Looking down didn't work -- try looking up selectablePos = lookForSelectablePosition(newPos, false); } if (selectablePos >= 0) { setNextSelectedPositionInt(selectablePos); checkSelectionChanged(); found = true; } } } if (!found) { // Nothing is selected mSelectedPosition = INVALID_POSITION; mSelectedRowId = INVALID_ROW_ID; mNextSelectedPosition = INVALID_POSITION; mNextSelectedRowId = INVALID_ROW_ID; mNeedSync = false; checkSelectionChanged(); } } void checkSelectionChanged() { if ((mSelectedPosition != mOldSelectedPosition) || (mSelectedRowId != mOldSelectedRowId)) { selectionChanged(); mOldSelectedPosition = mSelectedPosition; mOldSelectedRowId = mSelectedRowId; } } /** * Searches the adapter for a position matching mSyncRowId. The search starts at mSyncPosition * and then alternates between moving up and moving down until 1) we find the right position, or * 2) we run out of time, or 3) we have looked at every position * * @return Position of the row that matches mSyncRowId, or {@link #INVALID_POSITION} if it can't * be found */ int findSyncPosition() { int count = mItemCount; if (count == 0) { return INVALID_POSITION; } long idToMatch = mSyncRowId; int seed = mSyncPosition; // If there isn't a selection don't hunt for it if (idToMatch == INVALID_ROW_ID) { return INVALID_POSITION; } // Pin seed to reasonable values seed = Math.max(0, seed); seed = Math.min(count - 1, seed); long endTime = SystemClock.uptimeMillis() + SYNC_MAX_DURATION_MILLIS; long rowId; // first position scanned so far int first = seed; // last position scanned so far int last = seed; // True if we should move down on the next iteration boolean next = false; // True when we have looked at the first item in the data boolean hitFirst; // True when we have looked at the last item in the data boolean hitLast; // Get the item ID locally (instead of getItemIdAtPosition), so // we need the adapter T adapter = getAdapter(); if (adapter == null) { return INVALID_POSITION; } while (SystemClock.uptimeMillis() <= endTime) { rowId = adapter.getItemId(seed); if (rowId == idToMatch) { // Found it! return seed; } hitLast = last == count - 1; hitFirst = first == 0; if (hitLast && hitFirst) { // Looked at everything break; } if (hitFirst || (next && !hitLast)) { // Either we hit the top, or we are trying to move down last++; seed = last; // Try going up next time next = false; } else if (hitLast || (!next && !hitFirst)) { // Either we hit the bottom, or we are trying to move up first--; seed = first; // Try going down next time next = true; } } return INVALID_POSITION; } /** * Find a position that can be selected (i.e., is not a separator). * * @param position The starting position to look at. * @param lookDown Whether to look down for other positions. * @return The next selectable position starting at position and then searching either up or * down. Returns {@link #INVALID_POSITION} if nothing can be found. */ int lookForSelectablePosition(int position, boolean lookDown) { return position; } /** * Utility to keep mSelectedPosition and mSelectedRowId in sync * @param position Our current position */ void setSelectedPositionInt(int position) { mSelectedPosition = position; mSelectedRowId = getItemIdAtPosition(position); } /** * Utility to keep mNextSelectedPosition and mNextSelectedRowId in sync * @param position Intended value for mSelectedPosition the next time we go * through layout */ void setNextSelectedPositionInt(int position) { mNextSelectedPosition = position; mNextSelectedRowId = getItemIdAtPosition(position); // If we are trying to sync to the selection, update that too if (mNeedSync && mSyncMode == SYNC_SELECTED_POSITION && position >= 0) { mSyncPosition = position; mSyncRowId = mNextSelectedRowId; } } /** * Remember enough information to restore the screen state when the data has * changed. * */ void rememberSyncState() { if (getChildCount() > 0) { mNeedSync = true; mSyncHeight = mLayoutHeight; if (mSelectedPosition >= 0) { // Sync the selection state View v = getChildAt(mSelectedPosition - mFirstPosition); mSyncRowId = mNextSelectedRowId; mSyncPosition = mNextSelectedPosition; if (v != null) { mSpecificTop = v.getTop(); } mSyncMode = SYNC_SELECTED_POSITION; } else { // Sync the based on the offset of the first view View v = getChildAt(0); T adapter = getAdapter(); if (mFirstPosition >= 0 && mFirstPosition < adapter.getCount()) { mSyncRowId = adapter.getItemId(mFirstPosition); } else { mSyncRowId = NO_ID; } mSyncPosition = mFirstPosition; if (v != null) { mSpecificTop = v.getTop(); } mSyncMode = SYNC_FIRST_POSITION; } } } }
Java
/* * Copyright (C) 2006 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.actionbarsherlock.internal.widget; import android.content.Context; import android.database.DataSetObserver; import android.graphics.Rect; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import android.widget.SpinnerAdapter; /** * An abstract base class for spinner widgets. SDK users will probably not * need to use this class. * * @attr ref android.R.styleable#AbsSpinner_entries */ public abstract class IcsAbsSpinner extends IcsAdapterView<SpinnerAdapter> { private static final boolean IS_HONEYCOMB = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; SpinnerAdapter mAdapter; int mHeightMeasureSpec; int mWidthMeasureSpec; boolean mBlockLayoutRequests; int mSelectionLeftPadding = 0; int mSelectionTopPadding = 0; int mSelectionRightPadding = 0; int mSelectionBottomPadding = 0; final Rect mSpinnerPadding = new Rect(); final RecycleBin mRecycler = new RecycleBin(); private DataSetObserver mDataSetObserver; /** Temporary frame to hold a child View's frame rectangle */ private Rect mTouchFrame; public IcsAbsSpinner(Context context) { super(context); initAbsSpinner(); } public IcsAbsSpinner(Context context, AttributeSet attrs) { this(context, attrs, 0); } public IcsAbsSpinner(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initAbsSpinner(); /* TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.AbsSpinner, defStyle, 0); CharSequence[] entries = a.getTextArray(R.styleable.AbsSpinner_entries); if (entries != null) { ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(context, R.layout.simple_spinner_item, entries); adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item); setAdapter(adapter); } a.recycle(); */ } /** * Common code for different constructor flavors */ private void initAbsSpinner() { setFocusable(true); setWillNotDraw(false); } /** * The Adapter is used to provide the data which backs this Spinner. * It also provides methods to transform spinner items based on their position * relative to the selected item. * @param adapter The SpinnerAdapter to use for this Spinner */ @Override public void setAdapter(SpinnerAdapter adapter) { if (null != mAdapter) { mAdapter.unregisterDataSetObserver(mDataSetObserver); resetList(); } mAdapter = adapter; mOldSelectedPosition = INVALID_POSITION; mOldSelectedRowId = INVALID_ROW_ID; if (mAdapter != null) { mOldItemCount = mItemCount; mItemCount = mAdapter.getCount(); checkFocus(); mDataSetObserver = new AdapterDataSetObserver(); mAdapter.registerDataSetObserver(mDataSetObserver); int position = mItemCount > 0 ? 0 : INVALID_POSITION; setSelectedPositionInt(position); setNextSelectedPositionInt(position); if (mItemCount == 0) { // Nothing selected checkSelectionChanged(); } } else { checkFocus(); resetList(); // Nothing selected checkSelectionChanged(); } requestLayout(); } /** * Clear out all children from the list */ void resetList() { mDataChanged = false; mNeedSync = false; removeAllViewsInLayout(); mOldSelectedPosition = INVALID_POSITION; mOldSelectedRowId = INVALID_ROW_ID; setSelectedPositionInt(INVALID_POSITION); setNextSelectedPositionInt(INVALID_POSITION); invalidate(); } /** * @see android.view.View#measure(int, int) * * Figure out the dimensions of this Spinner. The width comes from * the widthMeasureSpec as Spinnners can't have their width set to * UNSPECIFIED. The height is based on the height of the selected item * plus padding. */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize; int heightSize; final int mPaddingLeft = getPaddingLeft(); final int mPaddingTop = getPaddingTop(); final int mPaddingRight = getPaddingRight(); final int mPaddingBottom = getPaddingBottom(); mSpinnerPadding.left = mPaddingLeft > mSelectionLeftPadding ? mPaddingLeft : mSelectionLeftPadding; mSpinnerPadding.top = mPaddingTop > mSelectionTopPadding ? mPaddingTop : mSelectionTopPadding; mSpinnerPadding.right = mPaddingRight > mSelectionRightPadding ? mPaddingRight : mSelectionRightPadding; mSpinnerPadding.bottom = mPaddingBottom > mSelectionBottomPadding ? mPaddingBottom : mSelectionBottomPadding; if (mDataChanged) { handleDataChanged(); } int preferredHeight = 0; int preferredWidth = 0; boolean needsMeasuring = true; int selectedPosition = getSelectedItemPosition(); if (selectedPosition >= 0 && mAdapter != null && selectedPosition < mAdapter.getCount()) { // Try looking in the recycler. (Maybe we were measured once already) View view = mRecycler.get(selectedPosition); if (view == null) { // Make a new one view = mAdapter.getView(selectedPosition, null, this); } if (view != null) { // Put in recycler for re-measuring and/or layout mRecycler.put(selectedPosition, view); } if (view != null) { if (view.getLayoutParams() == null) { mBlockLayoutRequests = true; view.setLayoutParams(generateDefaultLayoutParams()); mBlockLayoutRequests = false; } measureChild(view, widthMeasureSpec, heightMeasureSpec); preferredHeight = getChildHeight(view) + mSpinnerPadding.top + mSpinnerPadding.bottom; preferredWidth = getChildWidth(view) + mSpinnerPadding.left + mSpinnerPadding.right; needsMeasuring = false; } } if (needsMeasuring) { // No views -- just use padding preferredHeight = mSpinnerPadding.top + mSpinnerPadding.bottom; if (widthMode == MeasureSpec.UNSPECIFIED) { preferredWidth = mSpinnerPadding.left + mSpinnerPadding.right; } } preferredHeight = Math.max(preferredHeight, getSuggestedMinimumHeight()); preferredWidth = Math.max(preferredWidth, getSuggestedMinimumWidth()); if (IS_HONEYCOMB) { heightSize = resolveSizeAndState(preferredHeight, heightMeasureSpec, 0); widthSize = resolveSizeAndState(preferredWidth, widthMeasureSpec, 0); } else { heightSize = resolveSize(preferredHeight, heightMeasureSpec); widthSize = resolveSize(preferredWidth, widthMeasureSpec); } setMeasuredDimension(widthSize, heightSize); mHeightMeasureSpec = heightMeasureSpec; mWidthMeasureSpec = widthMeasureSpec; } int getChildHeight(View child) { return child.getMeasuredHeight(); } int getChildWidth(View child) { return child.getMeasuredWidth(); } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } void recycleAllViews() { final int childCount = getChildCount(); final IcsAbsSpinner.RecycleBin recycleBin = mRecycler; final int position = mFirstPosition; // All views go in recycler for (int i = 0; i < childCount; i++) { View v = getChildAt(i); int index = position + i; recycleBin.put(index, v); } } /** * Jump directly to a specific item in the adapter data. */ public void setSelection(int position, boolean animate) { // Animate only if requested position is already on screen somewhere boolean shouldAnimate = animate && mFirstPosition <= position && position <= mFirstPosition + getChildCount() - 1; setSelectionInt(position, shouldAnimate); } @Override public void setSelection(int position) { setNextSelectedPositionInt(position); requestLayout(); invalidate(); } /** * Makes the item at the supplied position selected. * * @param position Position to select * @param animate Should the transition be animated * */ void setSelectionInt(int position, boolean animate) { if (position != mOldSelectedPosition) { mBlockLayoutRequests = true; int delta = position - mSelectedPosition; setNextSelectedPositionInt(position); layout(delta, animate); mBlockLayoutRequests = false; } } abstract void layout(int delta, boolean animate); @Override public View getSelectedView() { if (mItemCount > 0 && mSelectedPosition >= 0) { return getChildAt(mSelectedPosition - mFirstPosition); } else { return null; } } /** * Override to prevent spamming ourselves with layout requests * as we place views * * @see android.view.View#requestLayout() */ @Override public void requestLayout() { if (!mBlockLayoutRequests) { super.requestLayout(); } } @Override public SpinnerAdapter getAdapter() { return mAdapter; } @Override public int getCount() { return mItemCount; } /** * Maps a point to a position in the list. * * @param x X in local coordinate * @param y Y in local coordinate * @return The position of the item which contains the specified point, or * {@link #INVALID_POSITION} if the point does not intersect an item. */ public int pointToPosition(int x, int y) { Rect frame = mTouchFrame; if (frame == null) { mTouchFrame = new Rect(); frame = mTouchFrame; } final int count = getChildCount(); for (int i = count - 1; i >= 0; i--) { View child = getChildAt(i); if (child.getVisibility() == View.VISIBLE) { child.getHitRect(frame); if (frame.contains(x, y)) { return mFirstPosition + i; } } } return INVALID_POSITION; } static class SavedState extends BaseSavedState { long selectedId; int position; /** * Constructor called from {@link AbsSpinner#onSaveInstanceState()} */ SavedState(Parcelable superState) { super(superState); } /** * Constructor called from {@link #CREATOR} */ private SavedState(Parcel in) { super(in); selectedId = in.readLong(); position = in.readInt(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeLong(selectedId); out.writeInt(position); } @Override public String toString() { return "AbsSpinner.SavedState{" + Integer.toHexString(System.identityHashCode(this)) + " selectedId=" + selectedId + " position=" + position + "}"; } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.selectedId = getSelectedItemId(); if (ss.selectedId >= 0) { ss.position = getSelectedItemPosition(); } else { ss.position = INVALID_POSITION; } return ss; } @Override public void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); if (ss.selectedId >= 0) { mDataChanged = true; mNeedSync = true; mSyncRowId = ss.selectedId; mSyncPosition = ss.position; mSyncMode = SYNC_SELECTED_POSITION; requestLayout(); } } class RecycleBin { private final SparseArray<View> mScrapHeap = new SparseArray<View>(); public void put(int position, View v) { mScrapHeap.put(position, v); } View get(int position) { // System.out.print("Looking for " + position); View result = mScrapHeap.get(position); if (result != null) { // System.out.println(" HIT"); mScrapHeap.delete(position); } else { // System.out.println(" MISS"); } return result; } void clear() { final SparseArray<View> scrapHeap = mScrapHeap; final int count = scrapHeap.size(); for (int i = 0; i < count; i++) { final View view = scrapHeap.valueAt(i); if (view != null) { removeDetachedView(view, true); } } scrapHeap.clear(); } } }
Java
/* * Copyright (C) 2011 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.actionbarsherlock.internal.widget; import android.content.Context; import android.content.res.Configuration; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.text.TextUtils.TruncateAt; import android.util.AttributeSet; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.widget.BaseAdapter; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import com.actionbarsherlock.R; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.internal.nineoldandroids.animation.Animator; import com.actionbarsherlock.internal.nineoldandroids.animation.ObjectAnimator; /** * This widget implements the dynamic action bar tab behavior that can change * across different configurations or circumstances. */ public class ScrollingTabContainerView extends HorizontalScrollView implements IcsAdapterView.OnItemSelectedListener { //UNUSED private static final String TAG = "ScrollingTabContainerView"; Runnable mTabSelector; private TabClickListener mTabClickListener; private IcsLinearLayout mTabLayout; private IcsSpinner mTabSpinner; private boolean mAllowCollapse; private LayoutInflater mInflater; int mMaxTabWidth; private int mContentHeight; private int mSelectedTabIndex; protected Animator mVisibilityAnim; protected final VisibilityAnimListener mVisAnimListener = new VisibilityAnimListener(); private static final /*Time*/Interpolator sAlphaInterpolator = new DecelerateInterpolator(); private static final int FADE_DURATION = 200; public ScrollingTabContainerView(Context context) { super(context); setHorizontalScrollBarEnabled(false); TypedArray a = getContext().obtainStyledAttributes(null, R.styleable.SherlockActionBar, R.attr.actionBarStyle, 0); setContentHeight(a.getLayoutDimension(R.styleable.SherlockActionBar_height, 0)); a.recycle(); mInflater = LayoutInflater.from(context); mTabLayout = createTabLayout(); addView(mTabLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final boolean lockedExpanded = widthMode == MeasureSpec.EXACTLY; setFillViewport(lockedExpanded); final int childCount = mTabLayout.getChildCount(); if (childCount > 1 && (widthMode == MeasureSpec.EXACTLY || widthMode == MeasureSpec.AT_MOST)) { if (childCount > 2) { mMaxTabWidth = (int) (MeasureSpec.getSize(widthMeasureSpec) * 0.4f); } else { mMaxTabWidth = MeasureSpec.getSize(widthMeasureSpec) / 2; } } else { mMaxTabWidth = -1; } heightMeasureSpec = MeasureSpec.makeMeasureSpec(mContentHeight, MeasureSpec.EXACTLY); final boolean canCollapse = !lockedExpanded && mAllowCollapse; if (canCollapse) { // See if we should expand mTabLayout.measure(MeasureSpec.UNSPECIFIED, heightMeasureSpec); if (mTabLayout.getMeasuredWidth() > MeasureSpec.getSize(widthMeasureSpec)) { performCollapse(); } else { performExpand(); } } else { performExpand(); } final int oldWidth = getMeasuredWidth(); super.onMeasure(widthMeasureSpec, heightMeasureSpec); final int newWidth = getMeasuredWidth(); if (lockedExpanded && oldWidth != newWidth) { // Recenter the tab display if we're at a new (scrollable) size. setTabSelected(mSelectedTabIndex); } } /** * Indicates whether this view is collapsed into a dropdown menu instead * of traditional tabs. * @return true if showing as a spinner */ private boolean isCollapsed() { return mTabSpinner != null && mTabSpinner.getParent() == this; } public void setAllowCollapse(boolean allowCollapse) { mAllowCollapse = allowCollapse; } private void performCollapse() { if (isCollapsed()) return; if (mTabSpinner == null) { mTabSpinner = createSpinner(); } removeView(mTabLayout); addView(mTabSpinner, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)); if (mTabSpinner.getAdapter() == null) { mTabSpinner.setAdapter(new TabAdapter()); } if (mTabSelector != null) { removeCallbacks(mTabSelector); mTabSelector = null; } mTabSpinner.setSelection(mSelectedTabIndex); } private boolean performExpand() { if (!isCollapsed()) return false; removeView(mTabSpinner); addView(mTabLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)); setTabSelected(mTabSpinner.getSelectedItemPosition()); return false; } public void setTabSelected(int position) { mSelectedTabIndex = position; final int tabCount = mTabLayout.getChildCount(); for (int i = 0; i < tabCount; i++) { final View child = mTabLayout.getChildAt(i); final boolean isSelected = i == position; child.setSelected(isSelected); if (isSelected) { animateToTab(position); } } } public void setContentHeight(int contentHeight) { mContentHeight = contentHeight; requestLayout(); } private IcsLinearLayout createTabLayout() { final IcsLinearLayout tabLayout = (IcsLinearLayout) LayoutInflater.from(getContext()) .inflate(R.layout.abs__action_bar_tab_bar_view, null); tabLayout.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)); return tabLayout; } private IcsSpinner createSpinner() { final IcsSpinner spinner = new IcsSpinner(getContext(), null, R.attr.actionDropDownStyle); spinner.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT)); spinner.setOnItemSelectedListener(this); return spinner; } @Override protected void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Action bar can change size on configuration changes. // Reread the desired height from the theme-specified style. TypedArray a = getContext().obtainStyledAttributes(null, R.styleable.SherlockActionBar, R.attr.actionBarStyle, 0); setContentHeight(a.getLayoutDimension(R.styleable.SherlockActionBar_height, 0)); a.recycle(); } public void animateToVisibility(int visibility) { if (mVisibilityAnim != null) { mVisibilityAnim.cancel(); } if (visibility == VISIBLE) { if (getVisibility() != VISIBLE) { setAlpha(0); } ObjectAnimator anim = ObjectAnimator.ofFloat(this, "alpha", 1); anim.setDuration(FADE_DURATION); anim.setInterpolator(sAlphaInterpolator); anim.addListener(mVisAnimListener.withFinalVisibility(visibility)); anim.start(); } else { ObjectAnimator anim = ObjectAnimator.ofFloat(this, "alpha", 0); anim.setDuration(FADE_DURATION); anim.setInterpolator(sAlphaInterpolator); anim.addListener(mVisAnimListener.withFinalVisibility(visibility)); anim.start(); } } public void animateToTab(final int position) { final View tabView = mTabLayout.getChildAt(position); if (mTabSelector != null) { removeCallbacks(mTabSelector); } mTabSelector = new Runnable() { public void run() { final int scrollPos = tabView.getLeft() - (getWidth() - tabView.getWidth()) / 2; smoothScrollTo(scrollPos, 0); mTabSelector = null; } }; post(mTabSelector); } @Override public void onAttachedToWindow() { super.onAttachedToWindow(); if (mTabSelector != null) { // Re-post the selector we saved post(mTabSelector); } } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mTabSelector != null) { removeCallbacks(mTabSelector); } } private TabView createTabView(ActionBar.Tab tab, boolean forAdapter) { //Workaround for not being able to pass a defStyle on pre-3.0 final TabView tabView = (TabView)mInflater.inflate(R.layout.abs__action_bar_tab, null); tabView.init(this, tab, forAdapter); if (forAdapter) { tabView.setBackgroundDrawable(null); tabView.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT, mContentHeight)); } else { tabView.setFocusable(true); if (mTabClickListener == null) { mTabClickListener = new TabClickListener(); } tabView.setOnClickListener(mTabClickListener); } return tabView; } public void addTab(ActionBar.Tab tab, boolean setSelected) { TabView tabView = createTabView(tab, false); mTabLayout.addView(tabView, new IcsLinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1)); if (mTabSpinner != null) { ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); } if (setSelected) { tabView.setSelected(true); } if (mAllowCollapse) { requestLayout(); } } public void addTab(ActionBar.Tab tab, int position, boolean setSelected) { final TabView tabView = createTabView(tab, false); mTabLayout.addView(tabView, position, new IcsLinearLayout.LayoutParams( 0, LayoutParams.MATCH_PARENT, 1)); if (mTabSpinner != null) { ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); } if (setSelected) { tabView.setSelected(true); } if (mAllowCollapse) { requestLayout(); } } public void updateTab(int position) { ((TabView) mTabLayout.getChildAt(position)).update(); if (mTabSpinner != null) { ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); } if (mAllowCollapse) { requestLayout(); } } public void removeTabAt(int position) { mTabLayout.removeViewAt(position); if (mTabSpinner != null) { ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); } if (mAllowCollapse) { requestLayout(); } } public void removeAllTabs() { mTabLayout.removeAllViews(); if (mTabSpinner != null) { ((TabAdapter) mTabSpinner.getAdapter()).notifyDataSetChanged(); } if (mAllowCollapse) { requestLayout(); } } @Override public void onItemSelected(IcsAdapterView<?> parent, View view, int position, long id) { TabView tabView = (TabView) view; tabView.getTab().select(); } @Override public void onNothingSelected(IcsAdapterView<?> parent) { } public static class TabView extends LinearLayout { private ScrollingTabContainerView mParent; private ActionBar.Tab mTab; private CapitalizingTextView mTextView; private ImageView mIconView; private View mCustomView; public TabView(Context context, AttributeSet attrs) { //TODO super(context, null, R.attr.actionBarTabStyle); super(context, attrs); } public void init(ScrollingTabContainerView parent, ActionBar.Tab tab, boolean forList) { mParent = parent; mTab = tab; if (forList) { setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL); } update(); } public void bindTab(ActionBar.Tab tab) { mTab = tab; update(); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // Re-measure if we went beyond our maximum size. if (mParent.mMaxTabWidth > 0 && getMeasuredWidth() > mParent.mMaxTabWidth) { super.onMeasure(MeasureSpec.makeMeasureSpec(mParent.mMaxTabWidth, MeasureSpec.EXACTLY), heightMeasureSpec); } } public void update() { final ActionBar.Tab tab = mTab; final View custom = tab.getCustomView(); if (custom != null) { final ViewParent customParent = custom.getParent(); if (customParent != this) { if (customParent != null) ((ViewGroup) customParent).removeView(custom); addView(custom); } mCustomView = custom; if (mTextView != null) mTextView.setVisibility(GONE); if (mIconView != null) { mIconView.setVisibility(GONE); mIconView.setImageDrawable(null); } } else { if (mCustomView != null) { removeView(mCustomView); mCustomView = null; } final Drawable icon = tab.getIcon(); final CharSequence text = tab.getText(); if (icon != null) { if (mIconView == null) { ImageView iconView = new ImageView(getContext()); LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); lp.gravity = Gravity.CENTER_VERTICAL; iconView.setLayoutParams(lp); addView(iconView, 0); mIconView = iconView; } mIconView.setImageDrawable(icon); mIconView.setVisibility(VISIBLE); } else if (mIconView != null) { mIconView.setVisibility(GONE); mIconView.setImageDrawable(null); } if (text != null) { if (mTextView == null) { CapitalizingTextView textView = new CapitalizingTextView(getContext(), null, R.attr.actionBarTabTextStyle); textView.setEllipsize(TruncateAt.END); LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); lp.gravity = Gravity.CENTER_VERTICAL; textView.setLayoutParams(lp); addView(textView); mTextView = textView; } mTextView.setTextCompat(text); mTextView.setVisibility(VISIBLE); } else if (mTextView != null) { mTextView.setVisibility(GONE); mTextView.setText(null); } if (mIconView != null) { mIconView.setContentDescription(tab.getContentDescription()); } } } public ActionBar.Tab getTab() { return mTab; } } private class TabAdapter extends BaseAdapter { @Override public int getCount() { return mTabLayout.getChildCount(); } @Override public Object getItem(int position) { return ((TabView) mTabLayout.getChildAt(position)).getTab(); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = createTabView((ActionBar.Tab) getItem(position), true); } else { ((TabView) convertView).bindTab((ActionBar.Tab) getItem(position)); } return convertView; } } private class TabClickListener implements OnClickListener { public void onClick(View view) { TabView tabView = (TabView) view; tabView.getTab().select(); final int tabCount = mTabLayout.getChildCount(); for (int i = 0; i < tabCount; i++) { final View child = mTabLayout.getChildAt(i); child.setSelected(child == view); } } } protected class VisibilityAnimListener implements Animator.AnimatorListener { private boolean mCanceled = false; private int mFinalVisibility; public VisibilityAnimListener withFinalVisibility(int visibility) { mFinalVisibility = visibility; return this; } @Override public void onAnimationStart(Animator animation) { setVisibility(VISIBLE); mVisibilityAnim = animation; mCanceled = false; } @Override public void onAnimationEnd(Animator animation) { if (mCanceled) return; mVisibilityAnim = null; setVisibility(mFinalVisibility); } @Override public void onAnimationCancel(Animator animation) { mCanceled = true; } @Override public void onAnimationRepeat(Animator animation) { } } }
Java
package com.actionbarsherlock.internal.widget; import java.util.Locale; import android.content.Context; import android.content.res.TypedArray; import android.os.Build; import android.util.AttributeSet; import android.widget.Button; public class CapitalizingButton extends Button { private static final boolean SANS_ICE_CREAM = Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH; private static final boolean IS_GINGERBREAD = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD; private static final int[] R_styleable_Button = new int[] { android.R.attr.textAllCaps }; private static final int R_styleable_Button_textAllCaps = 0; private boolean mAllCaps; public CapitalizingButton(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R_styleable_Button); mAllCaps = a.getBoolean(R_styleable_Button_textAllCaps, true); a.recycle(); } public void setTextCompat(CharSequence text) { if (SANS_ICE_CREAM && mAllCaps && text != null) { if (IS_GINGERBREAD) { setText(text.toString().toUpperCase(Locale.ROOT)); } else { setText(text.toString().toUpperCase()); } } else { setText(text); } } }
Java
package com.actionbarsherlock.internal; import android.content.Context; import android.os.Build; import android.util.DisplayMetrics; import com.actionbarsherlock.R; public final class ResourcesCompat { //No instances private ResourcesCompat() {} /** * Support implementation of {@code getResources().getBoolean()} that we * can use to simulate filtering based on width and smallest width * qualifiers on pre-3.2. * * @param context Context to load booleans from on 3.2+ and to fetch the * display metrics. * @param id Id of boolean to load. * @return Associated boolean value as reflected by the current display * metrics. */ public static boolean getResources_getBoolean(Context context, int id) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { return context.getResources().getBoolean(id); } DisplayMetrics metrics = context.getResources().getDisplayMetrics(); float widthDp = metrics.widthPixels / metrics.density; float heightDp = metrics.heightPixels / metrics.density; float smallestWidthDp = (widthDp < heightDp) ? widthDp : heightDp; if (id == R.bool.abs__action_bar_embed_tabs) { if (widthDp >= 480) { return true; //values-w480dp } return false; //values } if (id == R.bool.abs__split_action_bar_is_narrow) { if (widthDp >= 480) { return false; //values-w480dp } return true; //values } if (id == R.bool.abs__action_bar_expanded_action_views_exclusive) { if (smallestWidthDp >= 600) { return false; //values-sw600dp } return true; //values } if (id == R.bool.abs__config_allowActionMenuItemTextWithIcon) { if (widthDp >= 480) { return true; //values-w480dp } return false; //values } throw new IllegalArgumentException("Unknown boolean resource ID " + id); } /** * Support implementation of {@code getResources().getInteger()} that we * can use to simulate filtering based on width qualifiers on pre-3.2. * * @param context Context to load integers from on 3.2+ and to fetch the * display metrics. * @param id Id of integer to load. * @return Associated integer value as reflected by the current display * metrics. */ public static int getResources_getInteger(Context context, int id) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { return context.getResources().getInteger(id); } DisplayMetrics metrics = context.getResources().getDisplayMetrics(); float widthDp = metrics.widthPixels / metrics.density; if (id == R.integer.abs__max_action_buttons) { if (widthDp >= 600) { return 5; //values-w600dp } if (widthDp >= 500) { return 4; //values-w500dp } if (widthDp >= 360) { return 3; //values-w360dp } return 2; //values } throw new IllegalArgumentException("Unknown integer resource ID " + id); } }
Java
package yuku.adtbugs.widget; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.View; import yuku.adtbugs.R; public class CustomBitmapView extends View { public static final String TAG = CustomBitmapView.class.getSimpleName(); private Bitmap bitmap; public CustomBitmapView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bitmap640x200px); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawBitmap(bitmap, 0, 0, null); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(resolveSize(bitmap.getWidth(), widthMeasureSpec), resolveSize(bitmap.getHeight(), heightMeasureSpec)); } }
Java
package yuku.adtbugs.ac; import android.app.Activity; import android.os.Bundle; import yuku.adtbugs.R; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
Java
package yuku.easybilling; public interface EasyBillingListener { void onInventoryAmountChange(String productId, PurchaseState purchaseState, int oldAmount, int newAmount); }
Java
package yuku.easybilling; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.IntentSender.SendIntentException; import android.util.Log; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import yuku.easybilling.BillingRequest.CheckBillingSupportedRequest; import yuku.easybilling.BillingRequest.ConfirmNotificationsRequest; import yuku.easybilling.BillingRequest.GetPurchaseInformationRequest; import yuku.easybilling.BillingRequest.RequestPurchaseRequest; import yuku.easybilling.BillingRequest.RestoreTransactionsRequest; import yuku.easybilling.BillingResult.CheckBillingSupportedResult; import yuku.easybilling.BillingResult.ConfirmNotificationsResult; import yuku.easybilling.BillingResult.GetPurchaseInformationResult; import yuku.easybilling.BillingResult.RequestPurchaseResult; import yuku.easybilling.BillingResult.RestoreTransactionsResult; import yuku.easybilling.BillingSecurity.SignedData; /** Static methods to call from anywhere! */ public class EasyBilling { public static final String TAG = EasyBilling.class.getSimpleName(); static Context appContext; static BillingService service; static String base64Key; private static ResponseCode checkBillingSupportedResult; private static WeakHashMap<EasyBillingListener, Object> listeners = new WeakHashMap<EasyBillingListener, Object>(); private static final Object DUMMY = new Object(); public static void init(Context appContext, String base64Key) { EasyBilling.appContext = appContext; EasyBilling.base64Key = base64Key; // for checking if billing supported initService(); CheckBillingSupportedRequest request = new CheckBillingSupportedRequest(appContext); service.request(request, new BillingResultListener<CheckBillingSupportedResult>() { @Override public void onBillingResult(BillingRequestStatus status, CheckBillingSupportedResult result) { Log.d(TAG, "CheckBillingSupportedResult result: " + result.responseCode); checkBillingSupportedResult = result.responseCode; } }); } /** Check if Billing is supported. * @return {@link ResponseCode#RESULT_OK} if yes, non-null if no, and null if no result yet. */ public static ResponseCode isBillingSupported() { return checkBillingSupportedResult; } /** * This keeps track of the nonces that we generated and sent to the server. * We need to keep track of these until we get back the purchase state and * send a confirmation message back to Android Market. If we are killed and * lose this list of nonces, it is not fatal. Android Market will send us a * new "notify" message and we will re-generate a new nonce. This has to be * "static" so that the {@link BillingReceiver} can check if a nonce exists. */ private static HashSet<Long> sKnownNonces = new HashSet<Long>(); private static SecureRandom sRandom = new SecureRandom(); /** Generates a nonce (a random number used once). */ static long storeAndGetNonce() { long nonce = sRandom.nextLong(); Log.i(TAG, "Nonce generated: " + nonce); sKnownNonces.add(nonce); return nonce; } static void removeNonce(long nonce) { sKnownNonces.remove(nonce); } static boolean isNonceKnown(long nonce) { return sKnownNonces.contains(nonce); } public static void addListener(EasyBillingListener listener) { listeners.put(listener, DUMMY); } public static void removeListener(EasyBillingListener listener) { listeners.remove(listener); } public static int getInventoryAmount(String productId) { return BillingDb.get(appContext).getInventoryAmount(productId); } public static Map<String, Integer> getAllInventory() { return BillingDb.get(appContext).getAllInventory(); } private static void initService() { if (service == null) { service = new BillingService(); service.setContext(appContext); } } public static BillingRequestStatus startPurchase(final Activity activity, String productId, String optionalDeveloperPayload) { initService(); RequestPurchaseRequest request = new RequestPurchaseRequest(appContext, productId, optionalDeveloperPayload); return service.request(request, new BillingResultListener<RequestPurchaseResult>() { @Override public void onBillingResult(BillingRequestStatus status, RequestPurchaseResult result) { try { activity.startIntentSender(result.purchaseIntent.getIntentSender(), new Intent(), 0, 0, 0); } catch (SendIntentException e) { Log.e(TAG, "error starting activity", e); } } }); } public static BillingRequestStatus startRestoreTransactions() { initService(); RestoreTransactionsRequest request = new RestoreTransactionsRequest(appContext, storeAndGetNonce()); return service.request(request, new BillingResultListener<RestoreTransactionsResult>() { @Override public void onBillingResult(BillingRequestStatus status, RestoreTransactionsResult result) { Log.d(TAG, "RestoreTransactions result: " + result.responseCode); } }); } static void gotInAppNotify(String notification_id) { Log.d(TAG, "@@gotInAppNotify"); String[] notification_ids = { notification_id }; initService(); GetPurchaseInformationRequest request = new GetPurchaseInformationRequest(appContext, storeAndGetNonce(), notification_ids); service.request(request, new BillingResultListener<GetPurchaseInformationResult>() { @Override public void onBillingResult(BillingRequestStatus status, GetPurchaseInformationResult result) { Log.d(TAG, "GetPurchaseInformation result: " + result.responseCode); } }); } static void gotPurchaseStateChanged(String inapp_signed_data, String inapp_signature) { Log.d(TAG, "@@gotPurchaseStateChanged"); boolean verified = BillingSecurity.verifySignedData(inapp_signed_data, inapp_signature); if (!verified) { Log.e(TAG, "Signature verification error"); return; } SignedData signedData = BillingSecurity.decodeSignedData(inapp_signed_data); if (!isNonceKnown(signedData.nonce)) { Log.e(TAG, "Nonce is unknown: " + signedData.nonce); return; } // make a copy of current listeners Set<EasyBillingListener> listenerSet = new HashSet<EasyBillingListener>(listeners.keySet()); List<String> notification_ids = new ArrayList<String>(); for (SignedData.Order change: signedData.orders) { notification_ids.add(change.notificationId); BillingDb.get(appContext).updateWithChange(change, listenerSet); } initService(); ConfirmNotificationsRequest request = new ConfirmNotificationsRequest(appContext, notification_ids.toArray(new String[notification_ids.size()])); service.request(request, new BillingResultListener<ConfirmNotificationsResult>() { @Override public void onBillingResult(BillingRequestStatus status, ConfirmNotificationsResult result) { Log.d(TAG, "ConfirmNotifications result: " + result.responseCode); } }); } }
Java
package yuku.easybilling; // The response codes for a request, defined by Android Market. public enum ResponseCode { RESULT_OK, RESULT_USER_CANCELED, RESULT_SERVICE_UNAVAILABLE, RESULT_BILLING_UNAVAILABLE, RESULT_ITEM_UNAVAILABLE, RESULT_DEVELOPER_ERROR, RESULT_ERROR; // Converts from an ordinal value to the ResponseCode public static ResponseCode valueOf(int index) { ResponseCode[] values = ResponseCode.values(); if (index < 0 || index >= values.length) { return RESULT_ERROR; } return values[index]; } }
Java
package yuku.easybilling; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import android.util.Pair; import java.util.ArrayList; import java.util.List; import com.android.vending.billing.IMarketBillingService; public class BillingService extends Service implements ServiceConnection { private static final String TAG = BillingService.class.getSimpleName(); /** The service connection to the remote MarketBillingService. */ private IMarketBillingService remoteService; private List<Pair<BillingRequest, BillingResultListener<? extends BillingResult>>> pendingRequests = new ArrayList<Pair<BillingRequest, BillingResultListener<? extends BillingResult>>>(); @Override public void onCreate() { super.onCreate(); Log.i(TAG, "@@onCreate"); } public void setContext(Context context) { attachBaseContext(context); } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.i(TAG, "Remote service connected."); remoteService = IMarketBillingService.Stub.asInterface(service); // run pending requests if any runPendingRequests(); } @Override public void onServiceDisconnected(ComponentName name) { Log.d(TAG, "Remote service disconnected"); remoteService = null; } @SuppressWarnings("unchecked") private void runPendingRequests() { Log.d(TAG, "@@runPendingRequests"); while (true) { if (pendingRequests.size() == 0) { Log.d(TAG, "No more pendingRequests"); break; } else { Log.d(TAG, "We have " + pendingRequests.size() + " pendingRequests"); } if (remoteService == null) { Log.d(TAG, "runPendingRequests stopped because remoteService is disconnected"); break; } // remoteService is available now! Pair<BillingRequest, BillingResultListener<? extends BillingResult>> entry = null; synchronized (pendingRequests) { if (pendingRequests.size() > 0) entry = pendingRequests.remove(0); } if (entry == null) { Log.d(TAG, "No more pendingRequests"); break; } @SuppressWarnings("rawtypes") BillingResultListener listener = entry.second; try { BillingRequest request = entry.first; Bundle requestBundle = request.getRequestBundle(); Bundle resultBundle = remoteService.sendBillingRequest(requestBundle); BillingResult result = request.parseResultBundle(resultBundle); if (listener == null) { Log.d(TAG, "Listener is null, we ignore the result (OK)"); } else { listener.onBillingResult(BillingRequestStatus.DELAYED, result); } } catch (RemoteException e) { if (listener == null) { Log.d(TAG, "Listener is null, we ignore the result (RemoteException)"); } else { listener.onBillingResult(BillingRequestStatus.REMOTE_EXCEPTION, null); } } } } public <T extends BillingResult> BillingRequestStatus request(BillingRequest request, BillingResultListener<T> resultListener) { BillingRequestStatus res = requestImpl(request, resultListener); Log.d(TAG, "request method result for " + request.getClass().getSimpleName() + ": " + res); return res; } @SuppressWarnings("unchecked") private <T extends BillingResult> BillingRequestStatus requestImpl(BillingRequest request, BillingResultListener<T> resultListener) { if (remoteService != null) { // we are connected to remote service. try { Bundle requestBundle = request.getRequestBundle(); Bundle resultBundle = remoteService.sendBillingRequest(requestBundle); resultListener.onBillingResult(BillingRequestStatus.IMMEDIATE, (T) request.parseResultBundle(resultBundle)); return BillingRequestStatus.IMMEDIATE; } catch (RemoteException e) { Log.e(TAG, "BillingService#request", e); return BillingRequestStatus.REMOTE_EXCEPTION; } } else { boolean bindResult = bindService(new Intent("com.android.vending.billing.MarketBillingService.BIND"), this, Context.BIND_AUTO_CREATE); if (bindResult) { synchronized (pendingRequests) { pendingRequests.add(new Pair<BillingRequest, BillingResultListener<?>>(request, resultListener)); } return BillingRequestStatus.DELAYED; } else { return BillingRequestStatus.BIND_ERROR; } } } }
Java
package yuku.easybilling; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import yuku.easybilling.BillingSecurity.SignedData; public class BillingDb { public static final String TAG = BillingDb.class.getSimpleName(); private static BillingDb instance = null; public static BillingDb get() { if (instance == null) { throw new RuntimeException("Pass in context for first time"); } return instance; } public static synchronized BillingDb get(Context context) { if (instance == null) { instance = new BillingDb(new BillingDbHelper(context)); } return instance; } protected final BillingDbHelper helper; private BillingDb(BillingDbHelper helper) { this.helper = helper; } public int getInventoryAmount(String productId) { SQLiteDatabase db = helper.getReadableDatabase(); Cursor c = db.query("Inventory", new String[] {"amount"}, "productId=?", new String[] {productId}, null, null, null); try { if (c.moveToNext()) { return c.getInt(0); } return 0; } finally { c.close(); } } public Map<String, Integer> getAllInventory() { Map<String, Integer> res = new LinkedHashMap<String, Integer>(); SQLiteDatabase db = helper.getReadableDatabase(); Cursor c = db.query("Inventory", new String[] {"productId", "amount"}, null, null, null, null, null); try { while (c.moveToNext()) { String productId = c.getString(0); int amount = c.getInt(1); res.put(productId, amount); } } finally { c.close(); } return res; } public void updateWithChange(SignedData.Order change, Set<EasyBillingListener> listenerSet) { SQLiteDatabase db = helper.getWritableDatabase(); String orderId = change.orderId; String productId = change.productId; Log.d(TAG, "@@updateWithOrder orderId: " + orderId); db.beginTransaction(); try { { // put to permanent log ContentValues cv = new ContentValues(); cv.put("orderId", change.orderId); cv.put("packageName", change.packageName); cv.put("productId", change.productId); cv.put("purchaseTime", change.purchaseTime); cv.put("purchaseState", change.purchaseState.ordinal()); cv.put("developerPayload", change.developerPayload); db.insert("Changes", null, cv); } boolean orderInDb = count(db, "Orders", "orderId=?", orderId) > 0; Log.d(TAG, "This order is in db?: " + orderInDb); if (orderInDb) { PurchaseState oldPurchaseState = PurchaseState.valueOf(getInt(db, "Orders", "purchaseState", -1, "orderId=?", orderId)); PurchaseState newPurchaseState = change.purchaseState; boolean oldHave = oldPurchaseState == PurchaseState.PURCHASED; boolean newHave = newPurchaseState == PurchaseState.PURCHASED; { // update db ContentValues cv = new ContentValues(); cv.put("orderId", change.orderId); cv.put("purchaseState", change.purchaseState.ordinal()); db.update("Orders", cv, "orderId=?", new String[] {orderId}); } if (oldHave == newHave) { Log.d(TAG, "productId " + change.productId + " inventory not updated, purchase state old=" + oldPurchaseState + " new=" + newPurchaseState); } else { int[] amounts = modifyAmount(db, productId, newHave? +1: -1); for (EasyBillingListener listener: listenerSet) { listener.onInventoryAmountChange(productId, newPurchaseState, amounts[0], amounts[1]); } } } else { PurchaseState newPurchaseState = change.purchaseState; boolean newHave = newPurchaseState == PurchaseState.PURCHASED; { // insert to db ContentValues cv = new ContentValues(); cv.put("orderId", change.orderId); cv.put("purchaseState", change.purchaseState.ordinal()); db.insert("Orders", null, cv); } if (newHave) { int[] amounts = modifyAmount(db, productId, +1); for (EasyBillingListener listener: listenerSet) { listener.onInventoryAmountChange(productId, newPurchaseState, amounts[0], amounts[1]); } } else { Log.d(TAG, "new purchase state: " + newPurchaseState + " for non-existing product in inventory, not modifying amount"); } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } private int[] modifyAmount(SQLiteDatabase db, String productId, int delta) { int oldAmount = getInt(db, "Inventory", "amount", 0, "productId=?", productId); int newAmount = oldAmount + delta; if (newAmount < 0) { Log.w(TAG, "New inventory amount of " + productId + " is negative: " + newAmount + " was: " + oldAmount + ", using 0 instead"); newAmount = 0; } ContentValues cv = new ContentValues(); cv.put("productId", productId); cv.put("amount", newAmount); if (count(db, "Inventory", "productId=?", productId) > 0) { // already on the table db.update("Inventory", cv, "productId=?", new String[] {productId}); } else { db.insert("Inventory", null, cv); } Log.w(TAG, "Inventory amount of " + productId + " was: " + oldAmount + ", now: " + newAmount); return new int[] {oldAmount, newAmount}; } private int count(SQLiteDatabase db, String table, String whereClause, String... whereArgs) { Cursor c = db.query(table, new String[] {"count(*)"}, whereClause, whereArgs, null, null, null); try { c.moveToNext(); return c.getInt(0); } finally { c.close(); } } private int getInt(SQLiteDatabase db, String table, String column, int def, String whereClause, String... whereArgs) { Cursor c = db.query(table, new String[] {column}, whereClause, whereArgs, null, null, null); try { if (c.moveToNext()) { return c.getInt(0); } else { return def; } } finally { c.close(); } } }
Java
package yuku.easybilling; // The possible states of an in-app purchase, as defined by Android Market. public enum PurchaseState { // Responses to requestPurchase or restoreTransactions. PURCHASED, // User was charged for the order. CANCELED, // The charge failed on the server. REFUNDED; // User received a refund for the order. // Converts from an ordinal value to the PurchaseState public static PurchaseState valueOf(int index) { PurchaseState[] values = PurchaseState.values(); if (index < 0 || index >= values.length) { return CANCELED; } return values[index]; } }
Java
package yuku.easybilling; public interface BillingResultListener<T extends BillingResult> { void onBillingResult(BillingRequestStatus status, T result); }
Java
package yuku.easybilling; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; public class BillingReceiver extends BroadcastReceiver { private static final String TAG = BillingReceiver.class.getSimpleName(); @Override public void onReceive(Context context, Intent intent) { { // debug Log.d(TAG, "Intent passed to BillingReceiver: "); Log.d(TAG, " action: " + intent.getAction()); Log.d(TAG, " data uri: " + intent.getData()); Log.d(TAG, " component name: " + intent.getComponent()); Log.d(TAG, " flags: 0x" + Integer.toHexString(intent.getFlags())); Log.d(TAG, " mime: " + intent.getType()); Bundle extras = intent.getExtras(); Log.d(TAG, " extras: " + (extras == null? "null": (extras.size() + " entries"))); if (extras != null) { for (String key: extras.keySet()) { Log.d(TAG, " " + key + " = " + extras.get(key)); } } } String action = intent.getAction(); if ("com.android.vending.billing.RESPONSE_CODE".equals(action)) { long request_id = intent.getLongExtra("request_id", -1); ResponseCode response_code = ResponseCode.valueOf(intent.getIntExtra("response_code", -1)); Log.d(TAG, "Got RESPONSE_CODE with requestId: " + request_id + " responseCode: " + response_code); } else if ("com.android.vending.billing.IN_APP_NOTIFY".equals(action)) { String notification_id = intent.getStringExtra("notification_id"); EasyBilling.gotInAppNotify(notification_id); } else if ("com.android.vending.billing.PURCHASE_STATE_CHANGED".equals(action)) { String inapp_signed_data = intent.getStringExtra("inapp_signed_data"); String inapp_signature = intent.getStringExtra("inapp_signature"); EasyBilling.gotPurchaseStateChanged(inapp_signed_data, inapp_signature); } else { Log.e(TAG, "unexpected action: " + action); } } }
Java
package yuku.easybilling; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class BillingDbHelper extends SQLiteOpenHelper { public static final String TAG = BillingDbHelper.class.getSimpleName(); public BillingDbHelper(Context context) { super(context, "BillingDb", null, getVersionCode(context)); //$NON-NLS-1$ } @Override public void onOpen(SQLiteDatabase db) { // }; @Override public void onCreate(SQLiteDatabase db) { Log.d(TAG, "@@onCreate"); //$NON-NLS-1$ try { createTables(db); createIndexes(db); } catch (SQLException e) { Log.e(TAG, "onCreate db failed!", e); //$NON-NLS-1$ throw e; } } public void createTables(SQLiteDatabase db) { db.execSQL("create table if not exists Inventory ( " + "_id integer primary key autoincrement, " + //$NON-NLS-1$ "productId text, " + "amount integer" + ")"); db.execSQL("create table if not exists Orders ( " + "_id integer primary key autoincrement, " + //$NON-NLS-1$ "orderId text, " + "purchaseState integer " + ")"); db.execSQL("create table if not exists Changes ( " + "_id integer primary key autoincrement, " + //$NON-NLS-1$ "orderId text, " + "packageName text," + "productId text," + "purchaseTime integer," + "purchaseState integer," + "developerPayload text" + ")"); } public void createIndexes(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } public static int getVersionCode(Context context) { try { PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (NameNotFoundException e) { throw new RuntimeException("NameNotFoundException when querying own package. Should not happen", e); } } }
Java
package yuku.easybilling; import android.content.Context; import android.os.Bundle; import yuku.easybilling.BillingResult.CheckBillingSupportedResult; import yuku.easybilling.BillingResult.ConfirmNotificationsResult; import yuku.easybilling.BillingResult.GetPurchaseInformationResult; import yuku.easybilling.BillingResult.RequestPurchaseResult; import yuku.easybilling.BillingResult.RestoreTransactionsResult; public abstract class BillingRequest { public static final String TAG = BillingRequest.class.getSimpleName(); private final Context context; public static class CheckBillingSupportedRequest extends BillingRequest { public CheckBillingSupportedRequest(Context context) { super(context); } @Override public Bundle getRequestBundle() { Bundle res = makeRequestBundle("CHECK_BILLING_SUPPORTED"); return res; } @Override public CheckBillingSupportedResult parseResultBundle(Bundle resultBundle) { CheckBillingSupportedResult res = new CheckBillingSupportedResult(); res.responseCode = getResponseCodeFromResultBundle(resultBundle); return res; } } public static class RequestPurchaseRequest extends BillingRequest { private final String itemId; private final String optionalDeveloperPayload; public RequestPurchaseRequest(Context context, String itemId, String optionalDeveloperPayload) { super(context); this.itemId = itemId; this.optionalDeveloperPayload = optionalDeveloperPayload; } @Override public Bundle getRequestBundle() { Bundle res = makeRequestBundle("REQUEST_PURCHASE"); res.putString("ITEM_ID", itemId); if (optionalDeveloperPayload != null) res.putString("DEVELOPER_PAYLOAD", optionalDeveloperPayload); return res; } @Override public RequestPurchaseResult parseResultBundle(Bundle resultBundle) { RequestPurchaseResult res = new RequestPurchaseResult(); res.responseCode = getResponseCodeFromResultBundle(resultBundle); res.requestId = resultBundle.getLong("REQUEST_ID"); res.purchaseIntent = resultBundle.getParcelable("PURCHASE_INTENT"); return res; } } public static class GetPurchaseInformationRequest extends BillingRequest { private final long nonce; private final String[] notifyIds; public GetPurchaseInformationRequest(Context context, long nonce, String[] notifyIds) { super(context); this.nonce = nonce; this.notifyIds = notifyIds; } // TODO fix android docs on type of notifyIds @Override public Bundle getRequestBundle() { Bundle res = makeRequestBundle("GET_PURCHASE_INFORMATION"); res.putLong("NONCE", nonce); res.putStringArray("NOTIFY_IDS", notifyIds); return res; } @Override public GetPurchaseInformationResult parseResultBundle(Bundle resultBundle) { GetPurchaseInformationResult res = new GetPurchaseInformationResult(); res.responseCode = getResponseCodeFromResultBundle(resultBundle); res.requestId = resultBundle.getLong("REQUEST_ID"); return res; } } public static class ConfirmNotificationsRequest extends BillingRequest { private final String[] notifyIds; public ConfirmNotificationsRequest(Context context, String[] notifyIds) { super(context); this.notifyIds = notifyIds; } @Override public Bundle getRequestBundle() { Bundle res = makeRequestBundle("CONFIRM_NOTIFICATIONS"); res.putStringArray("NOTIFY_IDS", notifyIds); return res; } @Override public ConfirmNotificationsResult parseResultBundle(Bundle resultBundle) { ConfirmNotificationsResult res = new ConfirmNotificationsResult(); res.responseCode = getResponseCodeFromResultBundle(resultBundle); res.requestId = resultBundle.getLong("REQUEST_ID"); return res; } } public static class RestoreTransactionsRequest extends BillingRequest { private final long nonce; public RestoreTransactionsRequest(Context context, long nonce) { super(context); this.nonce = nonce; } @Override public Bundle getRequestBundle() { Bundle res = makeRequestBundle("RESTORE_TRANSACTIONS"); res.putLong("NONCE", nonce); return res; } @Override public RestoreTransactionsResult parseResultBundle(Bundle resultBundle) { RestoreTransactionsResult res = new RestoreTransactionsResult(); res.responseCode = getResponseCodeFromResultBundle(resultBundle); res.requestId = resultBundle.getLong("REQUEST_ID"); return res; } } public BillingRequest(Context context) { this.context = context; } public abstract Bundle getRequestBundle(); public abstract <T extends BillingResult> BillingResult parseResultBundle(Bundle resultBundle); protected Bundle makeRequestBundle(String method) { Bundle request = new Bundle(); request.putString("BILLING_REQUEST", method); request.putInt("API_VERSION", 1); request.putString("PACKAGE_NAME", context.getPackageName()); return request; } public static ResponseCode getResponseCodeFromResultBundle(Bundle resultBundle) { return ResponseCode.valueOf(resultBundle.getInt("RESPONSE_CODE", -1)); } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package yuku.easybilling; import android.text.TextUtils; import android.util.Base64; import android.util.Log; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * Security-related methods. For a secure implementation, all of this code * should be implemented on a server that communicates with the application on * the device. For the sake of simplicity and clarity of this example, this code * is included here and is executed on the device. If you must verify the * purchases on the phone, you should obfuscate this code to make it harder for * an attacker to replace the code with stubs that treat all purchases as * verified. */ public class BillingSecurity { private static final String TAG = "BillingService"; public static class SignedData { public long nonce; public List<Order> orders; public static class Order { public String notificationId; public String orderId; public String packageName; public String productId; public long purchaseTime; public PurchaseState purchaseState; public String developerPayload; } } /** * Verifies that the data was signed with the given signature. * * @param inapp_signed_data * the signed JSON string (signed, not encrypted) * @param inapp_signature * the signature for the data, signed with the private key */ static boolean verifySignedData(String inapp_signed_data, String inapp_signature) { if (!TextUtils.isEmpty(inapp_signature) && !TextUtils.isEmpty(inapp_signed_data)) { return verify(getPublicKey(), inapp_signed_data, inapp_signature); } return false; } static SignedData decodeSignedData(String inapp_signed_data) { SignedData res = new SignedData(); JSONObject jObject = null; try { jObject = new JSONObject(inapp_signed_data); } catch (JSONException e) { Log.e(TAG, "json error decoding: " + jObject, e); return null; } res.nonce = jObject.optLong("nonce"); JSONArray jTransactionsArray = jObject.optJSONArray("orders"); if (jTransactionsArray == null) { res.orders = new ArrayList<SignedData.Order>(0); } else { res.orders = new ArrayList<SignedData.Order>(jTransactionsArray.length()); } for (int i = 0; i < jTransactionsArray.length(); i++) { JSONObject jElement = jTransactionsArray.optJSONObject(i); SignedData.Order order = new SignedData.Order(); order.notificationId = jElement.optString("notificationId"); order.orderId = jElement.optString("orderId"); order.packageName = jElement.optString("packageName"); order.productId = jElement.optString("productId"); order.purchaseTime = jElement.optLong("purchaseTime"); order.purchaseState = PurchaseState.valueOf(jElement.optInt("purchaseState")); order.developerPayload = jElement.optString("developerPayload"); res.orders.add(order); } return res; } /** * Generates a PublicKey instance from a string containing the * Base64-encoded public key. * * @param encodedPublicKey * Base64-encoded public key * @throws IllegalArgumentException * if encodedPublicKey is invalid */ public static PublicKey getPublicKey() { try { byte[] decodedKey = Base64.decode(EasyBilling.base64Key, Base64.DEFAULT); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey)); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeySpecException e) { Log.e(TAG, "Invalid key specification."); throw new IllegalArgumentException(e); } } /** * Verifies that the signature from the server matches the computed * signature on the data. Returns true if the data is correctly signed. * * @param publicKey * public key associated with the developer account * @param inapp_signed_data * signed data from server * @param inapp_signature * server signature * @return true if the data and signature match */ public static boolean verify(PublicKey publicKey, String inapp_signed_data, String inapp_signature) { try { Signature sig = Signature.getInstance("SHA1withRSA"); sig.initVerify(publicKey); sig.update(inapp_signed_data.getBytes()); if (!sig.verify(Base64.decode(inapp_signature, Base64.DEFAULT))) { Log.e(TAG, "Signature verification failed."); return false; } return true; } catch (Exception e) { Log.e(TAG, "Verify got exception", e); return false; } } }
Java
package yuku.easybilling; public enum BillingRequestStatus { /** Got return value false when trying to bind to Google Play billing service */ BIND_ERROR, /** Got RemoteException when calling remote service method */ REMOTE_EXCEPTION, /** Return value delivered immediately */ IMMEDIATE, /** Return value delivered via listener because we need to bind to Google Play billing service first */ DELAYED, }
Java
package yuku.easybilling; import android.app.PendingIntent; class BillingResult { public static final String TAG = BillingResult.class.getSimpleName(); public ResponseCode responseCode; public static class CheckBillingSupportedResult extends BillingResult { } public static class RequestPurchaseResult extends BillingResult { public long requestId; public PendingIntent purchaseIntent; } public static class GetPurchaseInformationResult extends BillingResult { public long requestId; } public static class ConfirmNotificationsResult extends BillingResult { public long requestId; } public static class RestoreTransactionsResult extends BillingResult { public long requestId; } }
Java
package yuku.bintex; import java.io.*; public class BintexWriter { private final OutputStream os_; /** * Tambah hanya kalau manggil os_.write(*) Jangan tambah kalo ga. */ private int pos = 0; public BintexWriter(OutputStream os) { this.os_ = os; } public void writeShortString(String s) throws IOException { int len = s.length(); if (len > 255) { throw new IllegalArgumentException("string must not more than 255 chars. String is: " + s); //$NON-NLS-1$ } os_.write(len); pos += 1; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); writeChar(c); } } public void writeLongString(String s) throws IOException { writeInt(s.length()); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); writeChar(c); } } /** * Tulis pake 8-bit atau 16-bit * * byte pertama menentukan * 0x01 = 8 bit short * 0x02 = 16 bit short * 0x11 = 8 bit long * 0x12 = 16 bit long */ public void writeAutoString(String s) throws IOException { // cek dulu apa semuanya 8 bit boolean semua8bit = true; int len = s.length(); for (int i = 0; i < len; i++) { char c = s.charAt(i); if (c > 0xff) { semua8bit = false; break; } } if (len <= 255 && semua8bit) writeUint8(0x01); if (len > 255 && semua8bit) writeUint8(0x11); if (len <= 255 && !semua8bit) writeUint8(0x02); if (len > 255 && !semua8bit) writeUint8(0x12); if (len <= 255) { writeUint8(len); } else { writeInt(len); } if (semua8bit) { for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); writeUint8(c); } } else { for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); writeChar(c); } } } public void writeInt(int a) throws IOException { os_.write((a & 0xff000000) >> 24); os_.write((a & 0x00ff0000) >> 16); os_.write((a & 0x0000ff00) >> 8); os_.write((a & 0x000000ff) >> 0); pos += 4; } public void writeChar(char c) throws IOException { os_.write((c & 0xff00) >> 8); os_.write(c & 0x00ff); pos += 2; } public void writeUint8(int a) throws IOException { if (a < 0 || a > 255) { throw new IllegalArgumentException("uint8 must be 0 to 255"); //$NON-NLS-1$ } os_.write(a); pos += 1; } public void writeFloat(float f) throws IOException { int a = Float.floatToIntBits(f); writeInt(a); } public void writeRaw(byte[] buf) throws IOException { writeRaw(buf, 0, buf.length); } public void writeRaw(byte[] buf, int off, int len) throws IOException { os_.write(buf, off, len); pos += len; } public void close() throws IOException { os_.close(); } public int getPos() { return pos; } public OutputStream getOutputStream() { return new OutputStream() { @Override public void write(int oneByte) throws IOException { writeUint8(oneByte); } @Override public void write(byte[] buffer, int offset, int count) throws IOException { writeRaw(buffer, offset, count); } }; } }
Java
package yuku.bintex; import java.io.*; public class BintexReader { private final InputStream is_; private int pos_ = 0; private char[] buf = new char[1024]; // paling dikit 255 biar bisa shortstring public BintexReader(InputStream is) { this.is_ = is; } public String readShortString() throws IOException { int len = is_.read(); pos_++; if (len < 0) { throw new EOFException(); } else if (len == 0) { return ""; //$NON-NLS-1$ } // max len = 255, maka buf pasti cukup char[] _buf = this.buf; for (int i = 0; i < len; i++) { _buf[i] = readCharTanpaNaikPos(); } pos_ += len + len; return new String(_buf, 0, len); } public String readLongString() throws IOException { int len = readInt(); if (len == 0) { return ""; //$NON-NLS-1$ } if (len > buf.length) { this.buf = new char[len + 1024]; } char[] _buf = this.buf; for (int i = 0; i < len; i++) { _buf[i] = readCharTanpaNaikPos(); } pos_ += len + len; return new String(_buf, 0, len); } /** * Baca pake 8-bit atau 16-bit * * byte pertama menentukan * 0x01 = 8 bit short * 0x02 = 16 bit short * 0x11 = 8 bit long * 0x12 = 16 bit long */ public String readAutoString() throws IOException { int jenis = readUint8(); int len = 0; if (jenis == 0x01 || jenis == 0x02) { len = readUint8(); } else if (jenis == 0x11 || jenis == 0x12) { len = readInt(); } if (len > buf.length) { this.buf = new char[len + 1024]; } if (jenis == 0x01 || jenis == 0x11) { char[] _buf = this.buf; for (int i = 0; i < len; i++) { _buf[i] = (char) is_.read(); } pos_ += len; return new String(_buf, 0, len); } else if (jenis == 0x02 || jenis == 0x12) { char[] _buf = this.buf; for (int i = 0; i < len; i++) { _buf[i] = readCharTanpaNaikPos(); } pos_ += len + len; return new String(_buf, 0, len); } else { return null; } } public int readInt() throws IOException { int res = (is_.read() << 24) | (is_.read() << 16) | (is_.read() << 8) | (is_.read()); pos_ += 4; return res; } public char readChar() throws IOException { char res = (char) ((is_.read() << 8) | (is_.read())); pos_ += 2; return res; } private char readCharTanpaNaikPos() throws IOException { return (char) ((is_.read() << 8) | (is_.read())); } public int readUint8() throws IOException { int res = is_.read(); pos_++; return res; } public float readFloat() throws IOException { int a = (is_.read() << 24) | (is_.read() << 16) | (is_.read() << 8) | (is_.read()); return Float.intBitsToFloat(a); } public long skip(long n) throws IOException { long res = is_.skip(n); pos_ += (int) res; return res; } public int getPos() { return pos_; } public void close() { try { is_.close(); } catch (IOException e) { e.printStackTrace(); } } }
Java
package yuku.multigesture; import yuku.multigesture.MultiGestureDetector.DragEvent; import yuku.multigesture.MultiGestureDetector.FlickEvent; import yuku.multigesture.MultiGestureDetector.PinchEvent; import yuku.multigesture.MultiGestureDetector.RotateEvent; import yuku.multigesture.MultiGestureDetector.TapEvent; public interface OnMultiGestureListener { void onDrag(DragEvent event); void onRotate(RotateEvent event); void onPinch(PinchEvent event); void onTap(TapEvent event); void onDoubleTap(TapEvent event); void onFlick(FlickEvent event); }
Java
package yuku.multigesture; import android.graphics.PointF; import android.util.FloatMath; import android.view.MotionEvent; import java.util.ArrayList; import java.util.Iterator; // Android Multi-Touch event demo // David Bouchard // http://www.deadpixel.ca public class MultiGestureDetector { // util methods impl by yuku public static float dist(float x1, float y1, float x2, float y2) { float dx = x1 - x2; float dy = y1 - y2; return FloatMath.sqrt(dx*dx + dy*dy); } // The main detector object final TouchProcessor touch; // listener private OnMultiGestureListener listener; // ------------------------------------------------------------------------------------- public MultiGestureDetector(float screenDensity) { touch = new TouchProcessor(screenDensity); } public OnMultiGestureListener getListener() { return listener; } public void setListener(OnMultiGestureListener listener) { this.listener = listener; } // ------------------------------------------------------------------------------------- public void draw() { // I do the analysis and event processing inside draw, since I found that on Android // trying to draw from outside the main thread can cause pretty serious screen flickering // devices // TODO touch.analyse(); touch.sendEvents(); } // ------------------------------------------------------------------------------------- // MULTI TOUCH EVENTS! void onTap(TapEvent event) { if (event.isSingleTap()) { if (listener != null) listener.onTap(event); } if (event.isDoubleTap()) { if (listener != null) listener.onDoubleTap(event); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void onFlick(FlickEvent event) { if (listener != null) listener.onFlick(event); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void onDrag(DragEvent event) { if (listener != null) listener.onDrag(event); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void onRotate(RotateEvent event) { if (listener != null) listener.onRotate(event); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void onPinch(PinchEvent event) { if (listener != null) listener.onPinch(event); } // ------------------------------------------------------------------------------------- // This is the stock Android touch event // modified by yuku public boolean onTouchEvent(MotionEvent event) { // extract the action code & the pointer ID int action = event.getAction(); int code = action & MotionEvent.ACTION_MASK; int index = action >> MotionEvent.ACTION_POINTER_ID_SHIFT; float x = event.getX(index); float y = event.getY(index); int id = event.getPointerId(index); // pass the events to the TouchProcessor if (code == MotionEvent.ACTION_DOWN || code == MotionEvent.ACTION_POINTER_DOWN) { touch.pointDown(x, y, id); } else if (code == MotionEvent.ACTION_UP || code == MotionEvent.ACTION_POINTER_UP) { touch.pointUp(event.getPointerId(index)); } else if (code == MotionEvent.ACTION_MOVE) { int numPointers = event.getPointerCount(); for (int i = 0; i < numPointers; i++) { id = event.getPointerId(i); x = event.getX(i); y = event.getY(i); touch.pointMoved(x, y, id); } } // immediately analyze and sendEvents touch.analyse(); touch.sendEvents(); return true; } // Event classes // ///////////////////////////////////////////////////////////////////////////////// public class TouchEvent { // empty base class to make event handling easier } // ///////////////////////////////////////////////////////////////////////////////// public class DragEvent extends TouchEvent { public float x; // position public float y; public float dx; // movement public float dy; public int numberOfPoints; DragEvent(float x, float y, float dx, float dy, int n) { this.x = x; this.y = y; this.dx = dx; this.dy = dy; numberOfPoints = n; } } // ///////////////////////////////////////////////////////////////////////////////// public class PinchEvent extends TouchEvent { public float centerX; public float centerY; public float amount; // in pixels public float scale; public int numberOfPoints; PinchEvent(float centerX, float centerY, float amount, float scale, int n) { this.centerX = centerX; this.centerY = centerY; this.amount = amount; this.scale = scale; this.numberOfPoints = n; } } // ///////////////////////////////////////////////////////////////////////////////// public class RotateEvent extends TouchEvent { public float centerX; public float centerY; public float angle; // delta, in radians public int numberOfPoints; RotateEvent(float centerX, float centerY, float angle, int n) { this.centerX = centerX; this.centerY = centerY; this.angle = angle; } } // ///////////////////////////////////////////////////////////////////////////////// public class TapEvent extends TouchEvent { public static final int SINGLE = 0; public static final int DOUBLE = 1; public float x; public float y; public int type; TapEvent(float x, float y, int type) { this.x = x; this.y = y; this.type = type; } public boolean isSingleTap() { return (type == SINGLE) ? true : false; } public boolean isDoubleTap() { return (type == DOUBLE) ? true : false; } } // ///////////////////////////////////////////////////////////////////////////////// public class FlickEvent extends TouchEvent { public float x; public float y; public PointF velocity; FlickEvent(float x, float y, PointF velocity) { this.x = x; this.y = y; this.velocity = velocity; } } class TouchPoint { public float x; public float y; public float px; public float py; public int id; // used for gesture detection float angle; float oldAngle; float pinch; float oldPinch; // ------------------------------------------------------------------------------------- TouchPoint(float x, float y, int id) { this.x = x; this.y = y; this.px = x; this.py = y; this.id = id; } // ------------------------------------------------------------------------------------- public void update(float x, float y) { px = this.x; py = this.y; this.x = x; this.y = y; } // ------------------------------------------------------------------------------------- public void initGestureData(float cx, float cy) { pinch = oldPinch = dist(x, y, cx, cy); angle = oldAngle = (float) Math.atan2((y - cy), (x - cx)); } // ------------------------------------------------------------------------------------- // delta x -- int to get rid of some noise public int dx() { return (int) (x - px); } // ------------------------------------------------------------------------------------- // delta y -- int to get rid of some noise public int dy() { return (int) (y - py); } // ------------------------------------------------------------------------------------- public void setAngle(float angle) { oldAngle = this.angle; this.angle = angle; } // ------------------------------------------------------------------------------------- public void setPinch(float pinch) { oldPinch = this.pinch; this.pinch = pinch; } } // TODO: make distance thershold based on pixel density information! class TouchProcessor { // heuristic constants int DOUBLE_TAP_DIST_THRESHOLD = 30; int FLICK_VELOCITY_THRESHOLD = 20; float MAX_MULTI_DRAG_DISTANCE = 100; // from the centroid // A list of currently active touch points ArrayList<TouchPoint> touchPoints; // Used for tap/doubletaps TouchPoint firstTap; TouchPoint secondTap; long tap; int tapCount = 0; // Events to be broadcast to the sketch ArrayList<TouchEvent> events; // centroid information float cx, cy; float old_cx, old_cy; boolean pointsChanged = false; // ------------------------------------------------------------------------------------- public TouchProcessor(float screenDensity) { touchPoints = new ArrayList<TouchPoint>(); events = new ArrayList<TouchEvent>(); DOUBLE_TAP_DIST_THRESHOLD *= screenDensity; FLICK_VELOCITY_THRESHOLD *= screenDensity; MAX_MULTI_DRAG_DISTANCE *= screenDensity; } // ------------------------------------------------------------------------------------- // Point Update functions public synchronized void pointDown(float x, float y, int id) { TouchPoint p = new TouchPoint(x, y, id); touchPoints.add(p); updateCentroid(); if (touchPoints.size() >= 2) { p.initGestureData(cx, cy); if (touchPoints.size() == 2) { // if this is the second point, we now have a valid centroid to update the first point TouchPoint frst = (TouchPoint) touchPoints.get(0); frst.initGestureData(cx, cy); } } // tap detection if (tapCount == 0) { firstTap = p; } if (tapCount == 1) { secondTap = p; } tap = System.currentTimeMillis(); pointsChanged = true; } // ------------------------------------------------------------------------------------- public synchronized void pointUp(int id) { TouchPoint p = getPoint(id); touchPoints.remove(p); // tap detection // TODO: handle a long press event here? if (p == firstTap || p == secondTap) { // this could be either a Tap or a Flick gesture, based on movement float d = dist(p.x, p.y, p.px, p.py); if (d > FLICK_VELOCITY_THRESHOLD) { FlickEvent event = new FlickEvent(p.px, p.py, new PointF(p.x - p.px, p.y - p.py)); events.add(event); } else { // long interval = System.currentTimeMillis() - tap; tapCount++; } } pointsChanged = true; } // ------------------------------------------------------------------------------------- public synchronized void pointMoved(float x, float y, int id) { TouchPoint p = getPoint(id); p.update(x, y); // since the events will be in sync with draw(), we just wait until analyse() to // look for gestures pointsChanged = true; } // ------------------------------------------------------------------------------------- // Calculate the centroid of all active points public void updateCentroid() { old_cx = cx; old_cy = cy; cx = 0; cy = 0; for (int i = 0; i < touchPoints.size(); i++) { TouchPoint p = (TouchPoint) touchPoints.get(i); cx += p.x; cy += p.y; } cx /= touchPoints.size(); cy /= touchPoints.size(); } // ------------------------------------------------------------------------------------- public synchronized void analyse() { handleTaps(); // simple event priority rule: do not try to rotate or pinch while dragging // this gets rid of a lot of jittery events if (pointsChanged) { updateCentroid(); if (handleDrag()) { // we have handled drag, reset tap/doubletap firstTap = secondTap = null; tapCount = 0; } else { boolean ret1 = handleRotation(); boolean ret2 = handlePinch(); if (ret1 || ret2) { // we have handled rotation or pinch, reset tap/doubletap firstTap = secondTap = null; tapCount = 0; } } pointsChanged = false; } } // ------------------------------------------------------------------------------------- // send events to the sketch public void sendEvents() { for (int i = 0; i < events.size(); i++) { TouchEvent e = (TouchEvent) events.get(i); if (e instanceof TapEvent) onTap((TapEvent) e); else if (e instanceof FlickEvent) onFlick((FlickEvent) e); else if (e instanceof DragEvent) onDrag((DragEvent) e); else if (e instanceof PinchEvent) onPinch((PinchEvent) e); else if (e instanceof RotateEvent) onRotate((RotateEvent) e); } events.clear(); } // ------------------------------------------------------------------------------------- public void handleTaps() { if (tapCount == 2) { // check if the tap point has moved float d = dist(firstTap.x, firstTap.y, secondTap.x, secondTap.y); if (d > DOUBLE_TAP_DIST_THRESHOLD) { // if the two taps are apart, count them as two single taps // TapEvent event1 = new TapEvent(firstTap.x, firstTap.y, TapEvent.SINGLE); // onTap(event1); TapEvent event2 = new TapEvent(secondTap.x, secondTap.y, TapEvent.SINGLE); onTap(event2); } else { events.add(new TapEvent(firstTap.x, firstTap.y, TapEvent.DOUBLE)); } tapCount = 0; } else if (tapCount == 1) { // long interval = System.currentTimeMillis() - tap; // if (interval > TAP_TIMEOUT) { events.add(new TapEvent(firstTap.x, firstTap.y, TapEvent.SINGLE)); // tapCount = 0; // } } } // ------------------------------------------------------------------------------------- // rotation is the average angle change between each point and the centroid public boolean handleRotation() { if (touchPoints.size() < 2) return false; // look for rotation events float rotation = 0; for (int i = 0; i < touchPoints.size(); i++) { TouchPoint p = (TouchPoint) touchPoints.get(i); float angle = (float) Math.atan2(p.y - cy, p.x - cx); p.setAngle(angle); float delta = p.angle - p.oldAngle; if (delta > Math.PI) delta -= (float) Math.PI * 2.f; if (delta < -Math.PI) delta += (float) Math.PI * 2.f; rotation += delta; } rotation /= touchPoints.size(); if (rotation != 0) { events.add(new RotateEvent(cx, cy, rotation, touchPoints.size())); return true; } return false; } // ------------------------------------------------------------------------------------- // pinch is simply the average distance change from each points to the centroid public boolean handlePinch() { int ntouches = touchPoints.size(); if (ntouches < 2) return false; // look for pinch events float pinch = 0; float scalediff = 0.f; for (int i = 0; i < ntouches; i++) { TouchPoint p = touchPoints.get(i); float distance = dist(p.x, p.y, cx, cy); p.setPinch(distance); float delta = p.pinch - p.oldPinch; pinch += delta; scalediff += delta / distance; } pinch /= ntouches; scalediff /= ntouches; if (pinch != 0) { events.add(new PinchEvent(cx, cy, pinch, 1.f + scalediff, ntouches)); return true; } return false; } // ------------------------------------------------------------------------------------- public boolean handleDrag() { // look for multi-finger drag events // multi-drag is defined as all the fingers moving close-ish together in the same direction boolean x_drag = true; boolean y_drag = true; boolean clustered = false; int first_x_dir = 0; int first_y_dir = 0; for (int i = 0; i < touchPoints.size(); i++) { TouchPoint p = (TouchPoint) touchPoints.get(i); int x_dir = 0; int y_dir = 0; if (p.dx() > 0) x_dir = 1; if (p.dx() < 0) x_dir = -1; if (p.dy() > 0) y_dir = 1; if (p.dy() < 0) y_dir = -1; if (i == 0) { first_x_dir = x_dir; first_y_dir = y_dir; } else { if (first_x_dir != x_dir) x_drag = false; if (first_y_dir != y_dir) y_drag = false; } // if the point is stationary if (x_dir == 0) x_drag = false; if (y_dir == 0) y_drag = false; if (touchPoints.size() == 1) clustered = true; else { float distance = dist(p.x, p.y, cx, cy); if (distance < MAX_MULTI_DRAG_DISTANCE) { clustered = true; } } } if ((x_drag || y_drag) && clustered) { if (touchPoints.size() == 1) { TouchPoint p = (TouchPoint) touchPoints.get(0); // use the centroid to calculate the position and delta of this drag event events.add(new DragEvent(p.x, p.y, p.dx(), p.dy(), 1)); } else { // use the centroid to calculate the position and delta of this drag event events.add(new DragEvent(cx, cy, cx - old_cx, cy - old_cy, touchPoints.size())); } return true; } return false; } // ------------------------------------------------------------------------------------- @SuppressWarnings("unchecked") public synchronized ArrayList<TouchPoint> getPoints() { return (ArrayList<TouchPoint>) touchPoints.clone(); } // ------------------------------------------------------------------------------------- public synchronized TouchPoint getPoint(int pid) { Iterator<TouchPoint> i = touchPoints.iterator(); while (i.hasNext()) { TouchPoint tp = (TouchPoint) i.next(); if (tp.id == pid) return tp; } return null; } } }
Java
package yuku.multigesture; import yuku.multigesture.MultiGestureDetector.DragEvent; import yuku.multigesture.MultiGestureDetector.FlickEvent; import yuku.multigesture.MultiGestureDetector.PinchEvent; import yuku.multigesture.MultiGestureDetector.RotateEvent; import yuku.multigesture.MultiGestureDetector.TapEvent; public class SimpleOnMultiGestureListener implements OnMultiGestureListener { public static final String TAG = SimpleOnMultiGestureListener.class.getSimpleName(); @Override public void onDrag(DragEvent event) { } @Override public void onRotate(RotateEvent event) { } @Override public void onPinch(PinchEvent event) { } @Override public void onTap(TapEvent event) { } @Override public void onDoubleTap(TapEvent event) { } @Override public void onFlick(FlickEvent event) { } }
Java
package yuku.kirimfidbek; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Build; import android.os.Build.VERSION; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import yuku.capjempol.HitungCapJempol; public class PengirimFidbek { public static final String TAG = "KirimFidbek"; //$NON-NLS-1$ public static interface OnSuccessListener { void onSuccess(byte[] response); } static class Entri { String isi; int versionCode; int timestamp; String versionSdk; String capjempol; public Entri(String isi, int versionCode, int timestamp, String versionSdk, String capjempol) { this.isi = isi; this.versionCode = versionCode; this.timestamp = timestamp; this.versionSdk = versionSdk; this.capjempol = capjempol; } } final Context context_; final SharedPreferences offlineBuffer_; TangkapSemuaEror tangkapSemuaEror_; List<Entri> xentri_; OnSuccessListener onSuccessListener_ = null; boolean lagiKirim_ = false; public PengirimFidbek(Context context, SharedPreferences offlineBuffer) { context_ = context; offlineBuffer_ = offlineBuffer; getUniqueId(); // picu pembuatan uniqueId. } public void setOnSuccessListener(OnSuccessListener onSuccessListener) { onSuccessListener_ = onSuccessListener; } public void activateDefaultUncaughtExceptionHandler() { tangkapSemuaEror_ = new TangkapSemuaEror(this); tangkapSemuaEror_.aktifkan(); } public void tambah(String isi) { muat(); xentri_.add(new Entri(isi, getVersionCode(), getTimestamp(), getVersionSdk(), HitungCapJempol.hitung(context_))); simpan(); } int getTimestamp() { return (int)(new Date().getTime() / 1000L); } synchronized void simpan() { if (xentri_ == null) return; Editor editor = offlineBuffer_.edit(); { editor.putInt("nfidbek", xentri_.size()); //$NON-NLS-1$ for (int i = 0; i < xentri_.size(); i++) { Entri entri = xentri_.get(i); editor.putString("fidbek/" + i + "/isi", entri.isi); //$NON-NLS-1$ //$NON-NLS-2$ editor.putInt("fidbek/" + i + "/versionCode", entri.versionCode); //$NON-NLS-1$ //$NON-NLS-2$ editor.putInt("fidbek/" + i + "/timestamp", entri.timestamp); //$NON-NLS-1$ //$NON-NLS-2$ editor.putString("fidbek/" + i + "/versionSdk", entri.versionSdk); //$NON-NLS-1$ //$NON-NLS-2$ editor.putString("fidbek/" + i + "/capjempol", entri.capjempol); //$NON-NLS-1$ //$NON-NLS-2$ } } editor.commit(); } public synchronized void cobaKirim() { muat(); if (lagiKirim_ || xentri_.size() == 0) return; lagiKirim_ = true; new Pengirim().start(); } synchronized void muat() { if (xentri_ == null) { xentri_ = new ArrayList<Entri>(); int nfidbek = offlineBuffer_.getInt("nfidbek", 0); //$NON-NLS-1$ for (int i = 0; i < nfidbek; i++) { String isi = offlineBuffer_.getString("fidbek/" + i + "/isi", null); //$NON-NLS-1$ //$NON-NLS-2$ int versionCode = offlineBuffer_.getInt("fidbek/" + i + "/versionCode", 0); //$NON-NLS-1$ //$NON-NLS-2$ int timestamp = offlineBuffer_.getInt("fidbek/" + i + "/timestamp", 0); //$NON-NLS-1$ //$NON-NLS-2$ String versionSdk = offlineBuffer_.getString("fidbek/" + i + "/versionSdk", "0"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ String capjempol = offlineBuffer_.getString("fidbek/" + i + "/capjempol", null); //$NON-NLS-1$ //$NON-NLS-2$ xentri_.add(new Entri(isi, versionCode, timestamp, versionSdk, capjempol)); } } } class Pengirim extends Thread { public Pengirim() { } @Override public void run() { boolean berhasil = false; Log.d(TAG, "tred pengirim dimulai. thread id = " + getId()); //$NON-NLS-1$ try { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://www.kejut.com/prog/android/fidbek/kirim3.php"); //$NON-NLS-1$ ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); for (Entri entri: xentri_) { params.add(new BasicNameValuePair("uniqueId[]", getUniqueId())); //$NON-NLS-1$ params.add(new BasicNameValuePair("package_name[]", context_.getPackageName())); //$NON-NLS-1$ params.add(new BasicNameValuePair("fidbek_isi[]", entri.isi)); //$NON-NLS-1$ params.add(new BasicNameValuePair("package_versionCode[]", String.valueOf(entri.versionCode))); //$NON-NLS-1$ params.add(new BasicNameValuePair("timestamp[]", String.valueOf(entri.timestamp))); //$NON-NLS-1$ params.add(new BasicNameValuePair("build_product[]", getBuildProduct())); //$NON-NLS-1$ params.add(new BasicNameValuePair("build_device[]", getBuildDevice())); //$NON-NLS-1$ params.add(new BasicNameValuePair("version_sdk[]", entri.versionSdk)); //$NON-NLS-1$ params.add(new BasicNameValuePair("capjempol[]", entri.capjempol)); //$NON-NLS-1$ } post.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //$NON-NLS-1$ HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); while (true) { byte[] b = new byte[4096]; int read = content.read(b); if (read <= 0) break; baos.write(b, 0, read); } byte[] out = baos.toByteArray(); if (out.length >= 2 && out[0] == 'O' && out[1] == 'K') { berhasil = true; } if (onSuccessListener_ != null) { onSuccessListener_.onSuccess(out); } } catch (IOException e) { Log.w(TAG, "waktu post", e); //$NON-NLS-1$ } if (berhasil) { synchronized (PengirimFidbek.this) { xentri_.clear(); } simpan(); } Log.d(TAG, "tred pengirim selesai. berhasil = " + berhasil); //$NON-NLS-1$ lagiKirim_ = false; } } int getVersionCode() { int versionCode = 0; try { versionCode = context_.getPackageManager().getPackageInfo(context_.getPackageName(), 0).versionCode; } catch (NameNotFoundException e) { Log.w(TAG, "package get versioncode", e); //$NON-NLS-1$ } return versionCode; } String getBuildProduct() { return Build.PRODUCT; } String getBuildDevice() { return Build.DEVICE; } String getUniqueId() { String uniqueId = offlineBuffer_.getString("fidbek_uniqueId", null); //$NON-NLS-1$ if (uniqueId == null) { uniqueId = "u2:" + UUID.randomUUID().toString(); //$NON-NLS-1$ offlineBuffer_.edit().putString("fidbek_uniqueId", uniqueId).commit(); //$NON-NLS-1$ } return uniqueId; } String getVersionSdk() { return VERSION.SDK; } }
Java
package yuku.kirimfidbek; import android.os.SystemClock; import android.util.Log; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.Thread.UncaughtExceptionHandler; public class TangkapSemuaEror { public static final String TAG = TangkapSemuaEror.class.getSimpleName(); //$NON-NLS-1$ final PengirimFidbek pengirimFidbek_; private UncaughtExceptionHandler defaultUEH_; private UncaughtExceptionHandler handler_ = new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { StringWriter sw = new StringWriter(4000); e.printStackTrace(new PrintWriter(sw, true)); String pesanDueh = "[DUEH2] thread: " + t.getName() + " (" + t.getId() + ") " + e.getClass().getName() + ": " + e.getMessage() + "\n" + sw.toString(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ Log.w(TAG, pesanDueh); pengirimFidbek_.tambah(pesanDueh); pengirimFidbek_.cobaKirim(); // Coba tunggu 3 detik sebelum ancur. Ato ancur aja ya? SystemClock.sleep(3000); Log.w(TAG, "DUEH selesai."); //$NON-NLS-1$ // panggil yang lama (dialog force close) if (defaultUEH_ != null) { defaultUEH_.uncaughtException(t, e); } } }; TangkapSemuaEror(PengirimFidbek pengirimFidbek) { pengirimFidbek_ = pengirimFidbek; } public void aktifkan() { defaultUEH_ = Thread.getDefaultUncaughtExceptionHandler(); Log.d(TAG, "defaultUEH_: " + defaultUEH_); Thread.setDefaultUncaughtExceptionHandler(handler_); } }
Java
package yuku.capjempol; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.Signature; import java.io.UnsupportedEncodingException; public class HitungCapJempol { public static final String TAG = HitungCapJempol.class.getSimpleName(); public static String hitung(Context context) { String packageName = context.getPackageName(); PackageInfo packageInfo; try { packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES); } catch (NameNotFoundException e) { e.printStackTrace(); return null; } Signature[] signatures = packageInfo.signatures; if (signatures == null || signatures.length == 0) return null; try { Signature s = signatures[0]; int yrc_s = yrc1(s.toByteArray(), 0); int yrc_p = yrc1(packageName.getBytes("utf-8"), yrc_s); return String.format("c1:y1:%08x:%08x", yrc_s, yrc_p); } catch (UnsupportedEncodingException e) { return null; } } private static int yrc1(byte[] bytes, int initial) { int res = initial; // initial must only be 30 bit for (byte b: bytes) { int n = b & 0xff; // cast to unsigned // rotate left by 3 bit int l = res & 0x07ffffff; // last 27 bit int f = res & 0x38000000; // first 3 bit after 2 empty bit res = (l << 3) | (f >> 27); res += n + 1; // might be 31 bit res &= 0x3fffffff; // take 30 bit only } return res; } }
Java
package yuku.ambilwarna.dicoba; import yuku.ambilwarna.*; import android.app.*; import android.os.*; import android.view.*; import android.widget.*; public class CobaAmbilWarnaActivity extends Activity { int warna = 0xffffff00; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); findViewById(R.id.Button01).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AmbilWarnaDialog dialog = new AmbilWarnaDialog(CobaAmbilWarnaActivity.this, warna, new AmbilWarnaDialog.OnAmbilWarnaListener() { @Override public void onOk(AmbilWarnaDialog dialog, int color) { Toast.makeText(getApplicationContext(), "ok color=0x" + Integer.toHexString(color), Toast.LENGTH_SHORT).show(); warna = color; } @Override public void onCancel(AmbilWarnaDialog dialog) { Toast.makeText(getApplicationContext(), "cancel", Toast.LENGTH_SHORT).show(); } }); dialog.show(); } }); } }
Java
package yuku.afw.storage; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import yuku.afw.App; public abstract class InternalDbHelper extends SQLiteOpenHelper { public static final String TAG = InternalDbHelper.class.getSimpleName(); public InternalDbHelper() { super(App.context, "InternalDb", null, App.getVersionCode()); //$NON-NLS-1$ } @Override public void onOpen(SQLiteDatabase db) { // }; @Override public void onCreate(SQLiteDatabase db) { Log.d(TAG, "onCreate called"); //$NON-NLS-1$ try { createTables(db); createIndexes(db); } catch (SQLException e) { Log.e(TAG, "onCreate db failed!", e); //$NON-NLS-1$ throw e; } } public abstract void createTables(SQLiteDatabase db); public abstract void createIndexes(SQLiteDatabase db); @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
Java
package yuku.afw.storage; public class InternalDb { public static final String TAG = InternalDb.class.getSimpleName(); protected final InternalDbHelper helper; public InternalDb(InternalDbHelper helper) { this.helper = helper; } }
Java
package yuku.afw.storage; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.SystemClock; import android.preference.PreferenceManager; import android.util.Log; import java.util.HashSet; import java.util.Map; import java.util.Set; import yuku.afw.App; import yuku.afw.D; public class Preferences { private static final String TAG = Preferences.class.getSimpleName(); private static SharedPreferences cache; private static boolean dirty = true; private static Editor currentEditor; private static int held = 0; public static void invalidate() { dirty = true; } private static Editor getEditor(SharedPreferences pref) { if (currentEditor == null) { currentEditor = pref.edit(); } return currentEditor; } public static int getInt(Enum<?> key, int def) { return getInt(key.toString(), def); } public static int getInt(String key, int def) { SharedPreferences pref = read(); return pref.getInt(key, def); } public static float getFloat(Enum<?> key, float def) { SharedPreferences pref = read(); return pref.getFloat(key.toString(), def); } public static long getLong(Enum<?> key, long def) { return getLong(key.toString(), def); } public static long getLong(String key, long def) { SharedPreferences pref = read(); return pref.getLong(key, def); } public static String getString(Enum<?> key, String def) { SharedPreferences pref = read(); return pref.getString(key.toString(), def); } public static boolean getBoolean(Enum<?> key, boolean def) { return getBoolean(key.toString(), def); } public static boolean getBoolean(String key, boolean def) { SharedPreferences pref = read(); return pref.getBoolean(key, def); } public static Map<String, ?> getAll() { SharedPreferences pref = read(); return pref.getAll(); } public static Set<String> getAllKeys() { return new HashSet<String>(getAll().keySet()); } public static void setInt(Enum<?> key, int val) { setInt(key.toString(), val); } public static void setInt(String key, int val) { SharedPreferences pref = read(); getEditor(pref).putInt(key, val); commitIfNotHeld(); Log.d(TAG, key + " = (int) " + val); //$NON-NLS-1$ } public static void setLong(Enum<?> key, long val) { setLong(key.toString(), val); } public static void setLong(String key, long val) { SharedPreferences pref = read(); getEditor(pref).putLong(key, val); commitIfNotHeld(); Log.d(TAG, key + " = (long) " + val); //$NON-NLS-1$ } public static void setString(Enum<?> key, String val) { setString(key.toString(), val); } public static void setString(String key, String val) { SharedPreferences pref = read(); getEditor(pref).putString(key, val); commitIfNotHeld(); Log.d(TAG, key + " = (string) " + val); //$NON-NLS-1$ } public static void setBoolean(Enum<?> key, boolean val) { setBoolean(key.toString(), val); } public static void setBoolean(String key, boolean val) { SharedPreferences pref = read(); getEditor(pref).putBoolean(key, val); commitIfNotHeld(); Log.d(TAG, key + " = (bool) " + val); //$NON-NLS-1$ } public static void remove(Enum<?> key) { remove(key.toString()); } public static void remove(String key) { SharedPreferences pref = read(); getEditor(pref).remove(key.toString()); commitIfNotHeld(); Log.d(TAG, key + " removed"); //$NON-NLS-1$ } private synchronized static void commitIfNotHeld() { if (held > 0) { // don't do anything now } else { if (currentEditor != null) { currentEditor.commit(); currentEditor = null; } } } public synchronized static void hold() { held++; } public synchronized static void unhold() { if (held <= 0) { throw new RuntimeException("unhold called too many times"); } held--; if (held == 0) { if (currentEditor != null) { currentEditor.commit(); currentEditor = null; } } } private synchronized static SharedPreferences read() { SharedPreferences res; if (dirty || cache == null) { long start = 0; if (D.EBUG) start = SystemClock.uptimeMillis(); res = PreferenceManager.getDefaultSharedPreferences(App.context); if (D.EBUG) Log.d(TAG, "Preferences was read from disk in ms: " + (SystemClock.uptimeMillis() - start)); //$NON-NLS-1$ dirty = false; cache = res; } else { res = cache; } return res; } }
Java
package yuku.afw.rpc; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.zip.GZIPInputStream; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import yuku.afw.rpc.Request.Method; import yuku.afw.rpc.Request.OptionsKey; import yuku.afw.rpc.Response.Validity; public class HttpPerformer { public static final String TAG = HttpPerformer.class.getSimpleName(); private final Request request; private final AsyncRequest<?>.Task<?> task; /** * @param task can be null if cancel is not supported */ public HttpPerformer(@NullOk AsyncRequest<?>.Task<?> task, Request request) { this.task = task; this.request = request; } public Response perform() { String url = request.url; DefaultHttpClient client = new DefaultHttpClient(); HttpParams httpParams = client.getParams(); if (request.options != null && request.options.get(OptionsKey.connectionTimeout) != null) { HttpConnectionParams.setConnectionTimeout(httpParams, (Integer) request.options.get(OptionsKey.connectionTimeout)); } else { HttpConnectionParams.setConnectionTimeout(httpParams, 30000); // 30 seconds for connection timeout } if (request.options != null && request.options.get(OptionsKey.soTimeout) != null) { HttpConnectionParams.setSoTimeout(httpParams, (Integer) request.options.get(OptionsKey.soTimeout)); } else { HttpConnectionParams.setSoTimeout(httpParams, 15000); // 15 seconds for waiting for data } ByteArrayOutputStream os = new ByteArrayOutputStream(256); // TODO make it more efficient by not buffering byte[] int httpResponseCode = 0; try { HttpRequestBase base = null; if (request.method == Method.GET || request.method == Method.GET_RAW) { url += request.params.toUrlEncodedStringWithOptionalQuestionMark(); base = new HttpGet(url); } else if (request.method == Method.GET_DIGEST) { client.getCredentialsProvider().setCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(request.params.getAndRemove("email"), request.params.getAndRemove("passwd"))); //$NON-NLS-1$//$NON-NLS-2$ url += request.params.toUrlEncodedStringWithOptionalQuestionMark(); base = new HttpGet(url); } else if (request.method == Method.POST) { HttpPost method = new HttpPost(url); // use params as usual ArrayList<NameValuePair> list = new ArrayList<NameValuePair>(); request.params.addAllTo(list); method.setEntity(new UrlEncodedFormEntity(list, "utf-8")); //$NON-NLS-1$ base = method; } else if (request.method == Method.DELETE) { url += request.params.toUrlEncodedStringWithOptionalQuestionMark(); base = new HttpDelete(url); } else { throw new RuntimeException("http method " + request.method + " not supported yet"); //$NON-NLS-1$ //$NON-NLS-2$ } request.headers.addTo(base); base.addHeader("Cache-Control", "no-cache"); //$NON-NLS-1$//$NON-NLS-2$ base.addHeader("Accept-Encoding", "gzip"); //$NON-NLS-1$ //$NON-NLS-2$ HttpResponse response = client.execute(base); httpResponseCode = response.getStatusLine().getStatusCode(); if (task != null && task.isCancelled()) { base.abort(); } else { Header encodingHeader = response.getFirstHeader("Content-Encoding"); //$NON-NLS-1$ HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); try { if (encodingHeader != null && encodingHeader.getValue().equalsIgnoreCase("gzip")) { //$NON-NLS-1$ content = new GZIPInputStream(content); } byte[] buf = new byte[4096 * 4]; while (true) { int read = content.read(buf); if (read <= 0) break; os.write(buf, 0, read); if (task != null && task.isCancelled()) { base.abort(); break; } } } finally { if (content != null) content.close(); } } } catch (IOException e) { Log.d(TAG, "IoError: " + e.getClass().getSimpleName() + ": " + e.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$ return new Response(this.request, Validity.IoError, e.getClass().getName() + ": " + e.getMessage()); //$NON-NLS-1$ } if (task != null && task.isCancelled()) { return new Response(this.request, Validity.Cancelled, "cancelled"); //$NON-NLS-1$ } return new Response(this.request, os.toByteArray(), httpResponseCode); } }
Java
package yuku.afw.rpc; import org.json.JSONObject; public interface JsonResponseDataProcessor { void processJsonResponse(JSONObject json); }
Java
package yuku.afw.rpc; import android.content.Context; import android.os.SystemClock; import android.util.Log; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import yuku.afw.D; public class UrlLoader { public static final String TAG = UrlLoader.class.getSimpleName(); static class Data { List<Listener> listeners; long startTime; } Map<String, Data> running = new LinkedHashMap<String, Data>(); public interface Listener { void onResponse(String url, Response response, BaseData data, boolean firstTime); } /** must call this from main thread */ public synchronized boolean load(Context context, final String url, ImageData imageData, Listener listener) { Data data = running.get(url); if (data == null) { // not running, create new final Data newData = new Data(); newData.startTime = SystemClock.uptimeMillis(); newData.listeners = new ArrayList<Listener>(4); newData.listeners.add(listener); // save running.put(url, newData); if (D.EBUG) Log.d(TAG, "Loading url: " + url + " creates a new request with 1 listener"); new AsyncRequest<ImageData>(new UrlImage(url), imageData) { @Override protected void onResponse(Response response, ImageData imageData) { long responseTime = SystemClock.uptimeMillis(); // call all listeners and remove from map try { boolean firstTime = true; for (int i = 0, len = newData.listeners.size(); i < len; i++) { newData.listeners.get(i).onResponse(url, response, imageData, firstTime); firstTime = false; } } finally { running.remove(url); long endTime = SystemClock.uptimeMillis(); if (D.EBUG) Log.d(UrlLoader.TAG, "Loading url: " + url + " finished. Loaded in " + (responseTime - newData.startTime) + " ms, callback in " + (endTime - responseTime) + " ms"); } }; }.start(); return true; } else { // just add listeners data.listeners.add(listener); if (D.EBUG) Log.d(TAG, "Loading url: " + url + " uses existing request, now it has " + data.listeners.size() + " listeners"); return false; } } private static class UrlImage extends Request { public UrlImage(String url) { super(Method.GET_RAW, url); } } }
Java
package yuku.afw.rpc; public abstract class BaseData { public static final String TAG = BaseData.class.getSimpleName(); public abstract boolean isSuccessResponse(Response response); public abstract ResponseProcessor getResponseProcessor(Response response); }
Java
package yuku.afw.rpc; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** Just to document that the parameter may be null */ @Retention(RetentionPolicy.SOURCE) @Target(ElementType.PARAMETER) public @interface NullOk { }
Java
package yuku.afw.rpc; import android.content.Context; import android.os.AsyncTask; import android.os.SystemClock; import android.util.Log; import android.util.SparseArray; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import yuku.afw.App; import yuku.afw.D; import yuku.afw.rpc.Response.Validity; /** * Listener tree: * - OnResponse * - OnSuccess * - OnFailed * - OnApiError * * When a listener returns false, the parent listener will be called. Otherwise no more listeners will be called. */ public class AsyncRequest<Z extends BaseData> { public static final String TAG = AsyncRequest.class.getSimpleName(); protected static List<OnLoadingStatusChangedListener> onLoadingStatusChangedListeners = new ArrayList<AsyncRequest.OnLoadingStatusChangedListener>(16); protected static AtomicInteger activeCount = new AtomicInteger(0); protected static AtomicInteger serialNumber = new AtomicInteger(0); private static Object onLoadingStatusChangedListeners_lock = new Object(); public enum LoadingStatus { Start, Stop, } public interface OnLoadingStatusChangedListener { void onLoadingStatusChanged(LoadingStatus status, int activeCount); } protected void onSuccess(Response response, Z data) { } protected void onFailed(Response response, Z data) { } protected void onResponse(Response response, Z data) { } protected void onApiError(Response response, Z data) { } private final Request request; private Z data; private Task<Z> task; private SparseArray<Object> tags; private boolean finished = false; private int id; private boolean consumed; public AsyncRequest(Request request, Z data) { this.request = request; this.data = data; this.task = new Task<Z>(); this.id = serialNumber.incrementAndGet(); } public void cancel() { task.cancel(false); finished = true; } public synchronized void setTag(Object tag) { setTag(0, tag); } public synchronized void setTag(int id, Object tag) { if (tags == null) { tags = new SparseArray<Object>(2); } tags.put(id, tag); } public synchronized <T> T getTag() { return this.<T>getTag(0); } @SuppressWarnings("unchecked") public synchronized <T> T getTag(int id) { return (T) tags.get(id); } public class Task<Y> extends AsyncTask<Request, Integer, Void> { final Z return_data; // should be never null Response return_response; Request request; public Task() { return_data = AsyncRequest.this.data; } @Override protected Void doInBackground(Request... params) { request = params[0]; HttpPerformer httpPerformer = new HttpPerformer(this, request); if (D.EBUG) Log.d(TAG, "async start [" + id + "] (" + getActiveCount() + " active, total " + Thread.activeCount() + " threads) " + request.toString()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ return_response = httpPerformer.perform(); if (return_data.isSuccessResponse(return_response)) { ResponseProcessor rp = return_data.getResponseProcessor(return_response); try { rp.process(return_response.data); } catch (Exception e) { return_response.validity = Validity.ProcessError; Log.w(TAG, "Error during ResponseProcessor#process", e); } } return null; } @Override protected void onCancelled() { return_response = new Response(request, Validity.Cancelled, "cancelled from asynctask#onCancelled"); onPostExecute(null); //$NON-NLS-1$ } @Override protected void onPostExecute(Void result) { if (D.EBUG) Log.d(TAG, "async stop [" + id + "] response: " + return_response.toString()); //$NON-NLS-1$//$NON-NLS-2$ try { onReceiveResponse(return_response, return_data); } finally { trackStop(); } } } public static void trackStop() { int activeCount = AsyncRequest.activeCount.decrementAndGet(); synchronized (onLoadingStatusChangedListeners) { for (int i = 0, len = onLoadingStatusChangedListeners.size(); i < len; i++) { onLoadingStatusChangedListeners.get(i).onLoadingStatusChanged(LoadingStatus.Stop, activeCount); } } } protected void onReceiveResponse(Response response, Z data) { if (data.isSuccessResponse(response)) { onSuccess(response, data); } else { if (response.validity == Validity.IoError) { showErrorToastIfNoRecentErrorToast(App.context, "Network error"); } else if (response.validity == Validity.JsonError) { showErrorToastIfNoRecentErrorToast(App.context, "Response from network error"); } if (response.validity == Validity.Ok) { onApiError(response, data); } if (! consumed) { onFailed(response, data); } } if (! consumed) { onResponse(response, data); } this.finished = true; } private static long lastErrorToastTime = -1; private static void showErrorToastIfNoRecentErrorToast(Context context, String msg) { long now = SystemClock.uptimeMillis(); if (lastErrorToastTime == -1 || now - lastErrorToastTime > 2000L) { Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); lastErrorToastTime = now; } } public static void setLastErrorToastTime(long lastErrorToastTime) { AsyncRequest.lastErrorToastTime = lastErrorToastTime; } public AsyncRequest<Z> start() { trackStart(); task.execute(request); return this; } public static void trackStart() { int activeCount = AsyncRequest.activeCount.incrementAndGet(); synchronized (onLoadingStatusChangedListeners_lock) { for (int i = 0, len = onLoadingStatusChangedListeners.size(); i < len; i++) { onLoadingStatusChangedListeners.get(i).onLoadingStatusChanged(LoadingStatus.Start, activeCount); } } } public Request getRequest() { return request; } public static void addOnLoadingStatusChangedListener(OnLoadingStatusChangedListener onLoadingStatusChangedListener) { synchronized (onLoadingStatusChangedListeners_lock) { onLoadingStatusChangedListeners.add(onLoadingStatusChangedListener); } } public static void removeOnLoadingStatusChangedListener(OnLoadingStatusChangedListener onLoadingStatusChangedListener) { synchronized (onLoadingStatusChangedListeners_lock) { onLoadingStatusChangedListeners.remove(onLoadingStatusChangedListener); } } public static int getActiveCount() { return activeCount.get(); } /** * Used to determine if this request has no more effect and hence safe to do additional requests whose response * may conflict with the currently executing request's response. * @return true if this task has been returned with a response OR {@link #cancel()} has been called. */ public boolean isFinished() { return finished; } public boolean isCancelled() { return task.isCancelled(); } protected void consume() { consumed = true; } }
Java
package yuku.afw.rpc; import java.util.LinkedHashMap; import java.util.Map.Entry; import org.apache.http.client.methods.HttpRequestBase; public class Headers { public static final String TAG = Headers.class.getSimpleName(); LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(); public void put(String key, String value) { map.put(key, value); } public void put(String key, long value) { map.put(key, String.valueOf(value)); } public boolean has(String key) { return map.containsKey(key); } public void addTo(HttpRequestBase httpRequestBase) { for (Entry<String, String> entry: map.entrySet()) { httpRequestBase.addHeader(entry.getKey(), entry.getValue()); } } public void addDebugString(StringBuilder sb) { for (String key: map.keySet()) { String value = map.get(key); if (value.length() > 80) value = "(len=" + value.length() + ")" + value.substring(0, 78) + "..."; //$NON-NLS-1$ sb.append(' '); sb.append(key).append('=').append(value); } } }
Java
package yuku.afw.rpc; import yuku.afw.rpc.Request.Method; public class Response { public static final String TAG = Response.class.getSimpleName(); public enum Validity { Ok, Cancelled, JsonError, IoError, ProcessError, } public Validity validity; public final int code; public final Request request; public final String message; public final byte[] data; public Response(Request request, Validity validity, String message) { this.request = request; this.validity = validity; this.code = 0; this.message = message; this.data = null; } /** for {@link Method#GET_RAW} */ public Response(Request request, byte[] raw, int code) { this.request = request; this.validity = Validity.Ok; this.code = 0; this.message = null; this.data = raw; } @SuppressWarnings("unchecked") public <T> T getData() { return (T) data; } @Override public String toString() { return "Response{" + validity + " " + code + " message=" + message + " data=" + (data == null? "null": "len " + data.length) + "}"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } }
Java
package yuku.afw.rpc; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import android.util.Log; import yuku.afw.D; public abstract class ImageData extends BaseData { public static final String TAG = ImageData.class.getSimpleName(); public Bitmap bitmap; public Options opts; public class ImageProcessor implements ResponseProcessor { private int maxPixels = 0; public void setMaxPixels(int maxPixels) { this.maxPixels = maxPixels; } @Override public void process(byte[] raw) throws Exception { opts = new Options(); if (maxPixels != 0) { opts.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(raw, 0, raw.length, opts); if (opts.outHeight == -1 || opts.outWidth == -1) { return; } int pixels = opts.outHeight * opts.outWidth; int downscale = 1; while (true) { if (D.EBUG) Log.d(TAG, "maxpixels: " + maxPixels + " pixels: " + pixels + " downscale: " + downscale + " pixels/downscale/downscale: " + (pixels / downscale / downscale)); if (pixels / downscale / downscale > maxPixels) { downscale++; } else { break; } if (downscale >= 10) { break; } } opts.inJustDecodeBounds = false; opts.inSampleSize = downscale; opts.outHeight = -1; opts.outWidth = -1; bitmap = BitmapFactory.decodeByteArray(raw, 0, raw.length, opts); } else { bitmap = BitmapFactory.decodeByteArray(raw, 0, raw.length, opts); } } } @Override public ResponseProcessor getResponseProcessor(Response response) { return new ImageProcessor(); } }
Java
package yuku.afw.rpc; public interface ResponseProcessor { public static final String TAG = ResponseProcessor.class.getSimpleName(); void process(byte[] raw) throws Exception; }
Java
package yuku.afw.rpc; public interface RawResponseDataProcessor { void processRawResponse(byte[] raw); }
Java
package yuku.afw.rpc; import android.net.Uri; import android.util.Log; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class Params { public static final String TAG = Params.class.getSimpleName(); private JSONObject map = new JSONObject(); public void put(String key, String value) { try { map.put(key, value); } catch (JSONException e) { Log.e(TAG, "json exception", e); //$NON-NLS-1$ } } public void put(String key, double value) { put(key, String.valueOf(value)); } public void put(String key, long value) { put(key, String.valueOf(value)); } public void put(String key, int value) { put(key, String.valueOf(value)); } public void put(String key, List<String> value) { JSONArray jsonArray = new JSONArray(value); try { map.put(key, jsonArray); } catch (JSONException e) { Log.e(TAG, "json exception", e); //$NON-NLS-1$ } } public void put(String key, JSONArray value) { try { map.put(key, value); } catch (JSONException e) { Log.e(TAG, "json exception", e); //$NON-NLS-1$ } } public String toJsonString() { return map.toString(); } public void addDebugString(StringBuilder sb) { JSONArray names = map.names(); if (names == null) return; for (int i = 0, len = names.length(); i < len; i++) { String key = names.optString(i); String value = map.optString(key); if (value.length() > 80) value = "(len=" + value.length() + ")" + value.substring(0, 78) + "..."; //$NON-NLS-1$ sb.append(' '); sb.append(key).append('=').append(value); } } public String toUrlEncodedString() { StringBuilder sb = new StringBuilder(256); addUrlEncodedParamsTo(sb); return sb.toString(); } public String toUrlEncodedStringWithOptionalQuestionMark() { if (map.length() == 0) { return ""; //$NON-NLS-1$ } StringBuilder sb = new StringBuilder(256); sb.append('?'); addUrlEncodedParamsTo(sb); return sb.toString(); } private void addUrlEncodedParamsTo(StringBuilder sb) { JSONArray names = map.names(); for (int i = 0, len = names.length(); i < len; i++) { String key = names.optString(i); String value = map.optString(key); if (sb.length() > 1) { // not (empty or contains only '?') sb.append('&'); } sb.append(key).append('=').append(Uri.encode(value)); } } public String getAndRemove(String key) { if (map.has(key)) { String value = map.optString(key); map.remove(key); return value; } return null; } public String get(String key) { if (map.has(key)) { return map.optString(key); } return null; } public JSONArray getJsonArray(String key) { if (map.has(key)) { return map.optJSONArray(key); } return null; } public void addAllTo(List<NameValuePair> list) { JSONArray names = map.names(); for (int i = 0, len = names.length(); i < len; i++) { String key = names.optString(i); String value = map.optString(key); list.add(new BasicNameValuePair(key, value)); } } }
Java
package yuku.afw.rpc; import java.util.EnumMap; public class Request { public static final String TAG = Request.class.getSimpleName(); public enum Method { GET, GET_DIGEST, GET_RAW, POST, DELETE, // no PUT because it can be replaced with POST } public enum OptionsKey { /** int, default 10000 (10 sec timeout) */ connectionTimeout, /** int, default 5000 (5 sec timeout) */ soTimeout, /** bool, default true (encapsulate in params) */ encapsulateParams, } public static class Options extends EnumMap<OptionsKey, Object> { public Options() { super(OptionsKey.class); } } public Method method; public String url; public Headers headers = new Headers(); public Params params = new Params(); public Options options; public Request(Method method, String path) { this.method = method; this.url = path; } @Override public String toString() { StringBuilder debugInfo = new StringBuilder(100); debugInfo.append(method.name()); debugInfo.append(' ').append(url).append(" params:"); //$NON-NLS-1$ params.addDebugString(debugInfo); debugInfo.append(" headers:"); //$NON-NLS-1$ headers.addDebugString(debugInfo); return debugInfo.toString(); } }
Java
package yuku.afw; import android.content.pm.ApplicationInfo; /** * Debug switch */ public class D { public static final String TAG = D.class.getSimpleName(); public static boolean EBUG; // value depends on the static init BELOW. static { if (App.context == null) { throw new RuntimeException("D is called before App. Something is wrong!"); } D.EBUG = ((App.context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0); } }
Java
package yuku.afw; import android.app.Activity; import android.view.View; public class V { public static final String TAG = V.class.getSimpleName(); @SuppressWarnings("unchecked") public static <T extends View> T get(View parent, int id) { return (T) parent.findViewById(id); } @SuppressWarnings("unchecked") public static <T extends View> T get(Activity activity, int id) { return (T) activity.findViewById(id); } }
Java
package yuku.afw.widget; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; public abstract class EasyAdapter extends BaseAdapter { public static final String TAG = EasyAdapter.class.getSimpleName(); @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = newView(position, parent); } bindView(convertView, position, parent); return convertView; } public abstract View newView(int position, ViewGroup parent); public abstract void bindView(View view, int position, ViewGroup parent); }
Java
package yuku.afw; import android.app.Application; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; public class App extends Application { public static final String TAG = App.class.getSimpleName(); public static Context context; @Override public void onCreate() { super.onCreate(); context = getApplicationContext(); } private static PackageInfo packageInfo; private static void initPackageInfo() { if (packageInfo == null) { try { packageInfo = App.context.getPackageManager().getPackageInfo(App.context.getPackageName(), 0); } catch (NameNotFoundException e) { throw new RuntimeException("NameNotFoundException when querying own package. Should not happen", e); } } } public static String getVersionName() { initPackageInfo(); return packageInfo.versionName; } public static int getVersionCode() { initPackageInfo(); return packageInfo.versionCode; } }
Java
package yuku.ambilwarna; import android.app.*; import android.content.*; import android.content.DialogInterface.OnCancelListener; import android.graphics.*; import android.view.*; import android.widget.*; public class AmbilWarnaDialog { public interface OnAmbilWarnaListener { void onCancel(AmbilWarnaDialog dialog); void onOk(AmbilWarnaDialog dialog, int color); } final AlertDialog dialog; final OnAmbilWarnaListener listener; final View viewHue; final AmbilWarnaKotak viewSatVal; final ImageView viewCursor; final View viewOldColor; final View viewNewColor; final ImageView viewTarget; final ViewGroup viewContainer; final float[] currentColorHsv = new float[3]; /** * create an AmbilWarnaDialog. call this only from OnCreateDialog() or from a background thread. * * @param context * current context * @param color * current color * @param listener * an OnAmbilWarnaListener, allowing you to get back error or */ public AmbilWarnaDialog(final Context context, int color, OnAmbilWarnaListener listener) { this.listener = listener; Color.colorToHSV(color, currentColorHsv); final View view = LayoutInflater.from(context).inflate(R.layout.ambilwarna_dialog, null); viewHue = view.findViewById(R.id.ambilwarna_viewHue); viewSatVal = (AmbilWarnaKotak) view.findViewById(R.id.ambilwarna_viewSatBri); viewCursor = (ImageView) view.findViewById(R.id.ambilwarna_cursor); viewOldColor = view.findViewById(R.id.ambilwarna_warnaLama); viewNewColor = view.findViewById(R.id.ambilwarna_warnaBaru); viewTarget = (ImageView) view.findViewById(R.id.ambilwarna_target); viewContainer = (ViewGroup) view.findViewById(R.id.ambilwarna_viewContainer); viewSatVal.setHue(getHue()); viewOldColor.setBackgroundColor(color); viewNewColor.setBackgroundColor(color); viewHue.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_UP) { float y = event.getY(); if (y < 0.f) y = 0.f; if (y > viewHue.getMeasuredHeight()) y = viewHue.getMeasuredHeight() - 0.001f; // to avoid looping from end to start. float hue = 360.f - 360.f / viewHue.getMeasuredHeight() * y; if (hue == 360.f) hue = 0.f; setHue(hue); // update view viewSatVal.setHue(getHue()); moveCursor(); viewNewColor.setBackgroundColor(getColor()); return true; } return false; } }); viewSatVal.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_UP) { float x = event.getX(); // touch event are in dp units. float y = event.getY(); if (x < 0.f) x = 0.f; if (x > viewSatVal.getMeasuredWidth()) x = viewSatVal.getMeasuredWidth(); if (y < 0.f) y = 0.f; if (y > viewSatVal.getMeasuredHeight()) y = viewSatVal.getMeasuredHeight(); setSat(1.f / viewSatVal.getMeasuredWidth() * x); setVal(1.f - (1.f / viewSatVal.getMeasuredHeight() * y)); // update view moveTarget(); viewNewColor.setBackgroundColor(getColor()); return true; } return false; } }); dialog = new AlertDialog.Builder(context) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (AmbilWarnaDialog.this.listener != null) { AmbilWarnaDialog.this.listener.onOk(AmbilWarnaDialog.this, getColor()); } } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (AmbilWarnaDialog.this.listener != null) { AmbilWarnaDialog.this.listener.onCancel(AmbilWarnaDialog.this); } } }) .setOnCancelListener(new OnCancelListener() { // if back button is used, call back our listener. @Override public void onCancel(DialogInterface paramDialogInterface) { if (AmbilWarnaDialog.this.listener != null) { AmbilWarnaDialog.this.listener.onCancel(AmbilWarnaDialog.this); } } }) .create(); // kill all padding from the dialog window dialog.setView(view, 0, 0, 0, 0); // move cursor & target on first draw ViewTreeObserver vto = view.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { moveCursor(); moveTarget(); view.getViewTreeObserver().removeGlobalOnLayoutListener(this); } }); } protected void moveCursor() { float y = viewHue.getMeasuredHeight() - (getHue() * viewHue.getMeasuredHeight() / 360.f); if (y == viewHue.getMeasuredHeight()) y = 0.f; RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) viewCursor.getLayoutParams(); layoutParams.leftMargin = (int) (viewHue.getLeft() - Math.floor(viewCursor.getMeasuredWidth() / 2) - viewContainer.getPaddingLeft()); ; layoutParams.topMargin = (int) (viewHue.getTop() + y - Math.floor(viewCursor.getMeasuredHeight() / 2) - viewContainer.getPaddingTop()); ; viewCursor.setLayoutParams(layoutParams); } protected void moveTarget() { float x = getSat() * viewSatVal.getMeasuredWidth(); float y = (1.f - getVal()) * viewSatVal.getMeasuredHeight(); RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) viewTarget.getLayoutParams(); layoutParams.leftMargin = (int) (viewSatVal.getLeft() + x - Math.floor(viewTarget.getMeasuredWidth() / 2) - viewContainer.getPaddingLeft()); layoutParams.topMargin = (int) (viewSatVal.getTop() + y - Math.floor(viewTarget.getMeasuredHeight() / 2) - viewContainer.getPaddingTop()); viewTarget.setLayoutParams(layoutParams); } private int getColor() { return Color.HSVToColor(currentColorHsv); } private float getHue() { return currentColorHsv[0]; } private float getSat() { return currentColorHsv[1]; } private float getVal() { return currentColorHsv[2]; } private void setHue(float hue) { currentColorHsv[0] = hue; } private void setSat(float sat) { currentColorHsv[1] = sat; } private void setVal(float val) { currentColorHsv[2] = val; } public void show() { dialog.show(); } public AlertDialog getDialog() { return dialog; } }
Java
package yuku.ambilwarna; import android.content.*; import android.graphics.*; import android.graphics.Shader.TileMode; import android.util.*; import android.view.*; public class AmbilWarnaKotak extends View { Paint paint; Shader luar; final float[] color = { 1.f, 1.f, 1.f }; public AmbilWarnaKotak(Context context, AttributeSet attrs) { super(context, attrs); } public AmbilWarnaKotak(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (paint == null) { paint = new Paint(); luar = new LinearGradient(0.f, 0.f, 0.f, this.getMeasuredHeight(), 0xffffffff, 0xff000000, TileMode.CLAMP); } int rgb = Color.HSVToColor(color); Shader dalam = new LinearGradient(0.f, 0.f, this.getMeasuredWidth(), 0.f, 0xffffffff, rgb, TileMode.CLAMP); ComposeShader shader = new ComposeShader(luar, dalam, PorterDuff.Mode.MULTIPLY); paint.setShader(shader); canvas.drawRect(0.f, 0.f, this.getMeasuredWidth(), this.getMeasuredHeight(), paint); } void setHue(float hue) { color[0] = hue; invalidate(); } }
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.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TaskOptions.Method; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * A servlet that pushes a GCM message to all registered devices. This servlet creates multicast * entities consisting of 1000 devices each, and creates tasks to send individual GCM messages to * each device in the multicast. * * This servlet must be authenticated against with an administrator's Google account, ideally a * shared role account. */ public class SendMessageToAllServlet extends BaseServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { Queue queue = QueueFactory.getQueue("MulticastMessagesQueue"); String announcement = req.getParameter("announcement"); if (announcement == null) { announcement = ""; } List<String> devices = Datastore.getDevices(); // must split in chunks of 1000 devices (GCM limit) int total = devices.size(); List<String> partialDevices = new ArrayList<String>(total); int counter = 0; for (String device : devices) { counter++; partialDevices.add(device); int partialSize = partialDevices.size(); if (partialSize == Datastore.MULTICAST_SIZE || counter == total) { String multicastKey = Datastore.createMulticast(partialDevices, announcement); logger.fine("Queuing " + partialSize + " devices on multicast " + multicastKey); TaskOptions taskOptions = TaskOptions.Builder .withUrl("/send") .param("multicastKey", multicastKey) .method(Method.POST); queue.add(taskOptions); partialDevices.clear(); } } logger.fine("Queued message to " + counter + " devices"); resp.sendRedirect("/success.html"); } }
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 java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * A servlet that shows a simple admin console for sending multicast messages. This servlet is * visible to administrators only. */ 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>"); int total = Datastore.getTotalDevices(); out.print("<h2>" + total + " device(s) registered!</h2>"); out.print("<form method='POST' action='/sendall'>"); out.print("<table>"); 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; import com.google.appengine.api.datastore.DatastoreService; 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 java.util.logging.Logger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * Context initializer that loads the API key from the App Engine datastore. */ public class ApiKeyInitializer implements ServletContextListener { private final Logger logger = Logger.getLogger(ApiKeyInitializer.class.getSimpleName()); // Don't actually hard code your key here; rather, edit the entity in the App Engine console. static final String FAKE_API_KEY = "ENTER_KEY_HERE"; 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"; @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, FAKE_API_KEY); datastore.put(entity); logger.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() { 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) { logger.severe("Exception while retrieving the API Key" + e.toString()); } return apiKey; } @Override public void contextDestroyed(ServletContextEvent event) { } }
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 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}. * * The client app should call this servlet every time 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 = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.register(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; 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}. The client app should call this servlet every time 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 = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.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; import com.google.appengine.api.datastore.DatastoreService; 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.FetchOptions; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Transaction; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; /** * Simple implementation of a data store using standard Java collections. This class is neither * persistent (it will lost the data when the app is restarted) nor thread safe. */ public final class Datastore { private static final Logger logger = Logger.getLogger(Datastore.class.getSimpleName()); static final String MULTICAST_TYPE = "Multicast"; static final String MULTICAST_REG_IDS_PROPERTY = "regIds"; static final String MULTICAST_ANNOUNCEMENT_PROPERTY = "announcement"; static final int MULTICAST_SIZE = 1000; static final String DEVICE_TYPE = "Device"; static final String DEVICE_REG_ID_PROPERTY = "regid"; private static final FetchOptions DEFAULT_FETCH_OPTIONS = FetchOptions.Builder .withPrefetchSize(MULTICAST_SIZE) .chunkSize(MULTICAST_SIZE); private static final DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); private Datastore() { throw new UnsupportedOperationException(); } /** * Registers a device. */ public static void register(String regId) { logger.info("Registering " + regId); Transaction txn = ds.beginTransaction(); try { Entity entity = findDeviceByRegId(regId); if (entity != null) { logger.fine(regId + " is already registered; ignoring."); return; } entity = new Entity(DEVICE_TYPE); entity.setProperty(DEVICE_REG_ID_PROPERTY, regId); ds.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Unregisters a device. */ public static void unregister(String regId) { logger.info("Unregistering " + regId); Transaction txn = ds.beginTransaction(); try { Entity entity = findDeviceByRegId(regId); if (entity == null) { logger.warning("Device " + regId + " already unregistered"); } else { Key key = entity.getKey(); ds.delete(key); } txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Updates the registration id of a device. */ public static void updateRegistration(String oldId, String newId) { logger.info("Updating " + oldId + " to " + newId); Transaction txn = ds.beginTransaction(); try { Entity entity = findDeviceByRegId(oldId); if (entity == null) { logger.warning("No device for registration id " + oldId); return; } entity.setProperty(DEVICE_REG_ID_PROPERTY, newId); ds.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Gets the number of total devices. */ public static int getTotalDevices() { Transaction txn = ds.beginTransaction(); try { Query query = new Query(DEVICE_TYPE).setKeysOnly(); List<Entity> allKeys = ds.prepare(query).asList(DEFAULT_FETCH_OPTIONS); int total = allKeys.size(); logger.fine("Total number of devices: " + total); txn.commit(); return total; } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Gets all registered devices. */ public static List<String> getDevices() { List<String> devices; Transaction txn = ds.beginTransaction(); try { Query query = new Query(DEVICE_TYPE); Iterable<Entity> entities = ds.prepare(query).asIterable(DEFAULT_FETCH_OPTIONS); devices = new ArrayList<String>(); for (Entity entity : entities) { String device = (String) entity.getProperty(DEVICE_REG_ID_PROPERTY); devices.add(device); } txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } return devices; } /** * Returns the device object with the given registration ID. */ private static Entity findDeviceByRegId(String regId) { Query query = new Query(DEVICE_TYPE) .addFilter(DEVICE_REG_ID_PROPERTY, FilterOperator.EQUAL, regId); PreparedQuery preparedQuery = ds.prepare(query); List<Entity> entities = preparedQuery.asList(DEFAULT_FETCH_OPTIONS); Entity entity = null; if (!entities.isEmpty()) { entity = entities.get(0); } int size = entities.size(); if (size > 0) { logger.severe( "Found " + size + " entities for regId " + regId + ": " + entities); } return entity; } /** * Creates a persistent record with the devices to be notified using a multicast message. * * @param devices registration ids of the devices. * @param announcement announcement messageage * @return encoded key for the persistent record. */ public static String createMulticast(List<String> devices, String announcement) { String type = (announcement == null || announcement.trim().length() == 0) ? "sync" : ("announcement: " + announcement); logger.info("Storing multicast (" + type + ") for " + devices.size() + " devices"); String encodedKey; Transaction txn = ds.beginTransaction(); try { Entity entity = new Entity(MULTICAST_TYPE); entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices); entity.setProperty(MULTICAST_ANNOUNCEMENT_PROPERTY, announcement); ds.put(entity); Key key = entity.getKey(); encodedKey = KeyFactory.keyToString(key); logger.fine("multicast key: " + encodedKey); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } return encodedKey; } /** * Gets a persistent record with the devices to be notified using a multicast message. * * @param encodedKey encoded key for the persistent record. */ public static Entity getMulticast(String encodedKey) { Key key = KeyFactory.stringToKey(encodedKey); Entity entity; Transaction txn = ds.beginTransaction(); try { entity = ds.get(key); txn.commit(); return entity; } catch (EntityNotFoundException e) { logger.severe("No entity for key " + key); return null; } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Updates a persistent record with the devices to be notified using a multicast message. * * @param encodedKey encoded key for the persistent record. * @param devices new list of registration ids of the devices. */ public static void updateMulticast(String encodedKey, List<String> devices) { Key key = KeyFactory.stringToKey(encodedKey); Entity entity; Transaction txn = ds.beginTransaction(); try { try { entity = ds.get(key); } catch (EntityNotFoundException e) { logger.severe("No entity for key " + key); return; } entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices); ds.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Deletes a persistent record with the devices to be notified using a multicast message. * * @param encodedKey encoded key for the persistent record. */ public static void deleteMulticast(String encodedKey) { Transaction txn = ds.beginTransaction(); try { Key key = KeyFactory.stringToKey(encodedKey); ds.delete(key); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } }
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 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. */ abstract class BaseServlet extends HttpServlet { protected final Logger logger = Logger.getLogger(getClass().getSimpleName()); protected String getParameter(HttpServletRequest req, String parameter) throws ServletException { String value = req.getParameter(parameter); if (value == null || value.trim().isEmpty()) { 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.info("parameters: " + parameters); throw new ServletException("Parameter " + parameter + " not found"); } return value.trim(); } protected void setSuccess(HttpServletResponse resp) { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/plain"); resp.setContentLength(0); } }
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.android.gcm.server.Constants; import com.google.android.gcm.server.Message; import com.google.android.gcm.server.MulticastResult; import com.google.android.gcm.server.Result; import com.google.android.gcm.server.Sender; import com.google.appengine.api.datastore.Entity; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet, called from an App Engine task, that sends the given message (sync or announcement) * to all devices in a given multicast group (up to 1000). */ public class SendMessageServlet extends BaseServlet { private static final int ANNOUNCEMENT_TTL = (int) TimeUnit.MINUTES.toSeconds(300); private Sender sender; @Override public void init(ServletConfig config) throws ServletException { super.init(config); sender = newSender(config); } /** * Creates the {@link Sender} based on the servlet settings. */ protected Sender newSender(ServletConfig config) { String key = (String) config.getServletContext() .getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY); return new Sender(key); } /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { String multicastKey = req.getParameter("multicastKey"); Entity multicast = Datastore.getMulticast(multicastKey); @SuppressWarnings("unchecked") List<String> devices = (List<String>) multicast.getProperty(Datastore.MULTICAST_REG_IDS_PROPERTY); String announcement = (String) multicast.getProperty(Datastore.MULTICAST_ANNOUNCEMENT_PROPERTY); // Build the GCM message Message.Builder builder = new Message.Builder() .delayWhileIdle(true); if (announcement != null && announcement.trim().length() > 0) { builder .collapseKey("announcement") .addData("announcement", announcement) .timeToLive(ANNOUNCEMENT_TTL); } else { builder .collapseKey("sync"); } Message message = builder.build(); // Send the GCM message. MulticastResult multicastResult; try { multicastResult = sender.sendNoRetry(message, devices); logger.info("Result: " + multicastResult); } catch (IOException e) { logger.log(Level.SEVERE, "Exception posting " + message, e); taskDone(resp, multicastKey); return; } // check if any registration ids 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); Datastore.updateRegistration(regId, canonicalRegId); } } } boolean allDone = true; if (multicastResult.getFailure() != 0) { // there were failures, check if any could be retried List<Result> results = multicastResult.getResults(); List<String> retryableRegIds = 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); logger.warning("Got error (" + error + ") for regId " + regId); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it Datastore.unregister(regId); } else if (error.equals(Constants.ERROR_UNAVAILABLE)) { retryableRegIds.add(regId); } } } if (!retryableRegIds.isEmpty()) { // update task Datastore.updateMulticast(multicastKey, retryableRegIds); allDone = false; retryTask(resp); } } if (allDone) { taskDone(resp, multicastKey); } 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, String multicastKey) { Datastore.deleteMulticast(multicastKey); resp.setStatus(200); } }
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.api.android.plus; import android.content.Context; import android.util.AttributeSet; import android.widget.Button; /** * Stub until the release of <a href="https://developers.google.com/android/google-play-services/"> * Google Play Services.</a> */ public final class PlusOneButton extends Button { public PlusOneButton(Context context) { super(context); } public PlusOneButton(Context context, AttributeSet attrs) { super(context, attrs); } public PlusOneButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void setUrl(String url) { } public void setSize(Size size) { } public enum Size { SMALL, MEDIUM, TALL, STANDARD } }
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.api.android.plus; import android.content.Context; /** * Stub until the release of <a href="https://developers.google.com/android/google-play-services/"> * Google Play Services.</a> */ public final class GooglePlus { public static GooglePlus initialize(Context context, String apiKey, String clientId) { return new GooglePlus(); } }
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.analytics.tracking.android; import android.app.Activity; import android.content.Context; /** * Temporarily just a stub. */ public class EasyTracker { public static EasyTracker getTracker() { return new EasyTracker(); } public void trackView(String s) { } public void trackActivityStart(Activity activity) { } public void trackActivityStop(Activity activity) { } public void setContext(Context context) { } public void trackEvent(String s1, String s2, String s3, long l) { } public void dispatch() { } }
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; import com.google.android.apps.iosched.Config; import com.google.android.gcm.GCMRegistrar; import android.content.Context; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Random; 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.LOGI; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Helper class used to communicate with the demo server. */ public final class ServerUtilities { private static final String TAG = makeLogTag("GCM"); private static final int MAX_ATTEMPTS = 5; private static final int BACKOFF_MILLIS = 2000; private static final Random sRandom = new Random(); /** * Register this account/device pair within the server. * * @param context Current context * @param regId The GCM registration ID for this device * @return whether the registration succeeded or not. */ public static boolean register(final Context context, final String regId) { LOGI(TAG, "registering device (regId = " + regId + ")"); String serverUrl = Config.GCM_SERVER_URL + "/register"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); long backoff = BACKOFF_MILLIS + sRandom.nextInt(1000); // Once GCM returns a registration id, we need to register it in the // demo server. As the server might be down, we will retry it a couple // times. for (int i = 1; i <= MAX_ATTEMPTS; i++) { LOGV(TAG, "Attempt #" + i + " to register"); try { post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, true); return true; } catch (IOException e) { // Here we are simplifying and retrying on any error; in a real // application, it should retry only on unrecoverable errors // (like HTTP error code 503). LOGE(TAG, "Failed to register on attempt " + i, e); if (i == MAX_ATTEMPTS) { break; } try { LOGV(TAG, "Sleeping for " + backoff + " ms before retry"); Thread.sleep(backoff); } catch (InterruptedException e1) { // Activity finished before we complete - exit. LOGD(TAG, "Thread interrupted: abort remaining retries!"); Thread.currentThread().interrupt(); return false; } // increase backoff exponentially backoff *= 2; } } return false; } /** * Unregister this account/device pair within the server. * * @param context Current context * @param regId The GCM registration ID for this device */ static void unregister(final Context context, final String regId) { LOGI(TAG, "unregistering device (regId = " + regId + ")"); String serverUrl = Config.GCM_SERVER_URL + "/unregister"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); try { post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, false); } catch (IOException e) { // At this point the device is unregistered from GCM, but still // registered in the server. // We could try to unregister again, but it is not necessary: // if the server tries to send a message to the device, it will get // a "NotRegistered" error message and should unregister the device. LOGD(TAG, "Unable to unregister from application server", e); } } /** * Issue a POST request to the server. * * @param endpoint POST address. * @param params request parameters. * @throws java.io.IOException propagated from POST. */ private static void post(String endpoint, Map<String, String> params) throws IOException { URL url; try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=') .append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); LOGV(TAG, "Posting '" + body + "' to " + url); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setChunkedStreamingMode(0); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); conn.setRequestProperty("Content-Length", Integer.toString(body.length())); // post the request OutputStream out = conn.getOutputStream(); out.write(body.getBytes()); out.close(); // handle the response int status = conn.getResponseCode(); if (status != 200) { throw new IOException("Post failed with error code " + status); } } finally { if (conn != null) { conn.disconnect(); } } } }
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; import com.google.android.gcm.GCMBroadcastReceiver; import android.content.Context; /** * @author trevorjohns@google.com (Trevor Johns) */ public class GCMRedirectedBroadcastReceiver extends GCMBroadcastReceiver { /** * Gets the class name of the intent service that will handle GCM messages. * * Used to override class name, so that GCMIntentService can live in a * subpackage. */ @Override protected String getGCMIntentServiceClassName(Context context) { return GCMIntentService.class.getCanonicalName(); } }
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; 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.sync.TriggerSyncReceiver; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.util.UIUtils; import com.google.android.gcm.GCMBaseIntentService; import com.google.android.gcm.GCMRegistrar; import android.app.AlarmManager; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import java.util.Random; 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.LOGI; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * {@link android.app.IntentService} responsible for handling GCM messages. */ public class GCMIntentService extends GCMBaseIntentService { private static final String TAG = makeLogTag("GCM"); private static final int TRIGGER_SYNC_MAX_JITTER_MILLIS = 3 * 60 * 1000; // 3 minutes private static final Random sRandom = new Random(); public GCMIntentService() { super(Config.GCM_SENDER_ID); } @Override protected void onRegistered(Context context, String regId) { LOGI(TAG, "Device registered: regId=" + regId); ServerUtilities.register(context, regId); } @Override protected void onUnregistered(Context context, String regId) { LOGI(TAG, "Device unregistered"); if (GCMRegistrar.isRegisteredOnServer(context)) { ServerUtilities.unregister(context, regId); } else { // This callback results from the call to unregister made on // ServerUtilities when the registration to the server failed. LOGD(TAG, "Ignoring unregister callback"); } } @Override protected void onMessage(Context context, Intent intent) { if (UIUtils.isGoogleTV(context)) { // Google TV uses SyncHelper directly. return; } String announcement = intent.getStringExtra("announcement"); if (announcement != null) { displayNotification(context, announcement); return; } int jitterMillis = (int) (sRandom.nextFloat() * TRIGGER_SYNC_MAX_JITTER_MILLIS); final String debugMessage = "Received message to trigger sync; " + "jitter = " + jitterMillis + "ms"; LOGI(TAG, debugMessage); if (BuildConfig.DEBUG) { displayNotification(context, debugMessage); } ((AlarmManager) context.getSystemService(ALARM_SERVICE)) .set( AlarmManager.RTC, System.currentTimeMillis() + jitterMillis, PendingIntent.getBroadcast( context, 0, new Intent(context, TriggerSyncReceiver.class), PendingIntent.FLAG_CANCEL_CURRENT)); } private void displayNotification(Context context, String message) { LOGI(TAG, "displayNotification: " + message); ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)) .notify(0, new NotificationCompat.Builder(context) .setWhen(System.currentTimeMillis()) .setSmallIcon(R.drawable.ic_stat_notification) .setTicker(message) .setContentTitle(context.getString(R.string.app_name)) .setContentText(message) .setContentIntent( PendingIntent.getActivity(context, 0, new Intent(context, HomeActivity.class) .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP), 0)) .setAutoCancel(true) .getNotification()); } @Override public void onError(Context context, String errorId) { LOGE(TAG, "Received error: " + errorId); } @Override protected boolean onRecoverableError(Context context, String errorId) { // log message LOGW(TAG, "Received recoverable error: " + errorId); return super.onRecoverableError(context, errorId); } }
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.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.ImageFetcher; import com.google.android.apps.iosched.util.UIUtils; import com.google.api.client.googleapis.services.GoogleKeyInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.http.json.JsonHttpRequestInitializer; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson.JacksonFactory; import com.google.api.services.plus.Plus; import com.google.api.services.plus.model.Activity; import com.google.api.services.plus.model.ActivityFeed; import com.actionbarsherlock.app.SherlockListFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.Color; import android.net.ParseException; import android.net.Uri; import android.os.Bundle; 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.Html; import android.text.TextUtils; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; 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 {@link WebView}-based fragment that shows Google+ public 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. * * <p>WARNING! This fragment uses the Google+ API, and is subject to quotas. If you expect to * write a wildly popular app based on this code, please check the * at <a href="https://developers.google.com/+/">Google+ Platform documentation</a> on latest * best practices and quota details. You can check your current quota at the * <a href="https://code.google.com/apis/console">APIs console</a>. */ public class SocialStreamFragment extends SherlockListFragment implements AbsListView.OnScrollListener, LoaderManager.LoaderCallbacks<List<Activity>> { private static final String TAG = makeLogTag(SocialStreamFragment.class); public static final String EXTRA_QUERY = "com.google.android.iosched.extra.QUERY"; 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 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 ImageFetcher mImageFetcher; @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; } mImageFetcher = UIUtils.getImageFetcher(getActivity()); setListAdapter(mStreamAdapter); 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); view.setBackgroundColor(Color.WHITE); final ListView listView = getListView(); listView.setCacheColorHint(Color.WHITE); listView.setOnScrollListener(this); listView.setDrawSelectorOnTop(true); TypedValue v = new TypedValue(); getActivity().getTheme().resolveAttribute(R.attr.activatableItemBackground, v, true); listView.setSelector(v.resourceId); } @Override public void onPause() { super.onPause(); mImageFetcher.setPauseWork(false); mImageFetcher.flushCache(); } @Override public void onDestroy() { super.onDestroy(); mImageFetcher.closeCache(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.social_stream, menu); super.onCreateOptionsMenu(menu, inflater); } @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().trackEvent("Home Screen Dashboard", "Click", "Post to Google+", 0L); LOGD("Tracker", "Home Screen Dashboard: Click, post to Google+"); return true; } return super.onOptionsItemSelected(item); } @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); UIUtils.safeOpenLink(getActivity(), postDetailIntent); } @Override public void onScrollStateChanged(AbsListView listView, int scrollState) { // Pause disk cache access to ensure smoother scrolling if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING || scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) { mImageFetcher.setPauseWork(true); } else { mImageFetcher.setPauseWork(false); } } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // Simple implementation of the infinite scrolling UI pattern; loads more Google+ // search results as the user scrolls to the end of the list. 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; } /** * An {@link AsyncTaskLoader} that loads activities from the public Google+ stream for * a given search query. The loader maintains a page state with the Google+ API and thus * supports pagination. */ 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 JacksonFactory(); JsonHttpRequestInitializer initializer = new GoogleKeyInitializer( Config.API_KEY); // Set up the main Google+ class Plus plus = Plus.builder(httpTransport, jsonFactory) .setApplicationName(Config.APP_NAME) .setJsonHttpRequestInitializer(initializer) .build(); ActivityFeed activities = null; try { activities = plus.activities().search(mSearchString) .setPageToken(mNextPageToken) .setMaxResults(MAX_RESULTS_PER_REQUEST) .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(String searchString) { setSearchString(searchString); refresh(); } public void refresh() { reset(); startLoading(); } } /** * A list adapter that shows individual Google+ activities as list items. * If another page is available, the last item is a "loading" view to support the * infinite scrolling UI pattern. */ 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); } StreamRowViewBinder.bindActivityView(convertView, activity, mImageFetcher); return convertView; } } } /** * A helper class to bind data from a Google+ {@link Activity} to the list item view. */ private static class StreamRowViewBinder { private static class ViewHolder { private TextView[] detail; private ImageView[] detailIcon; private ImageView[] media; private ImageView[] mediaOverlay; private TextView originalAuthor; private View reshareLine; private View reshareSpacer; private ImageView userImage; private TextView userName; private TextView content; private View plusOneIcon; private TextView plusOneCount; private View commentIcon; private TextView commentCount; } private static void bindActivityView( final View rootView, Activity activity, ImageFetcher imageFetcher) { // Prepare view holder. ViewHolder temp = (ViewHolder) rootView.getTag(); final ViewHolder views; if (temp != null) { views = temp; } else { views = new ViewHolder(); rootView.setTag(views); views.detail = new TextView[] { (TextView) rootView.findViewById(R.id.stream_detail_text) }; views.detailIcon = new ImageView[] { (ImageView) rootView.findViewById(R.id.stream_detail_media_small) }; views.media = new ImageView[] { (ImageView) rootView.findViewById(R.id.stream_media_1_1), (ImageView) rootView.findViewById(R.id.stream_media_1_2), }; views.mediaOverlay = new ImageView[] { (ImageView) rootView.findViewById(R.id.stream_media_overlay_1_1), (ImageView) rootView.findViewById(R.id.stream_media_overlay_1_2), }; views.originalAuthor = (TextView) rootView.findViewById(R.id.stream_original_author); views.reshareLine = rootView.findViewById(R.id.stream_reshare_line); views.reshareSpacer = rootView.findViewById(R.id.stream_reshare_spacer); views.userImage = (ImageView) rootView.findViewById(R.id.stream_user_image); views.userName = (TextView) rootView.findViewById(R.id.stream_user_name); views.content = (TextView) rootView.findViewById(R.id.stream_content); views.plusOneIcon = rootView.findViewById(R.id.stream_plus_one_icon); views.plusOneCount = (TextView) rootView.findViewById(R.id.stream_plus_one_count); views.commentIcon = rootView.findViewById(R.id.stream_comment_icon); views.commentCount = (TextView) rootView.findViewById(R.id.stream_comment_count); } final Resources res = rootView.getContext().getResources(); // Hide all the array items. int detailIndex = 0; int mediaIndex = 0; for (View v : views.detail) { v.setVisibility(View.GONE); } for (View v : views.detailIcon) { v.setVisibility(View.GONE); } for (View v : views.media) { v.setVisibility(View.GONE); } for (View v : views.mediaOverlay) { v.setVisibility(View.GONE); } // Determine if this is a reshare (affects how activity fields are to be // interpreted). boolean isReshare = (activity.getObject().getActor() != null); // Set user name. views.userName.setText(activity.getActor().getDisplayName()); if (activity.getActor().getImage() != null) { imageFetcher.loadThumbnailImage(activity.getActor().getImage().getUrl(), views.userImage, R.drawable.person_image_empty); } else { views.userImage.setImageResource(R.drawable.person_image_empty); } // Set +1 and comment counts. final int plusOneCount = (activity.getObject().getPlusoners() != null) ? activity.getObject().getPlusoners().getTotalItems().intValue() : 0; if (plusOneCount == 0) { views.plusOneIcon.setVisibility(View.GONE); views.plusOneCount.setVisibility(View.GONE); } else { views.plusOneIcon.setVisibility(View.VISIBLE); views.plusOneCount.setVisibility(View.VISIBLE); views.plusOneCount.setText(Integer.toString(plusOneCount)); } final int commentCount = (activity.getObject().getReplies() != null) ? activity.getObject().getReplies().getTotalItems().intValue() : 0; if (commentCount == 0) { views.commentIcon.setVisibility(View.GONE); views.commentCount.setVisibility(View.GONE); } else { views.commentIcon.setVisibility(View.VISIBLE); views.commentCount.setVisibility(View.VISIBLE); views.commentCount.setText(Integer.toString(commentCount)); } // Set content. String selfContent = isReshare ? activity.getAnnotation() : activity.getObject().getContent(); if (!TextUtils.isEmpty(selfContent)) { views.content.setVisibility(View.VISIBLE); views.content.setText(Html.fromHtml(selfContent)); } else { views.content.setVisibility(View.GONE); } // Set original author. if (activity.getObject().getActor() != null) { views.originalAuthor.setVisibility(View.VISIBLE); views.originalAuthor.setText(res.getString(R.string.stream_originally_shared, activity.getObject().getActor().getDisplayName())); views.reshareLine.setVisibility(View.VISIBLE); views.reshareSpacer.setVisibility(View.INVISIBLE); } else { views.originalAuthor.setVisibility(View.GONE); views.reshareLine.setVisibility(View.GONE); views.reshareSpacer.setVisibility(View.GONE); } // Set document content. if (isReshare && !TextUtils.isEmpty(activity.getObject().getContent()) && detailIndex < views.detail.length) { views.detail[detailIndex].setVisibility(View.VISIBLE); views.detail[detailIndex].setTextColor(res.getColor(R.color.stream_content_color)); views.detail[detailIndex].setText(Html.fromHtml(activity.getObject().getContent())); ++detailIndex; } // Set location. String location = activity.getPlaceName(); if (!TextUtils.isEmpty(location)) { location = activity.getAddress(); } if (!TextUtils.isEmpty(location)) { location = activity.getGeocode(); } if (!TextUtils.isEmpty(location) && detailIndex < views.detail.length) { views.detail[detailIndex].setVisibility(View.VISIBLE); views.detail[detailIndex].setTextColor(res.getColor(R.color.stream_link_color)); views.detailIcon[detailIndex].setVisibility(View.VISIBLE); views.detail[detailIndex].setText(location); if ("checkin".equals(activity.getVerb())) { views.detailIcon[detailIndex].setImageResource(R.drawable.stream_ic_checkin); } else { views.detailIcon[detailIndex].setImageResource(R.drawable.stream_ic_location); } ++detailIndex; } // Set media content. if (activity.getObject().getAttachments() != null) { for (Activity.PlusObject.Attachments attachment : activity.getObject().getAttachments()) { String objectType = attachment.getObjectType(); if (("photo".equals(objectType) || "video".equals(objectType)) && mediaIndex < views.media.length) { if (attachment.getImage() == null) { continue; } final ImageView mediaView = views.media[mediaIndex]; mediaView.setVisibility(View.VISIBLE); imageFetcher.loadThumbnailImage(attachment.getImage().getUrl(), mediaView); if ("video".equals(objectType)) { views.mediaOverlay[mediaIndex].setVisibility(View.VISIBLE); } ++mediaIndex; } else if (("article".equals(objectType)) && detailIndex < views.detail.length) { try { String faviconUrl = "http://www.google.com/s2/favicons?domain=" + Uri.parse(attachment.getUrl()).getHost(); final ImageView iconView = views.detailIcon[detailIndex]; iconView.setVisibility(View.VISIBLE); imageFetcher.loadThumbnailImage(faviconUrl, iconView); } catch (ParseException ignored) {} views.detail[detailIndex].setVisibility(View.VISIBLE); views.detail[detailIndex].setTextColor( res.getColor(R.color.stream_link_color)); views.detail[detailIndex].setText(attachment.getDisplayName()); ++detailIndex; } } } } } }
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.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.ui.TracksAdapter.TracksQuery; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.SherlockListFragment; import android.app.Activity; import android.content.Intent; 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.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; /** * A simple {@link ListFragment} that renders a list of tracks and a map button at the top. */ public class ExploreFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor> { private TracksAdapter mAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAdapter = new TracksAdapter(getActivity()); setListAdapter(mAdapter); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final ListView listView = getListView(); listView.setSelector(android.R.color.transparent); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // As of 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(TracksQuery._TOKEN, null, this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate( R.layout.fragment_list_with_empty_container, container, false); root.setBackgroundColor(Color.WHITE); return root; } private final ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (getActivity() == null) { return; } Loader<Cursor> loader = getLoaderManager().getLoader(TracksQuery._TOKEN); if (loader != null) { loader.forceLoad(); } } }; @Override public void onAttach(Activity activity) { super.onAttach(activity); activity.getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mObserver); } @Override public void onDetach() { super.onDetach(); getActivity().getContentResolver().unregisterContentObserver(mObserver); } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { if (mAdapter.isMapItem(position)) { // Launch map of conference venue EasyTracker.getTracker().trackEvent( "Home Screen Dashboard", "Click", "Map", 0L); startActivity(new Intent(getActivity(), UIUtils.getMapActivityClass(getActivity()))); return; } final Cursor cursor = (Cursor) mAdapter.getItem(position); final String trackId; if (cursor != null) { trackId = cursor.getString(TracksAdapter.TracksQuery.TRACK_ID); } else { trackId = ScheduleContract.Tracks.ALL_TRACK_ID; } final Intent intent = new Intent(Intent.ACTION_VIEW); final Uri trackUri = ScheduleContract.Tracks.buildTrackUri(trackId); intent.setData(trackUri); startActivity(intent); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); Uri tracksUri = intent.getData(); if (tracksUri == null) { tracksUri = ScheduleContract.Tracks.CONTENT_URI; } // Filter our tracks query to only include those with valid results String[] projection = TracksAdapter.TracksQuery.PROJECTION; String selection = null; return new CursorLoader(getActivity(), tracksUri, projection, selection, null, ScheduleContract.Tracks.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } mAdapter.setHasMapItem(true); mAdapter.setHasAllItem(true); mAdapter.changeCursor(cursor); } @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 com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.graphics.drawable.ColorDrawable; import android.provider.BaseColumns; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.TextView; /** * A {@link android.widget.CursorAdapter} that renders a {@link TracksQuery}, additionally showing * "Map" and/or "All tracks" list items at the top. */ public class TracksAdapter extends CursorAdapter { private static final int ALL_ITEM_ID = Integer.MAX_VALUE; private static final int MAP_ITEM_ID = Integer.MAX_VALUE - 1; private Activity mActivity; private boolean mHasAllItem; private boolean mHasMapItem; private int mPositionDisplacement; public TracksAdapter(Activity activity) { super(activity, null, false); mActivity = activity; } public void setHasAllItem(boolean hasAllItem) { mHasAllItem = hasAllItem; updatePositionDisplacement(); } public void setHasMapItem(boolean hasMapItem) { mHasMapItem = hasMapItem; updatePositionDisplacement(); } private void updatePositionDisplacement() { mPositionDisplacement = (mHasAllItem ? 1 : 0) + (mHasMapItem ? 1 : 0); } public boolean isMapItem(int position) { return mHasMapItem && position == 0; } public boolean isAllItem(int position) { return mHasAllItem && position == (mHasMapItem ? 1 : 0); } @Override public int getCount() { return super.getCount() + mPositionDisplacement; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (isMapItem(position)) { if (convertView == null) { convertView = mActivity.getLayoutInflater().inflate( R.layout.list_item_track_map, parent, false); } return convertView; } else if (isAllItem(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; } return super.getView(position - mPositionDisplacement, convertView, parent); } @Override public Object getItem(int position) { if (isMapItem(position) || isAllItem(position)) { return null; } return super.getItem(position - mPositionDisplacement); } @Override public long getItemId(int position) { if (isMapItem(position)) { return MAP_ITEM_ID; } else if (isAllItem(position)) { return ALL_ITEM_ID; } return super.getItemId(position - mPositionDisplacement); } @Override public boolean isEnabled(int position) { return (mHasAllItem && position == 0) || super.isEnabled(position - mPositionDisplacement); } @Override public int getViewTypeCount() { // Add an item type for the "All" and map views. return super.getViewTypeCount() + 2; } @Override public int getItemViewType(int position) { if (isMapItem(position)) { return getViewTypeCount() - 1; } else if (isAllItem(position)) { return getViewTypeCount() - 2; } return super.getItemViewType(position - mPositionDisplacement); } /** {@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) { final TextView textView = (TextView) view.findViewById(android.R.id.text1); textView.setText(cursor.getString(TracksQuery.TRACK_NAME)); // Assign track color to visible block final ImageView iconView = (ImageView) view.findViewById(android.R.id.icon1); iconView.setImageDrawable(new ColorDrawable(cursor.getInt(TracksQuery.TRACK_COLOR))); } /** {@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, }; 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.SESSIONS_COUNT, }; String[] PROJECTION_WITH_VENDORS_COUNT = { BaseColumns._ID, ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_ABSTRACT, ScheduleContract.Tracks.TRACK_COLOR, ScheduleContract.Tracks.VENDORS_COUNT, }; int _ID = 0; int TRACK_ID = 1; int TRACK_NAME = 2; int TRACK_ABSTRACT = 3; int TRACK_COLOR = 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.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.ImageFetcher; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.SherlockFragment; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; 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 developer sandbox company, including * company name, description, logo, etc. */ public class VendorDetailFragment extends SherlockFragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final String TAG = makeLogTag(VendorDetailFragment.class); private Uri mVendorUri; private TextView mName; private ImageView mLogo; private TextView mUrl; private TextView mDesc; private ImageFetcher mImageFetcher; public interface Callbacks { public void onTrackIdAvailable(String trackId); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onTrackIdAvailable(String trackId) {} }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mVendorUri = intent.getData(); if (mVendorUri == null) { return; } mImageFetcher = UIUtils.getImageFetcher(getActivity()); mImageFetcher.setImageFadeIn(false); setHasOptionsMenu(true); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (mVendorUri == null) { return; } // Start background query to load vendor details getLoaderManager().initLoader(VendorsQuery._TOKEN, 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; } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; } @Override public void onPause() { super.onPause(); mImageFetcher.flushCache(); } @Override public void onDestroy() { super.onDestroy(); mImageFetcher.closeCache(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_vendor_detail, null); mName = (TextView) rootView.findViewById(R.id.vendor_name); mLogo = (ImageView) rootView.findViewById(R.id.vendor_logo); mUrl = (TextView) rootView.findViewById(R.id.vendor_url); mDesc = (TextView) rootView.findViewById(R.id.vendor_desc); return rootView; } public void buildUiFromCursor(Cursor cursor) { if (getActivity() == null) { return; } if (!cursor.moveToFirst()) { return; } String nameString = cursor.getString(VendorsQuery.NAME); mName.setText(nameString); // Start background fetch to load vendor logo final String logoUrl = cursor.getString(VendorsQuery.LOGO_URL); if (!TextUtils.isEmpty(logoUrl)) { mImageFetcher.loadThumbnailImage(logoUrl, mLogo, R.drawable.sandbox_logo_empty); } mUrl.setText(cursor.getString(VendorsQuery.URL)); mDesc.setText(cursor.getString(VendorsQuery.DESC)); EasyTracker.getTracker().trackView("Sandbox Vendor: " + nameString); LOGD("Tracker", "Sandbox Vendor: " + nameString); mCallbacks.onTrackIdAvailable(cursor.getString(VendorsQuery.TRACK_ID)); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(getActivity(), mVendorUri, VendorsQuery.PROJECTION, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { buildUiFromCursor(cursor); } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Vendors} * query parameters. */ private interface VendorsQuery { int _TOKEN = 0x4; String[] PROJECTION = { ScheduleContract.Vendors.VENDOR_NAME, ScheduleContract.Vendors.VENDOR_DESC, ScheduleContract.Vendors.VENDOR_URL, ScheduleContract.Vendors.VENDOR_LOGO_URL, ScheduleContract.Vendors.TRACK_ID, }; int NAME = 0; int DESC = 1; int URL = 2; int LOGO_URL = 3; int TRACK_ID = 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 com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.AccountUtils; import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.app.SherlockListFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import android.accounts.Account; import android.accounts.AccountManager; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.provider.Settings; 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 java.util.Arrays; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * The first activity most users see. This wizard-like activity first presents an account * selection fragment ({@link ChooseAccountFragment}), and then an authentication progress fragment * ({@link AuthProgressFragment}). */ public class AccountActivity extends SherlockFragmentActivity implements AccountUtils.AuthenticateCallback { 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 REQUEST_AUTHENTICATE = 100; private final Handler mHandler = new Handler(); private Account mChosenAccount; private Intent mFinishIntent; private boolean mCancelAuth = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_account); if (getIntent().hasExtra(EXTRA_FINISH_INTENT)) { mFinishIntent = getIntent().getParcelableExtra(EXTRA_FINISH_INTENT); } if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, new ChooseAccountFragment(), "choose_account") .commit(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_AUTHENTICATE) { if (resultCode == RESULT_OK) { tryAuthenticate(); } else { // go back to previous step mHandler.post(new Runnable() { @Override public void run() { getSupportFragmentManager().popBackStack(); } }); } } else { super.onActivityResult(requestCode, resultCode, data); } } private void tryAuthenticate() { AccountUtils.tryAuthenticate(AccountActivity.this, AccountActivity.this, REQUEST_AUTHENTICATE, mChosenAccount); } @Override public boolean shouldCancelAuthentication() { return mCancelAuth; } @Override public void onAuthTokenAvailable(String authToken) { ContentResolver.setIsSyncable(mChosenAccount, ScheduleContract.CONTENT_AUTHORITY, 1); if (mFinishIntent != null) { mFinishIntent.addCategory(Intent.CATEGORY_LAUNCHER); mFinishIntent.setAction(Intent.ACTION_MAIN); mFinishIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(mFinishIntent); } finish(); } /** * A fragment that presents the user with a list of accounts to choose from. Once an account is * selected, we move on to the login progress fragment ({@link AuthProgressFragment}). */ public static class ChooseAccountFragment extends SherlockListFragment { public ChooseAccountFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onResume() { super.onResume(); reloadAccountList(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.add_account, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_add_account) { Intent addAccountIntent = new Intent(Settings.ACTION_ADD_ACCOUNT); addAccountIntent.putExtra(Settings.EXTRA_AUTHORITIES, new String[]{ScheduleContract.CONTENT_AUTHORITY}); startActivity(addAccountIntent); return true; } return super.onOptionsItemSelected(item); } @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(GoogleAccountManager.ACCOUNT_TYPE); mAccountListAdapter = new AccountListAdapter(getActivity(), Arrays.asList(accounts)); setListAdapter(mAccountListAdapter); } private class AccountListAdapter extends ArrayAdapter<Account> { private static final int LAYOUT_RESOURCE = android.R.layout.simple_list_item_1; public AccountListAdapter(Context context, List<Account> accounts) { super(context, LAYOUT_RESOURCE, accounts); } private class ViewHolder { TextView text1; } 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(); } 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) { 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.fragment_container, new AuthProgressFragment(), "loading") .addToBackStack("choose_account") .commit(); activity.tryAuthenticate(); } } /** * This fragment shows a login progress spinner. Upon reaching a timeout of 7 seconds (in case * of a poor network connection), the user can try again. */ public static class AuthProgressFragment extends SherlockFragment { 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; } takingAWhilePanel.setVisibility(View.VISIBLE); } }, TRY_AGAIN_DELAY_MILLIS); return rootView; } @Override public void onDetach() { super.onDetach(); ((AccountActivity) getActivity()).mCancelAuth = 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.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.BaseActivity; import com.google.android.apps.iosched.ui.MapFragment; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.VendorDetailFragment; import com.google.android.apps.iosched.ui.VendorsFragment; import android.annotation.TargetApi; import android.app.FragmentBreadCrumbs; import android.content.Intent; import android.content.res.Configuration; import android.database.Cursor; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; /** * A multi-pane activity, where the full-screen content is a {@link MapFragment} and popup content * may be visible at any given time, containing either a {@link SessionsFragment} (representing * sessions for a given room) or a {@link SessionDetailFragment}. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class MapMultiPaneActivity extends BaseActivity implements FragmentManager.OnBackStackChangedListener, MapFragment.Callbacks, SessionsFragment.Callbacks, LoaderManager.LoaderCallbacks<Cursor> { private boolean mPauseBackStackWatcher = false; private FragmentBreadCrumbs mFragmentBreadCrumbs; private String mSelectedRoomName; private MapFragment mMapFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); FragmentManager fm = getSupportFragmentManager(); fm.addOnBackStackChangedListener(this); mFragmentBreadCrumbs = (FragmentBreadCrumbs) findViewById(R.id.breadcrumbs); mFragmentBreadCrumbs.setActivity(this); mMapFragment = (MapFragment) fm.findFragmentByTag("map"); if (mMapFragment == null) { mMapFragment = new MapFragment(); mMapFragment.setArguments(intentToFragmentArguments(getIntent())); fm.beginTransaction() .add(R.id.fragment_container_map, mMapFragment, "map") .commit(); } findViewById(R.id.close_button).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { clearBackStack(false); } }); updateBreadCrumbs(); onConfigurationChanged(getResources().getConfiguration()); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); boolean landscape = (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE); LinearLayout spacerView = (LinearLayout) findViewById(R.id.map_detail_spacer); spacerView.setOrientation(landscape ? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL); spacerView.setGravity(landscape ? Gravity.RIGHT : Gravity.BOTTOM); View popupView = findViewById(R.id.map_detail_popup); LinearLayout.LayoutParams popupLayoutParams = (LinearLayout.LayoutParams) popupView.getLayoutParams(); popupLayoutParams.width = landscape ? 0 : ViewGroup.LayoutParams.MATCH_PARENT; popupLayoutParams.height = landscape ? ViewGroup.LayoutParams.MATCH_PARENT : 0; popupView.setLayoutParams(popupLayoutParams); popupView.requestLayout(); } private void clearBackStack(boolean pauseWatcher) { if (pauseWatcher) { mPauseBackStackWatcher = true; } FragmentManager fm = getSupportFragmentManager(); while (fm.getBackStackEntryCount() > 0) { fm.popBackStackImmediate(); } if (pauseWatcher) { mPauseBackStackWatcher = false; } } public void onBackStackChanged() { if (mPauseBackStackWatcher) { return; } if (getSupportFragmentManager().getBackStackEntryCount() == 0) { showDetailPane(false); } updateBreadCrumbs(); } private void showDetailPane(boolean show) { View detailPopup = findViewById(R.id.map_detail_spacer); if (show != (detailPopup.getVisibility() == View.VISIBLE)) { detailPopup.setVisibility(show ? View.VISIBLE : View.GONE); // Pan the map left or up depending on the orientation. boolean landscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; mMapFragment.panBy( landscape ? (show ? 0.25f : -0.25f) : 0, landscape ? 0 : (show ? 0.25f : -0.25f)); } } public void updateBreadCrumbs() { final String title = (mSelectedRoomName != null) ? mSelectedRoomName : getString(R.string.title_sessions); final String detailTitle = getString(R.string.title_session_detail); if (getSupportFragmentManager().getBackStackEntryCount() >= 2) { mFragmentBreadCrumbs.setParentTitle(title, title, mFragmentBreadCrumbsClickListener); mFragmentBreadCrumbs.setTitle(detailTitle, detailTitle); } else { mFragmentBreadCrumbs.setParentTitle(null, null, null); mFragmentBreadCrumbs.setTitle(title, title); } } private View.OnClickListener mFragmentBreadCrumbsClickListener = new View.OnClickListener() { @Override public void onClick(View view) { getSupportFragmentManager().popBackStack(); } }; @Override public void onRoomSelected(String roomId) { // Load room details mSelectedRoomName = null; Bundle loadRoomDataArgs = new Bundle(); loadRoomDataArgs.putString("room_id", roomId); getSupportLoaderManager().restartLoader(0, loadRoomDataArgs, this); // force load // Show the sessions in the room clearBackStack(true); showDetailPane(true); SessionsFragment fragment = new SessionsFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, ScheduleContract.Rooms.buildSessionsDirUri(roomId)))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .addToBackStack(null) .commit(); updateBreadCrumbs(); } @Override public boolean onSessionSelected(String sessionId) { // Show the session details showDetailPane(true); SessionDetailFragment fragment = new SessionDetailFragment(); Intent intent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(sessionId)); intent.putExtra(SessionDetailFragment.EXTRA_VARIABLE_HEIGHT_HEADER, true); fragment.setArguments(BaseActivity.intentToFragmentArguments(intent)); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .addToBackStack(null) .commit(); updateBreadCrumbs(); return false; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(this, ScheduleContract.Rooms.buildRoomUri(data.getString("room_id")), RoomsQuery.PROJECTION, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { try { if (!cursor.moveToFirst()) { return; } mSelectedRoomName = cursor.getString(RoomsQuery.ROOM_NAME); updateBreadCrumbs(); } finally { cursor.close(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } private interface RoomsQuery { String[] PROJECTION = { ScheduleContract.Rooms.ROOM_ID, ScheduleContract.Rooms.ROOM_NAME, ScheduleContract.Rooms.ROOM_FLOOR, }; int ROOM_ID = 0; int ROOM_NAME = 1; int ROOM_FLOOR = 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.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.TracksAdapter; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.SherlockFragment; import android.annotation.TargetApi; import android.app.Activity; import android.content.res.Resources; import android.database.Cursor; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListPopupWindow; import android.widget.PopupWindow; import android.widget.TextView; /** * A tablet-specific fragment that emulates a giant {@link android.widget.Spinner}-like widget. * When touched, it shows a {@link ListPopupWindow} containing a list of tracks, * using {@link TracksAdapter}. Requires API level 11 or later since {@link ListPopupWindow} is * API level 11+. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class TracksDropdownFragment extends SherlockFragment implements LoaderManager.LoaderCallbacks<Cursor>, AdapterView.OnItemClickListener, PopupWindow.OnDismissListener { public static final String VIEW_TYPE_SESSIONS = "sessions"; public static final String VIEW_TYPE_VENDORS = "vendors"; private static final String STATE_VIEW_TYPE = "viewType"; private static final String STATE_SELECTED_TRACK_ID = "selectedTrackId"; private TracksAdapter mAdapter; private String mViewType; private Handler mHandler = new Handler(); private ListPopupWindow mListPopupWindow; private ViewGroup mRootView; private TextView mTitle; private TextView mAbstract; private String mTrackId; public interface Callbacks { public void onTrackSelected(String trackId); public void onTrackNameAvailable(String trackId, String trackName); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onTrackSelected(String trackId) { } @Override public void onTrackNameAvailable(String trackId, String trackName) {} }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAdapter = new TracksAdapter(getActivity()); if (savedInstanceState != null) { // Since this fragment doesn't rely on fragment arguments, we must // handle // state restores and saves ourselves. mViewType = savedInstanceState.getString(STATE_VIEW_TYPE); mTrackId = savedInstanceState.getString(STATE_SELECTED_TRACK_ID); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(STATE_VIEW_TYPE, mViewType); outState.putString(STATE_SELECTED_TRACK_ID, mTrackId); } public String getSelectedTrackId() { return mTrackId; } public void selectTrack(String trackId) { loadTrackList(mViewType, trackId); } public void loadTrackList(String viewType) { loadTrackList(viewType, mTrackId); } public void loadTrackList(String viewType, String selectTrackId) { // Teardown from previous arguments if (mListPopupWindow != null) { mListPopupWindow.setAdapter(null); } mViewType = viewType; mTrackId = selectTrackId; // Start background query to load tracks getLoaderManager().restartLoader(TracksAdapter.TracksQuery._TOKEN, null, this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_tracks_dropdown, null); mTitle = (TextView) mRootView.findViewById(R.id.track_title); mAbstract = (TextView) mRootView.findViewById(R.id.track_abstract); mRootView.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mListPopupWindow = new ListPopupWindow(getActivity()); mListPopupWindow.setAdapter(mAdapter); mListPopupWindow.setModal(true); mListPopupWindow.setContentWidth( getResources().getDimensionPixelSize(R.dimen.track_dropdown_width)); mListPopupWindow.setAnchorView(mRootView); mListPopupWindow.setOnItemClickListener(TracksDropdownFragment.this); mListPopupWindow.show(); mListPopupWindow.setOnDismissListener(TracksDropdownFragment.this); } }); return mRootView; } @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; if (mListPopupWindow != null) { mListPopupWindow.dismiss(); } } /** {@inheritDoc} */ public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position); loadTrack(cursor, true); if (mListPopupWindow != null) { mListPopupWindow.dismiss(); } } public String getTrackName() { return (String) mTitle.getText(); } private void loadTrack(Cursor cursor, boolean triggerCallback) { final int trackColor; final Resources res = getResources(); if (cursor != null) { trackColor = cursor.getInt(TracksAdapter.TracksQuery.TRACK_COLOR); mTrackId = cursor.getString(TracksAdapter.TracksQuery.TRACK_ID); mTitle.setText(cursor.getString(TracksAdapter.TracksQuery.TRACK_NAME)); mAbstract.setText(cursor.getString(TracksAdapter.TracksQuery.TRACK_ABSTRACT)); } else { trackColor = res.getColor(R.color.all_track_color); mTrackId = ScheduleContract.Tracks.ALL_TRACK_ID; mTitle.setText(VIEW_TYPE_SESSIONS.equals(mViewType) ? R.string.all_tracks_sessions : R.string.all_tracks_vendors); mAbstract.setText(VIEW_TYPE_SESSIONS.equals(mViewType) ? R.string.all_tracks_subtitle_sessions : R.string.all_tracks_subtitle_vendors); } boolean isDark = UIUtils.isColorDark(trackColor); mRootView.setBackgroundColor(trackColor); if (isDark) { mTitle.setTextColor(res.getColor(R.color.body_text_1_inverse)); mAbstract.setTextColor(res.getColor(R.color.body_text_2_inverse)); mRootView.findViewById(R.id.track_dropdown_arrow).setBackgroundResource( R.drawable.track_dropdown_arrow_light); } else { mTitle.setTextColor(res.getColor(R.color.body_text_1)); mAbstract.setTextColor(res.getColor(R.color.body_text_2)); mRootView.findViewById(R.id.track_dropdown_arrow).setBackgroundResource( R.drawable.track_dropdown_arrow_dark); } mCallbacks.onTrackNameAvailable(mTrackId, mTitle.getText().toString()); if (triggerCallback) { mHandler.post(new Runnable() { @Override public void run() { mCallbacks.onTrackSelected(mTrackId); } }); } } public void onDismiss() { mListPopupWindow = null; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { // Filter our tracks query to only include those with valid results String[] projection = TracksAdapter.TracksQuery.PROJECTION; String selection = null; if (VIEW_TYPE_SESSIONS.equals(mViewType)) { // Only show tracks with at least one session projection = TracksAdapter.TracksQuery.PROJECTION_WITH_SESSIONS_COUNT; selection = ScheduleContract.Tracks.SESSIONS_COUNT + ">0"; } else if (VIEW_TYPE_VENDORS.equals(mViewType)) { // Only show tracks with at least one vendor projection = TracksAdapter.TracksQuery.PROJECTION_WITH_VENDORS_COUNT; selection = ScheduleContract.Tracks.VENDORS_COUNT + ">0"; } return new CursorLoader(getActivity(), ScheduleContract.Tracks.CONTENT_URI, projection, selection, null, ScheduleContract.Tracks.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null || cursor == null) { return; } boolean trackLoaded = false; if (mTrackId != null) { cursor.moveToFirst(); while (!cursor.isAfterLast()) { if (mTrackId.equals(cursor.getString(TracksAdapter.TracksQuery.TRACK_ID))) { loadTrack(cursor, false); trackLoaded = true; break; } cursor.moveToNext(); } } if (!trackLoaded) { loadTrack(null, false); } mAdapter.setHasAllItem(true); mAdapter.changeCursor(cursor); } @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.tablet; 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.ui.BaseActivity; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.TrackInfoHelperFragment; import com.google.android.apps.iosched.ui.VendorDetailFragment; import com.google.android.apps.iosched.ui.VendorsFragment; import com.google.android.apps.iosched.ui.widget.ShowHideMasterLayout; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import android.annotation.TargetApi; import android.app.AlertDialog; import android.app.SearchManager; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.nfc.NfcAdapter; import android.nfc.NfcEvent; 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.FragmentTransaction; import android.widget.SearchView; import static com.google.android.apps.iosched.util.LogUtils.LOGD; /** * A multi-pane activity, consisting of a {@link TracksDropdownFragment} (top-left), a * {@link SessionsFragment} or {@link VendorsFragment} (bottom-left), and * a {@link SessionDetailFragment} or {@link VendorDetailFragment} (right pane). */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class SessionsVendorsMultiPaneActivity extends BaseActivity implements ActionBar.TabListener, SessionsFragment.Callbacks, VendorsFragment.Callbacks, VendorDetailFragment.Callbacks, TracksDropdownFragment.Callbacks, TrackInfoHelperFragment.Callbacks { public static final String EXTRA_MASTER_URI = "com.google.android.apps.iosched.extra.MASTER_URI"; private static final String STATE_VIEW_TYPE = "view_type"; private TracksDropdownFragment mTracksDropdownFragment; private Fragment mDetailFragment; private boolean mFullUI = false; private ShowHideMasterLayout mShowHideMasterLayout; private String mViewType; private boolean mInitialTabSelect = true; @Override protected void onCreate(Bundle savedInstanceState) { if (BeamUtils.wasLaunchedThroughBeamFirstTime(this, getIntent())) { BeamUtils.setBeamUnlocked(this); showFirstBeamDialog(); } BeamUtils.tryUpdateIntentFromBeam(this); super.onCreate(savedInstanceState); trySetBeamCallback(); setContentView(R.layout.activity_sessions_vendors); final FragmentManager fm = getSupportFragmentManager(); mTracksDropdownFragment = (TracksDropdownFragment) fm.findFragmentById( R.id.fragment_tracks_dropdown); mShowHideMasterLayout = (ShowHideMasterLayout) findViewById(R.id.show_hide_master_layout); if (mShowHideMasterLayout != null) { mShowHideMasterLayout.setFlingToExposeMasterEnabled(true); } routeIntent(getIntent(), savedInstanceState != null); if (savedInstanceState != null) { if (mFullUI) { getSupportActionBar().setSelectedNavigationItem( TracksDropdownFragment.VIEW_TYPE_SESSIONS.equals( savedInstanceState.getString(STATE_VIEW_TYPE)) ? 0 : 1); } mDetailFragment = fm.findFragmentById(R.id.fragment_container_detail); updateDetailBackground(); } // This flag prevents onTabSelected from triggering extra master pane reloads // unless it's actually being triggered by the user (and not automatically by // the system) mInitialTabSelect = false; EasyTracker.getTracker().setContext(this); } private void routeIntent(Intent intent, boolean updateSurfaceOnly) { Uri uri = intent.getData(); if (uri == null) { return; } if (intent.hasExtra(Intent.EXTRA_TITLE)) { setTitle(intent.getStringExtra(Intent.EXTRA_TITLE)); } String mimeType = getContentResolver().getType(uri); if (ScheduleContract.Tracks.CONTENT_ITEM_TYPE.equals(mimeType)) { // Load track details showFullUI(true); if (!updateSurfaceOnly) { // TODO: don't assume the URI will contain the track ID String selectedTrackId = ScheduleContract.Tracks.getTrackId(uri); loadTrackList(TracksDropdownFragment.VIEW_TYPE_SESSIONS, selectedTrackId); onTrackSelected(selectedTrackId); if (mShowHideMasterLayout != null) { mShowHideMasterLayout.showMaster(true, ShowHideMasterLayout.FLAG_IMMEDIATE); } } } else if (ScheduleContract.Sessions.CONTENT_TYPE.equals(mimeType)) { // Load a session list, hiding the tracks dropdown and the tabs mViewType = TracksDropdownFragment.VIEW_TYPE_SESSIONS; showFullUI(false); if (!updateSurfaceOnly) { loadSessionList(uri, null); if (mShowHideMasterLayout != null) { mShowHideMasterLayout.showMaster(true, ShowHideMasterLayout.FLAG_IMMEDIATE); } } } else if (ScheduleContract.Sessions.CONTENT_ITEM_TYPE.equals(mimeType)) { // Load session details if (intent.hasExtra(EXTRA_MASTER_URI)) { mViewType = TracksDropdownFragment.VIEW_TYPE_SESSIONS; showFullUI(false); if (!updateSurfaceOnly) { loadSessionList((Uri) intent.getParcelableExtra(EXTRA_MASTER_URI), ScheduleContract.Sessions.getSessionId(uri)); loadSessionDetail(uri); } } else { mViewType = TracksDropdownFragment.VIEW_TYPE_SESSIONS; // prepare for onTrackInfo... showFullUI(true); if (!updateSurfaceOnly) { loadSessionDetail(uri); loadTrackInfoFromSessionUri(uri); } } } else if (ScheduleContract.Vendors.CONTENT_TYPE.equals(mimeType)) { // Load a vendor list mViewType = TracksDropdownFragment.VIEW_TYPE_VENDORS; showFullUI(false); if (!updateSurfaceOnly) { loadVendorList(uri, null); if (mShowHideMasterLayout != null) { mShowHideMasterLayout.showMaster(true, ShowHideMasterLayout.FLAG_IMMEDIATE); } } } else if (ScheduleContract.Vendors.CONTENT_ITEM_TYPE.equals(mimeType)) { // Load vendor details mViewType = TracksDropdownFragment.VIEW_TYPE_VENDORS; showFullUI(false); if (!updateSurfaceOnly) { Uri masterUri = (Uri) intent.getParcelableExtra(EXTRA_MASTER_URI); if (masterUri == null) { masterUri = ScheduleContract.Vendors.CONTENT_URI; } loadVendorList(masterUri, ScheduleContract.Vendors.getVendorId(uri)); loadVendorDetail(uri); } } updateDetailBackground(); } private void showFullUI(boolean fullUI) { mFullUI = fullUI; final ActionBar actionBar = getSupportActionBar(); final FragmentManager fm = getSupportFragmentManager(); if (fullUI) { actionBar.removeAllTabs(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setDisplayShowTitleEnabled(false); actionBar.addTab(actionBar.newTab() .setText(R.string.title_sessions) .setTag(TracksDropdownFragment.VIEW_TYPE_SESSIONS) .setTabListener(this)); actionBar.addTab(actionBar.newTab() .setText(R.string.title_vendors) .setTag(TracksDropdownFragment.VIEW_TYPE_VENDORS) .setTabListener(this)); fm.beginTransaction() .show(fm.findFragmentById(R.id.fragment_tracks_dropdown)) .commit(); } else { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); fm.beginTransaction() .hide(fm.findFragmentById(R.id.fragment_tracks_dropdown)) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.search, 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())); } } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if (mShowHideMasterLayout != null && !mShowHideMasterLayout.isMasterVisible()) { // If showing the detail view, pressing Up should show the master pane. mShowHideMasterLayout.showMaster(true, 0); return true; } break; case R.id.menu_search: if (!UIUtils.hasHoneycomb()) { startSearch(null, false, Bundle.EMPTY, false); return true; } break; } return super.onOptionsItemSelected(item); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(STATE_VIEW_TYPE, mViewType); } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { loadTrackList((String) tab.getTag()); if (!mInitialTabSelect) { onTrackSelected(mTracksDropdownFragment.getSelectedTrackId()); if (mShowHideMasterLayout != null) { mShowHideMasterLayout.showMaster(true, 0); } } } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } private void loadTrackList(String viewType) { loadTrackList(viewType, null); } private void loadTrackList(String viewType, String selectTrackId) { if (mDetailFragment != null && !mViewType.equals(viewType)) { getSupportFragmentManager().beginTransaction() .remove(mDetailFragment) .commit(); mDetailFragment = null; } mViewType = viewType; if (selectTrackId != null) { mTracksDropdownFragment.loadTrackList(viewType, selectTrackId); } else { mTracksDropdownFragment.loadTrackList(viewType); } updateDetailBackground(); } private void updateDetailBackground() { if (mDetailFragment == null) { if (TracksDropdownFragment.VIEW_TYPE_SESSIONS.equals(mViewType)) { findViewById(R.id.fragment_container_detail).setBackgroundResource( R.drawable.grey_frame_on_white_empty_sessions); } else { findViewById(R.id.fragment_container_detail).setBackgroundResource( R.drawable.grey_frame_on_white_empty_sandbox); } } else { findViewById(R.id.fragment_container_detail).setBackgroundResource( R.drawable.grey_frame_on_white); } } private void loadSessionList(Uri sessionsUri, String selectSessionId) { SessionsFragment fragment = new SessionsFragment(); fragment.setSelectedSessionId(selectSessionId); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, sessionsUri))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_master, fragment) .commit(); } private void loadSessionDetail(Uri sessionUri) { BeamUtils.setBeamSessionUri(this, sessionUri); SessionDetailFragment fragment = new SessionDetailFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, sessionUri))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .commit(); mDetailFragment = fragment; updateDetailBackground(); // If loading session details in portrait, hide the master pane if (mShowHideMasterLayout != null) { mShowHideMasterLayout.showMaster(false, 0); } } private void loadVendorList(Uri vendorsUri, String selectVendorId) { VendorsFragment fragment = new VendorsFragment(); fragment.setSelectedVendorId(selectVendorId); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, vendorsUri))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_master, fragment) .commit(); } private void loadVendorDetail(Uri vendorUri) { VendorDetailFragment fragment = new VendorDetailFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, vendorUri))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .commit(); mDetailFragment = fragment; updateDetailBackground(); // If loading session details in portrait, hide the master pane if (mShowHideMasterLayout != null) { mShowHideMasterLayout.showMaster(false, 0); } } @Override public void onTrackNameAvailable(String trackId, String trackName) { String trackType; if (TracksDropdownFragment.VIEW_TYPE_SESSIONS.equals(mViewType)) { trackType = getString(R.string.title_sessions); } else { trackType = getString(R.string.title_vendors); } EasyTracker.getTracker().trackView(trackType + ": " + getTitle()); LOGD("Tracker", trackType + ": " + mTracksDropdownFragment.getTrackName()); } @Override public void onTrackSelected(String trackId) { boolean allTracks = (ScheduleContract.Tracks.ALL_TRACK_ID.equals(trackId)); if (TracksDropdownFragment.VIEW_TYPE_SESSIONS.equals(mViewType)) { loadSessionList(allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(trackId), null); } else { loadVendorList(allTracks ? ScheduleContract.Vendors.CONTENT_URI : ScheduleContract.Tracks.buildVendorsUri(trackId), null); } } @Override public boolean onSessionSelected(String sessionId) { loadSessionDetail(ScheduleContract.Sessions.buildSessionUri(sessionId)); return true; } @Override public boolean onVendorSelected(String vendorId) { loadVendorDetail(ScheduleContract.Vendors.buildVendorUri(vendorId)); return true; } private TrackInfoHelperFragment mTrackInfoHelperFragment; private String mTrackInfoLoadCookie; private void loadTrackInfoFromSessionUri(Uri sessionUri) { mTrackInfoLoadCookie = ScheduleContract.Sessions.getSessionId(sessionUri); Uri trackDirUri = ScheduleContract.Sessions.buildTracksDirUri( ScheduleContract.Sessions.getSessionId(sessionUri)); android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); if (mTrackInfoHelperFragment != null) { ft.remove(mTrackInfoHelperFragment); } mTrackInfoHelperFragment = TrackInfoHelperFragment.newFromTrackUri(trackDirUri); ft.add(mTrackInfoHelperFragment, "track_info").commit(); } @Override public void onTrackInfoAvailable(String trackId, String trackName, int trackColor) { loadTrackList(mViewType, trackId); boolean allTracks = (ScheduleContract.Tracks.ALL_TRACK_ID.equals(trackId)); if (TracksDropdownFragment.VIEW_TYPE_SESSIONS.equals(mViewType)) { loadSessionList(allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(trackId), mTrackInfoLoadCookie); } else { loadVendorList(allTracks ? ScheduleContract.Vendors.CONTENT_URI : ScheduleContract.Tracks.buildVendorsUri(trackId), mTrackInfoLoadCookie); } } @Override public void onTrackIdAvailable(String trackId) { } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void trySetBeamCallback() { if (UIUtils.hasICS()) { BeamUtils.setBeamCompleteCallback(this, new NfcAdapter.OnNdefPushCompleteCallback() { @Override public void onNdefPushComplete(NfcEvent event) { // Beam has been sent if (!BeamUtils.isBeamUnlocked(SessionsVendorsMultiPaneActivity.this)) { BeamUtils.setBeamUnlocked(SessionsVendorsMultiPaneActivity.this); runOnUiThread(new Runnable() { @Override public void run() { showFirstBeamDialog(); } }); } } }); } } private void showFirstBeamDialog() { new AlertDialog.Builder(this) .setTitle(R.string.just_beamed) .setMessage(R.string.beam_unlocked_session) .setNegativeButton(R.string.close, null) .setPositiveButton(R.string.view_beam_session, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { BeamUtils.launchBeamSession(SessionsVendorsMultiPaneActivity.this); di.dismiss(); } }) .create() .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 com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.actionbarsherlock.app.SherlockFragment; 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.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. and * returns this information via {@link Callbacks#onTrackInfoAvailable(String, String, int)}. */ public class TrackInfoHelperFragment extends SherlockFragment implements LoaderManager.LoaderCallbacks<Cursor> { /** * The track URI for which to load data. */ public static final String ARG_TRACK = "com.google.android.iosched.extra.TRACK"; private Uri mTrackUri; // To be loaded private String mTrackId; private String mTrackName; private int mTrackColor; private Handler mHandler = new Handler(); public interface Callbacks { public void onTrackInfoAvailable(String trackId, String trackName, int trackColor); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onTrackInfoAvailable(String trackId, String trackName, int trackColor) { } }; 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; mTrackName = getString(R.string.all_tracks); mTrackColor = getResources().getColor(android.R.color.white); mCallbacks.onTrackInfoAvailable(mTrackId, mTrackName, mTrackColor); } 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, mTrackName, mTrackColor); } }); } } @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); mTrackName = cursor.getString(TracksQuery.TRACK_NAME); mTrackColor = cursor.getInt(TracksQuery.TRACK_COLOR); // 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, mTrackName, mTrackColor); } }); } 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, }; int TRACK_ID = 0; int TRACK_NAME = 1; int TRACK_COLOR = 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 com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.tablet.SessionsVendorsMultiPaneActivity; import com.google.android.apps.iosched.ui.widget.SimpleSectionedListAdapter; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import com.google.android.apps.iosched.util.actionmodecompat.ActionMode; import com.actionbarsherlock.app.SherlockListFragment; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.res.Resources; 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.provider.BaseColumns; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.TextUtils; import android.text.format.DateUtils; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnLongClickListener; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A fragment that shows the user's customized schedule, including sessions that she has chosen, * and common conference items such as keynote sessions, lunch breaks, after hours party, etc. */ public class MyScheduleFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor>, ActionMode.Callback { private static final String TAG = makeLogTag(MyScheduleFragment.class); private SimpleSectionedListAdapter mAdapter; private MyScheduleAdapter mScheduleAdapter; private SparseArray<String> mLongClickedItemData; private View mLongClickedView; private ActionMode mActionMode; private boolean mScrollToNow; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // The MyScheduleAdapter is wrapped in a SimpleSectionedListAdapter so that // we can show list headers separating out the different days of the conference // (Wednesday/Thursday/Friday). mScheduleAdapter = new MyScheduleAdapter(getActivity()); mAdapter = new SimpleSectionedListAdapter(getActivity(), R.layout.list_item_schedule_header, mScheduleAdapter); setListAdapter(mAdapter); if (savedInstanceState == null) { mScrollToNow = true; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate( R.layout.fragment_list_with_empty_container, container, false); inflater.inflate(R.layout.empty_waiting_for_sync, (ViewGroup) root.findViewById(android.R.id.empty), true); root.setBackgroundColor(Color.WHITE); ListView listView = (ListView) root.findViewById(android.R.id.list); listView.setItemsCanFocus(true); listView.setCacheColorHint(Color.WHITE); listView.setSelector(android.R.color.transparent); //listView.setEmptyView(root.findViewById(android.R.id.empty)); return root; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // 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(0, null, this); } private final ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (getActivity() == null) { return; } Loader<Cursor> loader = getLoaderManager().getLoader(0); if (loader != null) { loader.forceLoad(); } } }; @Override public void onAttach(Activity activity) { super.onAttach(activity); activity.getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mObserver); } @Override public void onDetach() { super.onDetach(); getActivity().getContentResolver().unregisterContentObserver(mObserver); } // LoaderCallbacks @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(getActivity(), ScheduleContract.Blocks.CONTENT_URI, BlocksQuery.PROJECTION, null, null, ScheduleContract.Blocks.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } long currentTime = UIUtils.getCurrentTime(getActivity()); int firstNowPosition = ListView.INVALID_POSITION; List<SimpleSectionedListAdapter.Section> sections = new ArrayList<SimpleSectionedListAdapter.Section>(); cursor.moveToFirst(); long previousBlockStart = -1; long blockStart, blockEnd; while (!cursor.isAfterLast()) { blockStart = cursor.getLong(BlocksQuery.BLOCK_START); blockEnd = cursor.getLong(BlocksQuery.BLOCK_END); if (!UIUtils.isSameDay(previousBlockStart, blockStart)) { sections.add(new SimpleSectionedListAdapter.Section(cursor.getPosition(), DateUtils.formatDateTime(getActivity(), blockStart, DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY))); } if (mScrollToNow && firstNowPosition == ListView.INVALID_POSITION // if we're currently in this block, or we're not in a block // and this // block is in the future, then this is the scroll position && ((blockStart < currentTime && currentTime < blockEnd) || blockStart > currentTime)) { firstNowPosition = cursor.getPosition(); } previousBlockStart = blockStart; cursor.moveToNext(); } mScheduleAdapter.changeCursor(cursor); SimpleSectionedListAdapter.Section[] dummy = new SimpleSectionedListAdapter.Section[sections.size()]; mAdapter.setSections(sections.toArray(dummy)); if (mScrollToNow && firstNowPosition != ListView.INVALID_POSITION) { firstNowPosition = mAdapter.positionToSectionedPosition(firstNowPosition); getListView().setSelectionFromTop(firstNowPosition, getResources().getDimensionPixelSize(R.dimen.list_scroll_top_offset)); mScrollToNow = false; } } @Override public void onLoaderReset(Loader<Cursor> loader) { } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { SessionsHelper helper = new SessionsHelper(getActivity()); String title = mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_TITLE); String hashtags = mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_HASHTAGS); String url = mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_URL); boolean handled = false; switch (item.getItemId()) { case R.id.menu_map: String roomId = mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_ROOM_ID); helper.startMapActivity(roomId); handled = true; break; case R.id.menu_star: String sessionId = mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_ID); Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId); helper.setSessionStarred(sessionUri, false, title); handled = true; break; 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, title, hashtags, url); handled = true; break; case R.id.menu_social_stream: helper.startSocialStream(hashtags); handled = true; break; default: LOGW(TAG, "Unknown action taken"); } mActionMode.finish(); return handled; } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.sessions_context, menu); MenuItem starMenuItem = menu.findItem(R.id.menu_star); starMenuItem.setTitle(R.string.description_remove_schedule); starMenuItem.setIcon(R.drawable.ic_action_remove_schedule); return true; } @Override public void onDestroyActionMode(ActionMode mode) { mActionMode = null; if (mLongClickedView != null) { UIUtils.setActivatedCompat(mLongClickedView, false); } } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } /** * A list adapter that shows schedule blocks as list items. It handles a number of different * cases, such as empty blocks where the user has not chosen a session, blocks with conflicts * (i.e. multiple sessions chosen), non-session blocks, etc. */ private class MyScheduleAdapter extends CursorAdapter { public MyScheduleAdapter(Context context) { super(context, null, false); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_schedule_block, parent, false); } @Override public void bindView(View view, Context context, final Cursor cursor) { final String type = cursor.getString(BlocksQuery.BLOCK_TYPE); final String blockId = cursor.getString(BlocksQuery.BLOCK_ID); final String blockTitle = cursor.getString(BlocksQuery.BLOCK_TITLE); final long blockStart = cursor.getLong(BlocksQuery.BLOCK_START); final long blockEnd = cursor.getLong(BlocksQuery.BLOCK_END); final String blockMeta = cursor.getString(BlocksQuery.BLOCK_META); final String blockTimeString = UIUtils.formatBlockTimeString(blockStart, blockEnd, context); final TextView timeView = (TextView) view.findViewById(R.id.block_time); final TextView titleView = (TextView) view.findViewById(R.id.block_title); final TextView subtitleView = (TextView) view.findViewById(R.id.block_subtitle); final ImageButton extraButton = (ImageButton) view.findViewById(R.id.extra_button); final View primaryTouchTargetView = view.findViewById(R.id.list_item_middle_container); final Resources res = getResources(); String subtitle; boolean isLiveStreamed = false; primaryTouchTargetView.setOnLongClickListener(null); UIUtils.setActivatedCompat(primaryTouchTargetView, false); if (ParserUtils.BLOCK_TYPE_SESSION.equals(type) || ParserUtils.BLOCK_TYPE_CODE_LAB.equals(type)) { final int numStarredSessions = cursor.getInt(BlocksQuery.NUM_STARRED_SESSIONS); final String starredSessionId = cursor.getString(BlocksQuery.STARRED_SESSION_ID); View.OnClickListener allSessionsListener = new View.OnClickListener() { @Override public void onClick(View view) { final Uri sessionsUri = ScheduleContract.Blocks.buildSessionsUri(blockId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.putExtra(Intent.EXTRA_TITLE, blockTimeString); startActivity(intent); } }; if (numStarredSessions == 0) { // 0 sessions starred titleView.setText(getString(R.string.schedule_empty_slot_title_template, TextUtils.isEmpty(blockTitle) ? "" : (" " + blockTitle.toLowerCase()))); titleView.setTextColor(res.getColorStateList(R.color.body_text_1_positive)); subtitle = getString(R.string.schedule_empty_slot_subtitle); extraButton.setVisibility(View.GONE); primaryTouchTargetView.setOnClickListener(allSessionsListener); } else if (numStarredSessions == 1) { // exactly 1 session starred final String starredSessionTitle = cursor.getString(BlocksQuery.STARRED_SESSION_TITLE); titleView.setText(starredSessionTitle); titleView.setTextColor(res.getColorStateList(R.color.body_text_1)); subtitle = cursor.getString(BlocksQuery.STARRED_SESSION_ROOM_NAME); if (subtitle == null) { // TODO: remove this WAR for API not returning rooms for code labs subtitle = getString( starredSessionTitle.contains("Code Lab") ? R.string.codelab_room : R.string.unknown_room); } isLiveStreamed = !TextUtils.isEmpty( cursor.getString(BlocksQuery.STARRED_SESSION_LIVESTREAM_URL)); extraButton.setVisibility(View.VISIBLE); extraButton.setOnClickListener(allSessionsListener); if (mLongClickedItemData != null && mActionMode != null && mLongClickedItemData.get(BlocksQuery.STARRED_SESSION_ID, "").equals( starredSessionId)) { UIUtils.setActivatedCompat(primaryTouchTargetView, true); mLongClickedView = primaryTouchTargetView; } primaryTouchTargetView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Uri sessionUri = ScheduleContract.Sessions.buildSessionUri( starredSessionId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionUri); intent.putExtra(SessionsVendorsMultiPaneActivity.EXTRA_MASTER_URI, ScheduleContract.Blocks.buildSessionsUri(blockId)); intent.putExtra(Intent.EXTRA_TITLE, blockTimeString); startActivity(intent); } }); primaryTouchTargetView.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { if (mActionMode != null) { // CAB already displayed, ignore return true; } mLongClickedView = primaryTouchTargetView; String hashtags = cursor.getString(BlocksQuery.STARRED_SESSION_HASHTAGS); String url = cursor.getString(BlocksQuery.STARRED_SESSION_URL); String roomId = cursor.getString(BlocksQuery.STARRED_SESSION_ROOM_ID); mLongClickedItemData = new SparseArray<String>(); mLongClickedItemData.put(BlocksQuery.STARRED_SESSION_ID, starredSessionId); mLongClickedItemData.put(BlocksQuery.STARRED_SESSION_TITLE, starredSessionTitle); mLongClickedItemData.put(BlocksQuery.STARRED_SESSION_HASHTAGS, hashtags); mLongClickedItemData.put(BlocksQuery.STARRED_SESSION_URL, url); mLongClickedItemData.put(BlocksQuery.STARRED_SESSION_ROOM_ID, roomId); mActionMode = ActionMode.start(getActivity(), MyScheduleFragment.this); UIUtils.setActivatedCompat(primaryTouchTargetView, true); return true; } }); } else { // 2 or more sessions starred titleView.setText(getString(R.string.schedule_conflict_title, numStarredSessions)); titleView.setTextColor(res.getColorStateList(R.color.body_text_1)); subtitle = getString(R.string.schedule_conflict_subtitle); extraButton.setVisibility(View.VISIBLE); extraButton.setOnClickListener(allSessionsListener); primaryTouchTargetView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Uri sessionsUri = ScheduleContract.Blocks .buildStarredSessionsUri( blockId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.putExtra(Intent.EXTRA_TITLE, blockTimeString); startActivity(intent); } }); } subtitleView.setTextColor(res.getColorStateList(R.color.body_text_2)); primaryTouchTargetView.setEnabled(true); } else if (ParserUtils.BLOCK_TYPE_KEYNOTE.equals(type)) { final String starredSessionId = cursor.getString(BlocksQuery.STARRED_SESSION_ID); final String starredSessionTitle = cursor.getString(BlocksQuery.STARRED_SESSION_TITLE); long currentTimeMillis = UIUtils.getCurrentTime(context); boolean past = (currentTimeMillis > blockEnd && currentTimeMillis < UIUtils.CONFERENCE_END_MILLIS); boolean present = !past && (currentTimeMillis >= blockStart); boolean canViewStream = present && UIUtils.hasHoneycomb(); isLiveStreamed = true; titleView.setTextColor(canViewStream ? res.getColorStateList(R.color.body_text_1) : res.getColorStateList(R.color.body_text_disabled)); subtitleView.setTextColor(canViewStream ? res.getColorStateList(R.color.body_text_2) : res.getColorStateList(R.color.body_text_disabled)); subtitle = getString(R.string.keynote_room); titleView.setText(starredSessionTitle); extraButton.setVisibility(View.GONE); primaryTouchTargetView.setEnabled(canViewStream); primaryTouchTargetView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Uri sessionUri = ScheduleContract.Sessions.buildSessionUri( starredSessionId); Intent livestreamIntent = new Intent(Intent.ACTION_VIEW, sessionUri); livestreamIntent.setClass(getActivity(), SessionLivestreamActivity.class); startActivity(livestreamIntent); } }); } else { titleView.setTextColor(res.getColorStateList(R.color.body_text_disabled)); subtitleView.setTextColor(res.getColorStateList(R.color.body_text_disabled)); subtitle = blockMeta; titleView.setText(blockTitle); extraButton.setVisibility(View.GONE); primaryTouchTargetView.setEnabled(false); primaryTouchTargetView.setOnClickListener(null); } timeView.setText(DateUtils.formatDateTime(context, blockStart, DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR)); // Show past/present/future and livestream status for this block. UIUtils.updateTimeAndLivestreamBlockUI(context, blockStart, blockEnd, isLiveStreamed, view, titleView, subtitleView, subtitle); } } private interface BlocksQuery { String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Blocks.BLOCK_ID, ScheduleContract.Blocks.BLOCK_TITLE, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Blocks.BLOCK_TYPE, ScheduleContract.Blocks.BLOCK_META, ScheduleContract.Blocks.SESSIONS_COUNT, ScheduleContract.Blocks.NUM_STARRED_SESSIONS, ScheduleContract.Blocks.STARRED_SESSION_ID, ScheduleContract.Blocks.STARRED_SESSION_TITLE, ScheduleContract.Blocks.STARRED_SESSION_ROOM_NAME, ScheduleContract.Blocks.STARRED_SESSION_ROOM_ID, ScheduleContract.Blocks.STARRED_SESSION_HASHTAGS, ScheduleContract.Blocks.STARRED_SESSION_URL, ScheduleContract.Blocks.STARRED_SESSION_LIVESTREAM_URL, }; int _ID = 0; int BLOCK_ID = 1; int BLOCK_TITLE = 2; int BLOCK_START = 3; int BLOCK_END = 4; int BLOCK_TYPE = 5; int BLOCK_META = 6; int SESSIONS_COUNT = 7; int NUM_STARRED_SESSIONS = 8; int STARRED_SESSION_ID = 9; int STARRED_SESSION_TITLE = 10; int STARRED_SESSION_ROOM_NAME = 11; int STARRED_SESSION_ROOM_ID = 12; int STARRED_SESSION_HASHTAGS = 13; int STARRED_SESSION_URL = 14; int STARRED_SESSION_LIVESTREAM_URL = 15; } }
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.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.ReflectionUtils; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import android.annotation.TargetApi; import android.app.AlertDialog; import android.app.SearchManager; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.nfc.NfcAdapter; import android.nfc.NfcEvent; 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.widget.SearchView; 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 { private boolean mTwoPane; private SessionsFragment mSessionsFragment; private Fragment mDetailFragment; @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); } @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().trackView("Search: " + query); LOGD("Tracker", "Search: " + query); updateDetailBackground(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.search, menu); setupSearchMenuItem(menu); return true; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupSearchMenuItem(Menu 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.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; } }); } } } @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); trySetBeamCallback(); 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; } } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void trySetBeamCallback() { if (UIUtils.hasICS()) { BeamUtils.setBeamCompleteCallback(this, new NfcAdapter.OnNdefPushCompleteCallback() { @Override public void onNdefPushComplete(NfcEvent event) { // Beam has been sent if (!BeamUtils.isBeamUnlocked(SearchActivity.this)) { BeamUtils.setBeamUnlocked(SearchActivity.this); runOnUiThread(new Runnable() { @Override public void run() { showFirstBeamDialog(); } }); } } }); } } private void showFirstBeamDialog() { new AlertDialog.Builder(this) .setTitle(R.string.just_beamed) .setMessage(R.string.beam_unlocked_session) .setNegativeButton(R.string.close, null) .setPositiveButton(R.string.view_beam_session, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { BeamUtils.launchBeamSession(SearchActivity.this); di.dismiss(); } }) .create() .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 com.google.analytics.tracking.android.EasyTracker; 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.gcm.ServerUtilities; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.gtv.GoogleTVSessionLivestreamActivity; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.HelpUtils; import com.google.android.apps.iosched.util.UIUtils; import com.google.android.gcm.GCMRegistrar; import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; 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.ViewPager; import android.text.TextUtils; import android.widget.SearchView; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * The landing screen for the app, once the user has logged in. * * <p>This activity uses different layouts to present its various fragments, depending on the * device configuration. {@link MyScheduleFragment}, {@link ExploreFragment}, and * {@link SocialStreamFragment} are always available to the user. {@link WhatsOnFragment} is * always available on tablets and phones in portrait, but is hidden on phones held in landscape. * * <p>On phone-size screens, the three fragments are represented by {@link ActionBar} tabs, and * can are held inside a {@link ViewPager} to allow horizontal swiping. * * <p>On tablets, the three fragments are always visible and are presented as either three panes * (landscape) or a grid (portrait). */ public class HomeActivity extends BaseActivity implements ActionBar.TabListener, ViewPager.OnPageChangeListener { private static final String TAG = makeLogTag(HomeActivity.class); private Object mSyncObserverHandle; private MyScheduleFragment mMyScheduleFragment; private ExploreFragment mExploreFragment; private SocialStreamFragment mSocialStreamFragment; private ViewPager mViewPager; private Menu mOptionsMenu; private AsyncTask<Void, Void, Void> mGCMRegisterTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // We're on Google TV; immediately short-circuit the normal behavior and show the // Google TV-specific landing page. if (UIUtils.isGoogleTV(this)) { Intent intent = new Intent(HomeActivity.this, GoogleTVSessionLivestreamActivity.class); startActivity(intent); finish(); } if (isFinishing()) { return; } UIUtils.enableDisableActivities(this); EasyTracker.getTracker().setContext(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)); homeScreenLabel = getString(R.string.title_my_schedule); } else { mExploreFragment = (ExploreFragment) fm.findFragmentById(R.id.fragment_tracks); mMyScheduleFragment = (MyScheduleFragment) fm.findFragmentById( R.id.fragment_my_schedule); mSocialStreamFragment = (SocialStreamFragment) fm.findFragmentById(R.id.fragment_stream); homeScreenLabel = "Home"; } getSupportActionBar().setHomeButtonEnabled(false); EasyTracker.getTracker().trackView(homeScreenLabel); LOGD("Tracker", homeScreenLabel); // Sync data on load if (savedInstanceState == null) { triggerRefresh(); registerGCMClient(); } } private void registerGCMClient() { GCMRegistrar.checkDevice(this); if (BuildConfig.DEBUG) { 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, check server. if (GCMRegistrar.isRegisteredOnServer(this)) { // Skips registration LOGI(TAG, "Already registered on the GCM server"); } else { // Try to register again, but not on the UI thread. // It's also necessary to cancel the task in onDestroy(). mGCMRegisterTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { boolean registered = ServerUtilities.register(HomeActivity.this, regId); if (!registered) { // 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. 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, "GCM 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().trackView(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 (mMyScheduleFragment = new MyScheduleFragment()); case 1: return (mExploreFragment = new ExploreFragment()); case 2: return (mSocialStreamFragment = new SocialStreamFragment()); } return null; } @Override public int getCount() { return 3; } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); mOptionsMenu = menu; getSupportMenuInflater().inflate(R.menu.home, menu); setupSearchMenuItem(menu); if (!BeamUtils.isBeamUnlocked(this)) { // Only show Beam unlocked after first Beam MenuItem beamItem = menu.findItem(R.id.menu_beam); if (beamItem != null) { menu.removeItem(beamItem.getItemId()); } } return true; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupSearchMenuItem(Menu 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())); } } } @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_sign_out: AccountUtils.signOut(this); finish(); return true; case R.id.menu_beam: Intent beamIntent = new Intent(this, BeamActivity.class); startActivity(beamIntent); return true; } return super.onOptionsItemSelected(item); } private void triggerRefresh() { Bundle extras = new Bundle(); extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); if (!UIUtils.isGoogleTV(this)) { ContentResolver.requestSync( new Account(AccountUtils.getChosenAccountName(this), GoogleAccountManager.ACCOUNT_TYPE), ScheduleContract.CONTENT_AUTHORITY, extras); } 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); } public void setRefreshActionButtonState(boolean refreshing) { if (mOptionsMenu == null) { return; } final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_refresh); if (refreshItem != null) { if (refreshing) { refreshItem.setActionView(R.layout.actionbar_indeterminate_progress); } else { refreshItem.setActionView(null); } } } private final 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, GoogleAccountManager.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 com.google.android.apps.iosched.R; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import android.os.Bundle; import android.support.v4.app.Fragment; /** * A single-pane activity that shows a {@link SocialStreamFragment}. */ public class SocialStreamActivity extends SimpleSinglePaneActivity { @Override protected Fragment onCreatePane() { return new SocialStreamFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); setTitle(getIntent().getStringExtra(SocialStreamFragment.EXTRA_QUERY)); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.social_stream_standalone, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_refresh: ((SocialStreamFragment) getFragment()).refresh(); return true; } return super.onOptionsItemSelected(item); } }
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 com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.SherlockListFragment; 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.text.Spannable; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.TextView; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; import static com.google.android.apps.iosched.util.UIUtils.buildStyledSnippet; /** * A {@link ListFragment} showing a list of developer sandbox companies. */ public class VendorsFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final String TAG = makeLogTag(VendorsFragment.class); private static final String STATE_SELECTED_ID = "selectedId"; private Uri mVendorsUri; private CursorAdapter mAdapter; private String mSelectedVendorId; private boolean mHasSetEmptyText = false; public interface Callbacks { /** Return true to select (activate) the vendor in the list, false otherwise. */ public boolean onVendorSelected(String vendorId); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public boolean onVendorSelected(String vendorId) { return true; } }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { mSelectedVendorId = savedInstanceState.getString(STATE_SELECTED_ID); } reloadFromArguments(getArguments()); } public void reloadFromArguments(Bundle arguments) { // Teardown from previous arguments setListAdapter(null); // Load new arguments final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments); mVendorsUri = intent.getData(); final int vendorQueryToken; if (mVendorsUri == null) { return; } mAdapter = new VendorsAdapter(getActivity()); vendorQueryToken = VendorsQuery._TOKEN; setListAdapter(mAdapter); // Start background query to load vendors getLoaderManager().initLoader(vendorQueryToken, null, this); } public void setSelectedVendorId(String id) { mSelectedVendorId = 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 onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (!mHasSetEmptyText) { // Could be a bug, but calling this twice makes it become visible // when it shouldn't be visible. setEmptyText(getString(R.string.empty_vendors)); mHasSetEmptyText = true; } } @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 (mSelectedVendorId != null) { outState.putString(STATE_SELECTED_ID, mSelectedVendorId); } } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position); String vendorId = cursor.getString(VendorsQuery.VENDOR_ID); if (mCallbacks.onVendorSelected(vendorId)) { mSelectedVendorId = vendorId; mAdapter.notifyDataSetChanged(); } } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(getActivity(), mVendorsUri, VendorsQuery.PROJECTION, null, null, ScheduleContract.Vendors.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } int token = loader.getId(); if (token == VendorsQuery._TOKEN) { mAdapter.changeCursor(cursor); } else { cursor.close(); } } @Override public void onLoaderReset(Loader<Cursor> cursor) { } /** * {@link CursorAdapter} that renders a {@link VendorsQuery}. */ private class VendorsAdapter extends CursorAdapter { public VendorsAdapter(Context context) { super(context, null, false); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_vendor, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { UIUtils.setActivatedCompat(view, cursor.getString(VendorsQuery.VENDOR_ID) .equals(mSelectedVendorId)); ((TextView) view.findViewById(R.id.vendor_name)).setText( cursor.getString(VendorsQuery.NAME)); } } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Vendors} * query parameters. */ private interface VendorsQuery { int _TOKEN = 0x1; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Vendors.VENDOR_ID, ScheduleContract.Vendors.VENDOR_NAME, }; int _ID = 0; int VENDOR_ID = 1; int NAME = 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.widget; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A layout that supports the Show/Hide pattern for portrait tablet layouts. See <a * href="http://developer.android.com/design/patterns/multi-pane-layouts.html#orientation">Android * Design &gt; Patterns &gt; Multi-pane Layouts & gt; Compound Views and Orientation Changes</a> for * more details on this pattern. This layout should normally be used in association with the Up * button. Specifically, show the master pane using {@link #showMaster(boolean, int)} when the Up * button is pressed. If the master pane is visible, defer to normal Up behavior. * * <p>TODO: swiping should be more tactile and actually follow the user's finger. * * <p>Requires API level 11 */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class ShowHideMasterLayout extends ViewGroup implements Animator.AnimatorListener { private static final String TAG = makeLogTag(ShowHideMasterLayout.class); /** * A flag for {@link #showMaster(boolean, int)} indicating that the change in visiblity should * not be animated. */ public static final int FLAG_IMMEDIATE = 0x1; private boolean mFirstShow = true; private boolean mMasterVisible = true; private View mMasterView; private View mDetailView; private OnMasterVisibilityChangedListener mOnMasterVisibilityChangedListener; private GestureDetector mGestureDetector; private boolean mFlingToExposeMaster; private boolean mIsAnimating; private Runnable mShowMasterCompleteRunnable; // The last measured master width, including its margins. private int mTranslateAmount; public interface OnMasterVisibilityChangedListener { public void onMasterVisibilityChanged(boolean visible); } public ShowHideMasterLayout(Context context) { super(context); init(); } public ShowHideMasterLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ShowHideMasterLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { mGestureDetector = new GestureDetector(getContext(), mGestureListener); } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new MarginLayoutParams(getContext(), attrs); } @Override protected LayoutParams generateLayoutParams(LayoutParams p) { return new MarginLayoutParams(p); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int count = getChildCount(); // Measure once to find the maximum child size. int maxHeight = 0; int maxWidth = 0; int childState = 0; for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0); final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); maxWidth = Math.max(maxWidth, child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin); maxHeight = Math.max(maxHeight, child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin); childState = combineMeasuredStates(childState, child.getMeasuredState()); } // Account for padding too maxWidth += getPaddingLeft() + getPaddingRight(); maxHeight += getPaddingLeft() + getPaddingRight(); // Check against our minimum height and width maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight()); maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth()); // Set our own measured size setMeasuredDimension( resolveSizeAndState(maxWidth, widthMeasureSpec, childState), resolveSizeAndState(maxHeight, heightMeasureSpec, childState << MEASURED_HEIGHT_STATE_SHIFT)); // Measure children for them to set their measured dimensions for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); int childWidthMeasureSpec; int childHeightMeasureSpec; if (lp.width == LayoutParams.MATCH_PARENT) { childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth() - getPaddingLeft() - getPaddingRight() - lp.leftMargin - lp.rightMargin, MeasureSpec.EXACTLY); } else { childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin, lp.width); } if (lp.height == LayoutParams.MATCH_PARENT) { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight() - getPaddingTop() - getPaddingBottom() - lp.topMargin - lp.bottomMargin, MeasureSpec.EXACTLY); } else { childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec, getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin, lp.height); } child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { updateChildReferences(); if (mMasterView == null || mDetailView == null) { LOGW(TAG, "Master or detail is missing (need 2 children), can't layout."); return; } int masterWidth = mMasterView.getMeasuredWidth(); MarginLayoutParams masterLp = (MarginLayoutParams) mMasterView.getLayoutParams(); MarginLayoutParams detailLp = (MarginLayoutParams) mDetailView.getLayoutParams(); mTranslateAmount = masterWidth + masterLp.leftMargin + masterLp.rightMargin; mMasterView.layout( l + masterLp.leftMargin, t + masterLp.topMargin, l + masterLp.leftMargin + masterWidth, b - masterLp.bottomMargin); mDetailView.layout( l + detailLp.leftMargin + mTranslateAmount, t + detailLp.topMargin, r - detailLp.rightMargin + mTranslateAmount, b - detailLp.bottomMargin); // Update translationX values if (!mIsAnimating) { final float translationX = mMasterVisible ? 0 : -mTranslateAmount; mMasterView.setTranslationX(translationX); mDetailView.setTranslationX(translationX); } } private void updateChildReferences() { int childCount = getChildCount(); mMasterView = (childCount > 0) ? getChildAt(0) : null; mDetailView = (childCount > 1) ? getChildAt(1) : null; } /** * Allow or disallow the user to flick right on the detail pane to expose the master pane. * @param enabled Whether or not to enable this interaction. */ public void setFlingToExposeMasterEnabled(boolean enabled) { mFlingToExposeMaster = enabled; } /** * Request the given listener be notified when the master pane is shown or hidden. * * @param listener The listener to notify when the master pane is shown or hidden. */ public void setOnMasterVisibilityChangedListener(OnMasterVisibilityChangedListener listener) { mOnMasterVisibilityChangedListener = listener; } /** * Returns whether or not the master pane is visible. * * @return True if the master pane is visible. */ public boolean isMasterVisible() { return mMasterVisible; } /** * Calls {@link #showMaster(boolean, int, Runnable)} with a null runnable. */ public void showMaster(boolean show, int flags) { showMaster(show, flags, null); } /** * Shows or hides the master pane. * * @param show Whether or not to show the master pane. * @param flags {@link #FLAG_IMMEDIATE} to show/hide immediately, or 0 to animate. * @param completeRunnable An optional runnable to run when any animations related to this are * complete. */ public void showMaster(boolean show, int flags, Runnable completeRunnable) { if (!mFirstShow && mMasterVisible == show) { return; } mShowMasterCompleteRunnable = completeRunnable; mFirstShow = false; mMasterVisible = show; if (mOnMasterVisibilityChangedListener != null) { mOnMasterVisibilityChangedListener.onMasterVisibilityChanged(show); } updateChildReferences(); if (mMasterView == null || mDetailView == null) { LOGW(TAG, "Master or detail is missing (need 2 children), can't change translation."); return; } final float translationX = show ? 0 : -mTranslateAmount; if ((flags & FLAG_IMMEDIATE) != 0) { mMasterView.setTranslationX(translationX); mDetailView.setTranslationX(translationX); if (mShowMasterCompleteRunnable != null) { mShowMasterCompleteRunnable.run(); mShowMasterCompleteRunnable = null; } } else { final long duration = getResources().getInteger(android.R.integer.config_shortAnimTime); // Animate if we have Honeycomb APIs, don't animate otherwise mIsAnimating = true; AnimatorSet animatorSet = new AnimatorSet(); mMasterView.setLayerType(LAYER_TYPE_HARDWARE, null); mDetailView.setLayerType(LAYER_TYPE_HARDWARE, null); animatorSet .play(ObjectAnimator .ofFloat(mMasterView, "translationX", translationX) .setDuration(duration)) .with(ObjectAnimator .ofFloat(mDetailView, "translationX", translationX) .setDuration(duration)); animatorSet.addListener(this); animatorSet.start(); // For API level 12+, use this instead: // mMasterView.animate().translationX().setDuration(duration); // mDetailView.animate().translationX(show ? masterWidth : 0).setDuration(duration); } } @Override public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { // Really bad hack... we really shouldn't do this. //super.requestDisallowInterceptTouchEvent(disallowIntercept); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { if (mFlingToExposeMaster && !mMasterVisible) { mGestureDetector.onTouchEvent(event); } if (event.getAction() == MotionEvent.ACTION_DOWN && mMasterView != null && mMasterVisible) { // If the master is visible, touching in the detail area should hide the master. if (event.getX() > mTranslateAmount) { return true; } } return super.onInterceptTouchEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) { if (mFlingToExposeMaster && !mMasterVisible && mGestureDetector.onTouchEvent(event)) { return true; } if (event.getAction() == MotionEvent.ACTION_DOWN && mMasterView != null && mMasterVisible) { // If the master is visible, touching in the detail area should hide the master. if (event.getX() > mTranslateAmount) { showMaster(false, 0); return true; } } return super.onTouchEvent(event); } @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { mIsAnimating = false; mMasterView.setLayerType(LAYER_TYPE_NONE, null); mDetailView.setLayerType(LAYER_TYPE_NONE, null); requestLayout(); if (mShowMasterCompleteRunnable != null) { mShowMasterCompleteRunnable.run(); mShowMasterCompleteRunnable = null; } } @Override public void onAnimationCancel(Animator animator) { mIsAnimating = false; mMasterView.setLayerType(LAYER_TYPE_NONE, null); mDetailView.setLayerType(LAYER_TYPE_NONE, null); requestLayout(); if (mShowMasterCompleteRunnable != null) { mShowMasterCompleteRunnable.run(); mShowMasterCompleteRunnable = null; } } @Override public void onAnimationRepeat(Animator animator) { } private final GestureDetector.OnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent e) { return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { ViewConfiguration viewConfig = ViewConfiguration.get(getContext()); float absVelocityX = Math.abs(velocityX); float absVelocityY = Math.abs(velocityY); if (mFlingToExposeMaster && !mMasterVisible && velocityX > 0 && absVelocityX >= absVelocityY // Fling at least as hard in X as in Y && absVelocityX > viewConfig.getScaledMinimumFlingVelocity() && absVelocityX < viewConfig.getScaledMaximumFlingVelocity()) { showMaster(true, 0); return true; } return super.onFling(e1, e2, velocityX, velocityY); } }; }
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.database.DataSetObserver; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.Arrays; import java.util.Comparator; public class SimpleSectionedListAdapter extends BaseAdapter { private boolean mValid = true; private int mSectionResourceId; private LayoutInflater mLayoutInflater; private ListAdapter mBaseAdapter; private SparseArray<Section> mSections = new SparseArray<Section>(); public static class Section { int firstPosition; int sectionedPosition; CharSequence title; public Section(int firstPosition, CharSequence title) { this.firstPosition = firstPosition; this.title = title; } public CharSequence getTitle() { return title; } } public SimpleSectionedListAdapter(Context context, int sectionResourceId, ListAdapter baseAdapter) { mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mSectionResourceId = sectionResourceId; mBaseAdapter = baseAdapter; mBaseAdapter.registerDataSetObserver(new DataSetObserver() { @Override public void onChanged() { mValid = !mBaseAdapter.isEmpty(); notifyDataSetChanged(); } @Override public void onInvalidated() { mValid = false; notifyDataSetInvalidated(); } }); } public void setSections(Section[] sections) { mSections.clear(); Arrays.sort(sections, new Comparator<Section>() { @Override public int compare(Section o, Section o1) { return (o.firstPosition == o1.firstPosition) ? 0 : ((o.firstPosition < o1.firstPosition) ? -1 : 1); } }); int offset = 0; // offset positions for the headers we're adding for (Section section : sections) { section.sectionedPosition = section.firstPosition + offset; mSections.append(section.sectionedPosition, section); ++offset; } notifyDataSetChanged(); } public int positionToSectionedPosition(int position) { int offset = 0; for (int i = 0; i < mSections.size(); i++) { if (mSections.valueAt(i).firstPosition > position) { break; } ++offset; } return position + offset; } public int sectionedPositionToPosition(int sectionedPosition) { if (isSectionHeaderPosition(sectionedPosition)) { return ListView.INVALID_POSITION; } int offset = 0; for (int i = 0; i < mSections.size(); i++) { if (mSections.valueAt(i).sectionedPosition > sectionedPosition) { break; } --offset; } return sectionedPosition + offset; } public boolean isSectionHeaderPosition(int position) { return mSections.get(position) != null; } @Override public int getCount() { return (mValid ? mBaseAdapter.getCount() + mSections.size() : 0); } @Override public Object getItem(int position) { return isSectionHeaderPosition(position) ? mSections.get(position) : mBaseAdapter.getItem(sectionedPositionToPosition(position)); } @Override public long getItemId(int position) { return isSectionHeaderPosition(position) ? Integer.MAX_VALUE - mSections.indexOfKey(position) : mBaseAdapter.getItemId(sectionedPositionToPosition(position)); } @Override public int getItemViewType(int position) { return isSectionHeaderPosition(position) ? getViewTypeCount() - 1 : mBaseAdapter.getItemViewType(position); } @Override public boolean isEnabled(int position) { //noinspection SimplifiableConditionalExpression return isSectionHeaderPosition(position) ? false : mBaseAdapter.isEnabled(sectionedPositionToPosition(position)); } @Override public int getViewTypeCount() { return mBaseAdapter.getViewTypeCount() + 1; // the section headings } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean hasStableIds() { return mBaseAdapter.hasStableIds(); } @Override public boolean isEmpty() { return mBaseAdapter.isEmpty(); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (isSectionHeaderPosition(position)) { TextView view = (TextView) convertView; if (view == null) { view = (TextView) mLayoutInflater.inflate(mSectionResourceId, parent, false); } view.setText(mSections.get(position).title); return view; } else { return mBaseAdapter.getView(sectionedPositionToPosition(position), convertView, parent); } } }
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.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.widget.ImageView; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * An {@link 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 static final String TAG = makeLogTag(BezelImageView.class); private Paint mMaskedPaint; private Rect mBounds; private RectF mBoundsF; private Drawable mBorderDrawable; private Drawable mMaskDrawable; private boolean mGuardInvalidate; // prevents stack overflows 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 = getResources().getDrawable(R.drawable.bezel_mask); } mMaskDrawable.setCallback(this); mBorderDrawable = a.getDrawable(R.styleable.BezelImageView_borderDrawable); if (mBorderDrawable == null) { mBorderDrawable = getResources().getDrawable(R.drawable.bezel_border_default); } mBorderDrawable.setCallback(this); a.recycle(); // Other initialization mMaskedPaint = new Paint(); mMaskedPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)); } private Bitmap mCached; private void invalidateCache() { if (mBounds == null || mBounds.width() == 0 || mBounds.height() == 0) { return; } if (mCached != null) { mCached.recycle(); mCached = null; } mCached = Bitmap.createBitmap(mBounds.width(), mBounds.height(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(mCached); int sc = canvas.saveLayer(mBoundsF, null, Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG); mMaskDrawable.draw(canvas); canvas.saveLayer(mBoundsF, mMaskedPaint, 0); // certain drawables invalidate themselves on draw, e.g. TransitionDrawable sets its alpha // which invalidates itself. to prevent stack overflow errors, we must guard the // invalidation (see specialized behavior when guarded in invalidate() below). mGuardInvalidate = true; super.onDraw(canvas); mGuardInvalidate = false; canvas.restoreToCount(sc); mBorderDrawable.draw(canvas); } @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); mBorderDrawable.setBounds(mBounds); mMaskDrawable.setBounds(mBounds); if (changed) { invalidateCache(); } return changed; } @Override protected void onDraw(Canvas canvas) { if (mCached == null) { invalidateCache(); } if (mCached != null) { canvas.drawBitmap(mCached, mBounds.left, mBounds.top, null); } //super.onDraw(canvas); } @Override protected void drawableStateChanged() { super.drawableStateChanged(); if (mBorderDrawable.isStateful()) { mBorderDrawable.setState(getDrawableState()); } if (mMaskDrawable.isStateful()) { mMaskDrawable.setState(getDrawableState()); } // TODO: may need to invalidate elsewhere invalidate(); } @Override public void invalidate() { if (mGuardInvalidate) { removeCallbacks(mInvalidateCacheRunnable); postDelayed(mInvalidateCacheRunnable, 16); } else { super.invalidate(); invalidateCache(); } } private Runnable mInvalidateCacheRunnable = new Runnable() { @Override public void run() { invalidateCache(); BezelImageView.super.invalidate(); LOGD(TAG, "delayed invalidate"); } }; }
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; /** * A {@link Checkable} {@link FrameLayout}. When this is the root view for an item in a * {@link android.widget.ListView} and the list view has a choice mode of * {@link android.widget.ListView#CHOICE_MODE_MULTIPLE_MODAL }, the list view will * set the item's state to CHECKED and not ACTIVATED. This is important to ensure that we can * use the ACTIVATED state on tablet devices to represent the currently-viewed detail screen, while * allowing multiple-selection. */ 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.util.UIUtils; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; /** * An extremely simple {@link LinearLayout} descendant that simply switches the order of its child * views on Android 4.0+. The reason for this is that on Android, negative buttons should be shown * to the left of positive buttons. */ public class ButtonBar extends LinearLayout { public ButtonBar(Context context) { super(context); } public ButtonBar(Context context, AttributeSet attrs) { super(context, attrs); } public ButtonBar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public View getChildAt(int index) { if (UIUtils.hasICS()) { // Flip the buttons so that we get e.g. "Cancel | OK" on ICS return super.getChildAt(getChildCount() - 1 - index); } return super.getChildAt(index); } }
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.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.api.YouTube; import com.google.android.youtube.api.YouTubePlayer; import com.google.android.youtube.api.YouTubePlayerSupportFragment; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.Window; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.BaseColumns; 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.app.NavUtils; 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.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; 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 java.util.ArrayList; 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.OnPlaybackEventsListener, YouTubePlayer.OnFullscreenListener, ActionBar.OnNavigationListener { private static final String TAG = makeLogTag(SessionLivestreamActivity.class); private static final String EXTRA_PREFIX = "com.google.android.iosched.extra."; 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 LOADER_SESSIONS_ARG = "futureSessions"; 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 int mNormalScreenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; private TabHost mTabHost; private TabsAdapter mTabsAdapter; private YouTubePlayerSupportFragment mYouTubePlayer; private LinearLayout mPlayerContainer; private String mYouTubeVideoId; private LinearLayout mMainLayout; private LinearLayout mVideoLayout; private LinearLayout mExtraLayout; private FrameLayout mSummaryLayout; private FrameLayout mFullscreenCaptions; private MenuItem mCaptionsMenuItem; private MenuItem mShareMenuItem; private Runnable mShareMenuDeferredSetup; private Runnable mSessionSummaryDeferredSetup; private SessionShareData mSessionShareData; private boolean mSessionsFound; private boolean isKeynote = false; private Handler mHandler = new Handler(); private LivestreamAdapter mLivestreamAdapter; private Uri mSessionUri; private String mSessionId; private String mTrackName; @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); YouTube.initialize(this, Config.YOUTUBE_API_KEY); setContentView(R.layout.activity_session_livestream); mIsTablet = UIUtils.isHoneycombTablet(this); // Set up YouTube player mYouTubePlayer = (YouTubePlayerSupportFragment) getSupportFragmentManager() .findFragmentById(R.id.livestream_player); mYouTubePlayer.enableCustomFullscreen(this); mYouTubePlayer.setOnPlaybackEventsListener(this); int fullscreenControlFlags = YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI | YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION; if (!mIsTablet) { fullscreenControlFlags |= YouTubePlayer.FULLSCREEN_FLAG_FULLSCREEN_WHEN_DEVICE_LANDSCAPE; setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); } mYouTubePlayer.setFullscreenControlFlags(fullscreenControlFlags); // Views that are common over all layouts mMainLayout = (LinearLayout) findViewById(R.id.livestream_mainlayout); 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); 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(this); final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); actionBar.setListNavigationCallbacks(mLivestreamAdapter, this); actionBar.setDisplayShowTitleEnabled(false); } } @Override protected void onResume() { super.onResume(); if (mSessionSummaryDeferredSetup != null) { mSessionSummaryDeferredSetup.run(); mSessionSummaryDeferredSetup = null; } mHandler.postDelayed(mStreamRefreshRunnable, STREAM_REFRESH_TIME); } @Override protected void onPause() { super.onPause(); mHandler.removeCallbacks(mStreamRefreshRunnable); } /** * 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 { 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; navigateUpOrFinish(); } } /** * 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); } @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) { getSupportMenuInflater().inflate(R.menu.session_livestream, menu); mCaptionsMenuItem = menu.findItem(R.id.menu_captions); 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 android.R.id.home: if (mIsFullscreen) { mYouTubePlayer.setFullscreen(false); } else { navigateUpOrFinish(); } return true; 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.SESSION_TITLE, mSessionShareData.SESSION_HASHTAG, mSessionShareData.SESSION_URL); return true; } break; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { if (mIsFullscreen) { // Exit full screen mode on back key mYouTubePlayer.setFullscreen(false); } else { super.onBackPressed(); } } @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); setActionBarColor(cursor.getInt(SessionsQuery.TRACK_COLOR)); 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 { navigateUpOrFinish(); } 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 onLoaded(String s) { } @Override public void onPlaying() { } @Override public void onPaused() { } @Override public void onBuffering(boolean b) { } @Override public void onEnded() { } @Override public void onError() { Toast.makeText(this, R.string.session_livestream_error, Toast.LENGTH_LONG).show(); } 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 navigateUpOrFinish(); return; } mTrackName = trackName; String youtubeVideoId = youtubeUrl; if (youtubeUrl.startsWith("http")) { final Uri youTubeUri = Uri.parse(youtubeUrl); youtubeVideoId = youTubeUri.getQueryParameter("v"); } playVideo(youtubeVideoId); if (mTrackPlay) { EasyTracker.getTracker().trackView("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; if (mIsTablet) { sessionSummaryFragment = (SessionSummaryFragment) getSupportFragmentManager().findFragmentByTag(TAG_SESSION_SUMMARY); } else { 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); } } Runnable mStreamRefreshRunnable = new Runnable() { @Override public void run() { if (mTabsAdapter != null && mTabsAdapter.mFragments != null) { final SocialStreamFragment socialStreamFragment = (SocialStreamFragment) mTabsAdapter.mFragments.get(TABNUM_SOCIAL_STREAM); if (socialStreamFragment != null) { socialStreamFragment.refresh(); } } mHandler.postDelayed(mStreamRefreshRunnable, STREAM_REFRESH_TIME); } }; private void updateTagStreamFragment(String trackHashTag) { String hashTags = UIUtils.CONFERENCE_HASHTAG; if (!TextUtils.isEmpty(trackHashTag)) { hashTags += " " + trackHashTag; } final SocialStreamFragment socialStreamFragment = (SocialStreamFragment) mTabsAdapter.mFragments.get(TABNUM_SOCIAL_STREAM); if (socialStreamFragment != null) { socialStreamFragment.refresh(hashTags); } } private void updateSessionLiveCaptionsFragment(String trackName) { final SessionLiveCaptionsFragment captionsFragment = (SessionLiveCaptionsFragment) mTabsAdapter.mFragments.get(TABNUM_LIVE_CAPTIONS); if (captionsFragment != null) { captionsFragment.setTrackName(trackName); } } private void playVideo(String videoId) { if ((TextUtils.isEmpty(mYouTubeVideoId) || !mYouTubeVideoId.equals(videoId)) && !TextUtils.isEmpty(videoId)) { mYouTubeVideoId = videoId; mYouTubePlayer.loadVideo(mYouTubeVideoId); mTrackPlay = true; if (mSessionShareData != null) { mSessionShareData.SESSION_URL = Config.YOUTUBE_SHARE_URL_PREFIX + mYouTubeVideoId; } } } private void navigateUpOrFinish() { if (mLoadFromExtras || isKeynote) { final Intent homeIntent = new Intent(); homeIntent.setClass(this, HomeActivity.class); NavUtils.navigateUpTo(this, homeIntent); } else if (mSessionUri != null) { final Intent parentIntent = new Intent(Intent.ACTION_VIEW, mSessionUri); NavUtils.navigateUpTo(this, parentIntent); } else { finish(); } } /** * 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); SessionSummaryFragment fragment = (SessionSummaryFragment) mTabsAdapter.mFragments.get(TABNUM_SESSION_SUMMARY); if (fragment != null) { fragment.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 = mYouTubePlayer.getView(); if (youTubePlayerView != null) { ViewGroup.LayoutParams playerParams = mYouTubePlayer.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); } else { mTabHost.setVisibility(View.VISIBLE); } } 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, false); 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 SparseArray<Fragment> mFragments; private final ArrayList<Integer> mTabNums; private int mTabCount = 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; } } public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) { super(activity.getSupportFragmentManager()); mContext = activity; mTabHost = tabHost; mViewPager = pager; mTabHost.setOnTabChangedListener(this); mViewPager.setAdapter(this); mViewPager.setOnPageChangeListener(this); mFragments = new SparseArray<Fragment>(3); 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(mTabCount++)); 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); 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; } 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.setBackgroundColor(Color.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); } } private static class SessionShareData { String SESSION_TITLE; String SESSION_HASHTAG; String SESSION_URL; public SessionShareData(String title, String hashTag, String url) { SESSION_TITLE = title; SESSION_HASHTAG = hashTag; SESSION_URL = url; } } /** * Single session query */ public interface SessionSummaryQuery { int _TOKEN = 0; 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, }; int SESSION_ID = 0; int TITLE = 1; int ABSTRACT = 2; int HASHTAGS = 3; int LIVESTREAM_URL = 4; int TRACK_NAME = 5; int BLOCK_START= 6; int BLOCK_END = 7; } /** * List of sessions query */ public interface SessionsQuery { int _TOKEN = 1; String[] PROJECTION = { BaseColumns._ID, Sessions.SESSION_ID, Sessions.SESSION_TITLE, Tracks.TRACK_NAME, Tracks.TRACK_COLOR, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, }; int ID = 0; int SESSION_ID = 1; int TITLE = 2; int TRACK_NAME = 3; int TRACK_COLOR = 4; int BLOCK_START= 5; 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 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.calendar.SessionAlarmService; import com.google.android.apps.iosched.calendar.SessionCalendarService; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.FractionalTouchDelegate; import com.google.android.apps.iosched.util.HelpUtils; import com.google.android.apps.iosched.util.ImageFetcher; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import com.google.api.android.plus.GooglePlus; import com.google.api.android.plus.PlusOneButton; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.RectF; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; 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. * * <p>This fragment is used in a number of activities, including * {@link com.google.android.apps.iosched.ui.phone.SessionDetailActivity}, * {@link com.google.android.apps.iosched.ui.tablet.SessionsVendorsMultiPaneActivity}, * {@link com.google.android.apps.iosched.ui.tablet.MapMultiPaneActivity}, etc. */ public class SessionDetailFragment extends SherlockFragment implements LoaderManager.LoaderCallbacks<Cursor> { 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 String mSessionId; private Uri mSessionUri; private long mSessionBlockStart; private long mSessionBlockEnd; private String mTitleString; private String mHashtags; private String mUrl; private String mRoomId; private String mRoomName; private boolean mStarred; private boolean mInitStarred; private MenuItem mShareMenuItem; private MenuItem mStarMenuItem; private MenuItem mSocialStreamMenuItem; private ViewGroup mRootView; private TextView mTitle; private TextView mSubtitle; private PlusOneButton mPlusOneButton; private TextView mAbstract; private TextView mRequirements; private boolean mSessionCursor = false; private boolean mSpeakersCursor = false; private boolean mHasSummaryContent = false; private boolean mVariableHeightHeader = false; private ImageFetcher mImageFetcher; private List<Runnable> mDeferredUiOperations = new ArrayList<Runnable>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GooglePlus.initialize(getActivity(), Config.API_KEY, Config.CLIENT_ID); 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); mImageFetcher = UIUtils.getImageFetcher(getActivity()); mImageFetcher.setImageFadeIn(false); setHasOptionsMenu(true); HelpUtils.maybeShowAddToScheduleTutorial(getActivity()); } @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); final View plusOneParent = mRootView.findViewById(R.id.header_session); FractionalTouchDelegate.setupDelegate(plusOneParent, 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); if (mVariableHeightHeader) { View headerView = mRootView.findViewById(R.id.header_session); ViewGroup.LayoutParams layoutParams = headerView.getLayoutParams(); layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT; headerView.setLayoutParams(layoutParams); } return mRootView; } @Override public void onStop() { super.onStop(); if (mInitStarred != mStarred) { // Update Calendar event through the Calendar API on Android 4.0 or new versions. if (UIUtils.hasICS()) { Intent intent; if (mStarred) { // Set up intent to add session to Calendar, if it doesn't exist already. intent = new Intent(SessionCalendarService.ACTION_ADD_SESSION_CALENDAR, mSessionUri); intent.putExtra(SessionCalendarService.EXTRA_SESSION_BLOCK_START, mSessionBlockStart); intent.putExtra(SessionCalendarService.EXTRA_SESSION_BLOCK_END, mSessionBlockEnd); intent.putExtra(SessionCalendarService.EXTRA_SESSION_ROOM, mRoomName); intent.putExtra(SessionCalendarService.EXTRA_SESSION_TITLE, mTitleString); } else { // Set up intent to remove session from Calendar, if exists. intent = new Intent(SessionCalendarService.ACTION_REMOVE_SESSION_CALENDAR, mSessionUri); intent.putExtra(SessionCalendarService.EXTRA_SESSION_BLOCK_START, mSessionBlockStart); intent.putExtra(SessionCalendarService.EXTRA_SESSION_BLOCK_END, mSessionBlockEnd); intent.putExtra(SessionCalendarService.EXTRA_SESSION_TITLE, mTitleString); } intent.setClass(getActivity(), SessionCalendarService.class); getActivity().startService(intent); } if (mStarred && System.currentTimeMillis() < mSessionBlockStart) { setupNotification(); } } } @Override public void onPause() { super.onPause(); mImageFetcher.flushCache(); } @Override public void onDestroy() { super.onDestroy(); mImageFetcher.closeCache(); } private void setupNotification() { // Schedule an alarm that fires a system notification when expires. final Context ctx = getActivity(); Intent scheduleIntent = new Intent( SessionAlarmService.ACTION_SCHEDULE_STARRED_BLOCK, null, ctx, SessionAlarmService.class); scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, mSessionBlockStart); scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, mSessionBlockEnd); ctx.startService(scheduleIntent); } /** * Handle {@link SessionsQuery} {@link Cursor}. */ private void onSessionQueryComplete(Cursor cursor) { mSessionCursor = true; if (!cursor.moveToFirst()) { return; } mTitleString = cursor.getString(SessionsQuery.TITLE); // Format time block this session occupies mSessionBlockStart = cursor.getLong(SessionsQuery.BLOCK_START); mSessionBlockEnd = cursor.getLong(SessionsQuery.BLOCK_END); mRoomName = cursor.getString(SessionsQuery.ROOM_NAME); final String subtitle = UIUtils.formatSessionSubtitle( mTitleString, mSessionBlockStart, mSessionBlockEnd, mRoomName, 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)); 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); } mPlusOneButton.setSize(PlusOneButton.Size.TALL); String url = cursor.getString(SessionsQuery.URL); if (TextUtils.isEmpty(url)) { mPlusOneButton.setVisibility(View.GONE); } else { mPlusOneButton.setUrl(url); } 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); } ViewGroup linksContainer = (ViewGroup) mRootView.findViewById(R.id.links_container); linksContainer.removeAllViews(); LayoutInflater inflater = getLayoutInflater(null); boolean hasLinks = false; final Context context = mRootView.getContext(); // Render I/O live link 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) { hasLinks = true; // Create the link item ViewGroup linkContainer = (ViewGroup) inflater.inflate(R.layout.list_item_session_link, linksContainer, false); ((TextView) linkContainer.findViewById(R.id.link_text)).setText( R.string.session_link_livestream); linkContainer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { fireLinkEvent(R.string.session_link_livestream); Intent livestreamIntent = new Intent(Intent.ACTION_VIEW, mSessionUri); livestreamIntent.setClass(context, SessionLivestreamActivity.class); startActivity(livestreamIntent); } }); linksContainer.addView(linkContainer); } // Render normal links for (int i = 0; i < SessionsQuery.LINKS_INDICES.length; i++) { final String linkUrl = cursor.getString(SessionsQuery.LINKS_INDICES[i]); if (!TextUtils.isEmpty(linkUrl)) { hasLinks = true; // Create the link item ViewGroup linkContainer = (ViewGroup) inflater.inflate(R.layout.list_item_session_link, linksContainer, false); ((TextView) linkContainer.findViewById(R.id.link_text)).setText( SessionsQuery.LINKS_TITLES[i]); final int linkTitleIndex = i; linkContainer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { fireLinkEvent(SessionsQuery.LINKS_TITLES[linkTitleIndex]); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(linkUrl)); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); UIUtils.safeOpenLink(context, intent); } }); linksContainer.addView(linkContainer); } } // Show past/present/future and livestream status for this block. UIUtils.updateTimeAndLivestreamBlockUI(context, mSessionBlockStart, mSessionBlockEnd, hasLivestream, null, null, mSubtitle, subtitle); mRootView.findViewById(R.id.session_links_block) .setVisibility(hasLinks ? View.VISIBLE : View.GONE); EasyTracker.getTracker().trackView("Session: " + mTitleString); LOGD("Tracker", "Session: " + mTitleString); } private void enableSocialStreamMenuItemDeferred() { mDeferredUiOperations.add(new Runnable() { @Override public void run() { mSocialStreamMenuItem.setVisible(true); } }); tryExecuteDeferredUiOperations(); } private void showStarredDeferred(final boolean starred) { mDeferredUiOperations.add(new Runnable() { @Override public void run() { showStarred(starred); } }); tryExecuteDeferredUiOperations(); } private void showStarred(boolean starred) { 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; } 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; // TODO: remove existing speakers from layout, since this cursor might be from a data change final ViewGroup speakersGroup = (ViewGroup) mRootView.findViewById(R.id.session_speakers_block); 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)) { mImageFetcher.loadThumbnailImage(speakerImageUrl, speakerImageView, R.drawable.person_image_empty); } 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); UIUtils.safeOpenLink(getActivity(), 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); mSocialStreamMenuItem = menu.findItem(R.id.menu_social_stream); mShareMenuItem = menu.findItem(R.id.menu_share); tryExecuteDeferredUiOperations(); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { SessionsHelper helper = new SessionsHelper(getActivity()); switch (item.getItemId()) { case R.id.menu_map: EasyTracker.getTracker().trackEvent( "Session", "Map", mTitleString, 0L); LOGD("Tracker", "Map: " + mTitleString); helper.startMapActivity(mRoomId); return true; case R.id.menu_star: boolean star = !mStarred; showStarred(star); helper.setSessionStarred(mSessionUri, star, mTitleString); Toast.makeText( getActivity(), getResources().getQuantityString(star ? R.plurals.toast_added_to_schedule : R.plurals.toast_removed_from_schedule, 1, 1), Toast.LENGTH_SHORT).show(); EasyTracker.getTracker().trackEvent( "Session", star ? "Starred" : "Unstarred", mTitleString, 0L); LOGD("Tracker", (star ? "Starred: " : "Unstarred: ") + mTitleString); 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().trackEvent( "Session", "Stream", mTitleString, 0L); LOGD("Tracker", "Stream: " + mTitleString); helper.startSocialStream(UIUtils.getSessionHashtagsString(mHashtags)); return true; } return super.onOptionsItemSelected(item); } /* * Event structure: * Category -> "Session Details" * Action -> Link Text * Label -> Session's Title * Value -> 0. */ public void fireLinkEvent(int actionId) { EasyTracker.getTracker().trackEvent( "Session", getActivity().getString(actionId), mTitleString, 0L); LOGD("Tracker", getActivity().getString(actionId) + ": " + mTitleString); } @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 (getActivity() == null) { 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) {} /** * {@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.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 ROOM_ID = 13; int ROOM_NAME = 14; int[] LINKS_INDICES = { URL, YOUTUBE_URL, PDF_URL, NOTES_URL, }; int[] LINKS_TITLES = { R.string.session_link_main, R.string.session_link_youtube, 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; } }
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.phone; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import android.annotation.TargetApi; import android.app.SearchManager; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.widget.SearchView; /** * A single-pane activity that shows a {@link SessionsFragment} containing a list of sessions. * This is used when showing the sessions for a given time slot, or showing session search results. */ public class SessionsActivity extends SimpleSinglePaneActivity implements SessionsFragment.Callbacks { @Override protected Fragment onCreatePane() { return new SessionsFragment(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.search, menu); setupSearchMenuItem(menu); return true; } @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupSearchMenuItem(Menu 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())); } } } @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); } @Override public boolean onSessionSelected(String sessionId) { startActivity(new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(sessionId))); 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.ui.phone; 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.ui.BaseActivity; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.SocialStreamActivity; import com.google.android.apps.iosched.ui.SocialStreamFragment; import com.google.android.apps.iosched.ui.TrackInfoHelperFragment; import com.google.android.apps.iosched.ui.VendorsFragment; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import android.content.Intent; import android.net.Uri; 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.ViewPager; import static com.google.android.apps.iosched.util.LogUtils.LOGD; /** * A single-pane activity that shows a {@link SessionsFragment} in one tab and a * {@link VendorsFragment} in another tab, representing the sessions and developer sandbox companies * for the given conference track (Android, Chrome, etc.). */ public class TrackDetailActivity extends BaseActivity implements ActionBar.TabListener, ViewPager.OnPageChangeListener, SessionsFragment.Callbacks, VendorsFragment.Callbacks, TrackInfoHelperFragment.Callbacks { private ViewPager mViewPager; private String mTrackId; private Uri mTrackUri; private boolean mShowVendors = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_track_detail); mTrackUri = getIntent().getData(); mTrackId = ScheduleContract.Tracks.getTrackId(mTrackUri); mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(new TrackDetailPagerAdapter(getSupportFragmentManager())); mViewPager.setOnPageChangeListener(this); mViewPager.setPageMarginDrawable(R.drawable.grey_border_inset_lr); mViewPager.setPageMargin(getResources().getDimensionPixelSize(R.dimen.page_margin_width)); mShowVendors = !ScheduleContract.Tracks.CODELABS_TRACK_ID.equals(mTrackId) && !ScheduleContract.Tracks.TECH_TALK_TRACK_ID.equals(mTrackId); if (mShowVendors) { final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.addTab(actionBar.newTab() .setText(R.string.title_sessions) .setTabListener(this)); actionBar.addTab(actionBar.newTab() .setText(R.string.title_vendors) .setTabListener(this)); } if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(TrackInfoHelperFragment.newFromTrackUri(mTrackUri), "track_info") .commit(); } } @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_sessions; break; case 1: titleId = R.string.title_vendors; break; } String title = getString(titleId); EasyTracker.getTracker().trackView(title + ": " + getTitle()); LOGD("Tracker", title + ": " + getTitle()); } @Override public void onPageScrollStateChanged(int i) { } private class TrackDetailPagerAdapter extends FragmentPagerAdapter { public TrackDetailPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { boolean allTracks = (ScheduleContract.Tracks.ALL_TRACK_ID.equals(mTrackId)); if (position == 0) { Fragment fragment = new SessionsFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments(new Intent( Intent.ACTION_VIEW, allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(mTrackId)))); return fragment; } else { Fragment fragment = new VendorsFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments(new Intent( Intent.ACTION_VIEW, allTracks ? ScheduleContract.Vendors.CONTENT_URI : ScheduleContract.Tracks.buildVendorsUri(mTrackId)))); return fragment; } } @Override public int getCount() { return mShowVendors ? 2 : 1; } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.track_detail, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_social_stream: Intent intent = new Intent(this, SocialStreamActivity.class); intent.putExtra(SocialStreamFragment.EXTRA_QUERY, UIUtils.getSessionHashtagsString(mTrackId)); startActivity(intent); break; } return super.onOptionsItemSelected(item); } @Override public void onTrackInfoAvailable(String trackId, String trackName, int trackColor) { setTitle(trackName); setActionBarColor(trackColor); EasyTracker.getTracker().trackView(getString(R.string.title_sessions) + ": " + getTitle()); LOGD("Tracker", getString(R.string.title_sessions) + ": " + getTitle()); } @Override public boolean onSessionSelected(String sessionId) { startActivity(new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(sessionId))); return false; } @Override public boolean onVendorSelected(String vendorId) { startActivity(new Intent(Intent.ACTION_VIEW, ScheduleContract.Vendors.buildVendorUri(vendorId))); 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.ui.phone; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity; import com.google.android.apps.iosched.ui.TrackInfoHelperFragment; import com.google.android.apps.iosched.ui.VendorDetailFragment; import com.actionbarsherlock.view.MenuItem; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.NavUtils; /** * A single-pane activity that shows a {@link VendorDetailFragment}. */ public class VendorDetailActivity extends SimpleSinglePaneActivity implements VendorDetailFragment.Callbacks, TrackInfoHelperFragment.Callbacks { private String mTrackId = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected Fragment onCreatePane() { return new VendorDetailFragment(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { // Up to this session's track details, or Home if no track is available Intent parentIntent; if (mTrackId != null) { parentIntent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Tracks.buildTrackUri(mTrackId)); } else { parentIntent = new Intent(this, HomeActivity.class); } NavUtils.navigateUpTo(this, parentIntent); return true; } return super.onOptionsItemSelected(item); } @Override public void onTrackInfoAvailable(String trackId, String trackName, int trackColor) { mTrackId = trackId; setTitle(trackName); setActionBarColor(trackColor); } @Override public void onTrackIdAvailable(final String trackId) { new Handler().post(new Runnable() { @Override public void run() { FragmentManager fm = getSupportFragmentManager(); if (fm.findFragmentByTag("track_info") == null) { fm.beginTransaction() .add(TrackInfoHelperFragment.newFromTrackUri( ScheduleContract.Tracks.buildTrackUri(trackId)), "track_info") .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.ui.phone; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.MapFragment; import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; /** * A single-pane activity that shows a {@link MapFragment}. */ public class MapActivity extends SimpleSinglePaneActivity implements MapFragment.Callbacks, LoaderManager.LoaderCallbacks<Cursor> { @Override protected Fragment onCreatePane() { return new MapFragment(); } @Override public void onRoomSelected(String roomId) { Bundle loadRoomDataArgs = new Bundle(); loadRoomDataArgs.putString("room_id", roomId); // force load (don't use previously used data) getSupportLoaderManager().restartLoader(0, loadRoomDataArgs, this); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(this, ScheduleContract.Rooms.buildRoomUri(data.getString("room_id")), RoomsQuery.PROJECTION, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { try { if (!cursor.moveToFirst()) { return; } Intent roomIntent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Rooms.buildSessionsDirUri( cursor.getString(RoomsQuery.ROOM_ID))); roomIntent.putExtra(Intent.EXTRA_TITLE, cursor.getString(RoomsQuery.ROOM_NAME)); startActivity(roomIntent); } finally { cursor.close(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } private interface RoomsQuery { String[] PROJECTION = { ScheduleContract.Rooms.ROOM_ID, ScheduleContract.Rooms.ROOM_NAME, ScheduleContract.Rooms.ROOM_FLOOR, }; int ROOM_ID = 0; int ROOM_NAME = 1; int ROOM_FLOOR = 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.phone; 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.SessionDetailFragment; import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity; import com.google.android.apps.iosched.ui.TrackInfoHelperFragment; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.view.MenuItem; import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.nfc.NfcAdapter; import android.nfc.NfcEvent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.NavUtils; /** * A single-pane activity that shows a {@link SessionDetailFragment}. */ public class SessionDetailActivity extends SimpleSinglePaneActivity implements TrackInfoHelperFragment.Callbacks { private String mTrackId = null; @Override protected void onCreate(Bundle savedInstanceState) { if (BeamUtils.wasLaunchedThroughBeamFirstTime(this, getIntent())) { BeamUtils.setBeamUnlocked(this); showFirstBeamDialog(); } BeamUtils.tryUpdateIntentFromBeam(this); super.onCreate(savedInstanceState); if (savedInstanceState == null) { Uri sessionUri = getIntent().getData(); BeamUtils.setBeamSessionUri(this, sessionUri); trySetBeamCallback(); getSupportFragmentManager().beginTransaction() .add(TrackInfoHelperFragment.newFromSessionUri(sessionUri), "track_info") .commit(); } } @Override protected Fragment onCreatePane() { return new SessionDetailFragment(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { // Up to this session's track details, or Home if no track is available Intent parentIntent; if (mTrackId != null) { parentIntent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Tracks.buildTrackUri(mTrackId)); } else { parentIntent = new Intent(this, HomeActivity.class); } NavUtils.navigateUpTo(this, parentIntent); return true; } return super.onOptionsItemSelected(item); } @Override public void onTrackInfoAvailable(String trackId, String trackName, int trackColor) { mTrackId = trackId; setTitle(trackName); setActionBarColor(trackColor); } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) private void trySetBeamCallback() { if (UIUtils.hasICS()) { BeamUtils.setBeamCompleteCallback(this, new NfcAdapter.OnNdefPushCompleteCallback() { @Override public void onNdefPushComplete(NfcEvent event) { // Beam has been sent if (!BeamUtils.isBeamUnlocked(SessionDetailActivity.this)) { BeamUtils.setBeamUnlocked(SessionDetailActivity.this); runOnUiThread(new Runnable() { @Override public void run() { showFirstBeamDialog(); } }); } } }); } } private void showFirstBeamDialog() { new AlertDialog.Builder(this) .setTitle(R.string.just_beamed) .setMessage(R.string.beam_unlocked_session) .setNegativeButton(R.string.close, null) .setPositiveButton(R.string.view_beam_session, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { BeamUtils.launchBeamSession(SessionDetailActivity.this); di.dismiss(); } }) .create() .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.gtv; 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.sync.SyncHelper; import com.google.android.apps.iosched.ui.BaseActivity; import com.google.android.apps.iosched.ui.SessionLivestreamActivity.SessionSummaryFragment; import com.google.android.apps.iosched.util.UIUtils; import com.google.android.youtube.api.YouTube; import com.google.android.youtube.api.YouTubePlayer; import android.annotation.TargetApi; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.BaseColumns; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.text.TextUtils; import android.text.format.DateUtils; import android.text.method.LinkMovementMethod; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; 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; /** * A Google TV home activity for Google I/O 2012 that displays session live streams pulled in * from YouTube. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class GoogleTVSessionLivestreamActivity extends BaseActivity implements LoaderCallbacks<Cursor>, YouTubePlayer.OnPlaybackEventsListener, YouTubePlayer.OnFullscreenListener, OnItemClickListener { private static final String TAG = makeLogTag(GoogleTVSessionLivestreamActivity.class); private static final String TAG_SESSION_SUMMARY = "session_summary"; private static final int UPCOMING_SESSIONS_QUERY_ID = 3; private static final String PROMO_VIDEO_URL = "http://www.youtube.com/watch?v=gTA-5HM8Zhs"; private boolean mIsFullscreen = false; private boolean mTrackPlay = true; private YouTubePlayer mYouTubePlayer; private FrameLayout mPlayerContainer; private String mYouTubeVideoId; private LinearLayout mMainLayout; private LinearLayout mVideoLayout; private LinearLayout mExtraLayout; private FrameLayout mSummaryLayout; private ListView mLiveListView; private SyncHelper mGTVSyncHelper; private LivestreamAdapter mLivestreamAdapter; private String mSessionId; private Handler mHandler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); YouTube.initialize(this, Config.YOUTUBE_API_KEY); setContentView(R.layout.activity_session_livestream); // Set up YouTube player mYouTubePlayer = (YouTubePlayer) getSupportFragmentManager().findFragmentById( R.id.livestream_player); mYouTubePlayer.setOnPlaybackEventsListener(this); mYouTubePlayer.enableCustomFullscreen(this); mYouTubePlayer.setFullscreenControlFlags( YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI); // Views that are common over all layouts mMainLayout = (LinearLayout) findViewById(R.id.livestream_mainlayout); mPlayerContainer = (FrameLayout) findViewById(R.id.livestream_player_container); // 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.googletv_livesextra_layout); mSummaryLayout = (FrameLayout) findViewById(R.id.livestream_summary); // Reload all other data in this activity reloadFromUri(getIntent().getData()); // Start sessions query to populate action bar navigation spinner getSupportLoaderManager().initLoader(SessionsQuery._TOKEN, null, this); // Set up left side listview mLivestreamAdapter = new LivestreamAdapter(this); mLiveListView = (ListView) findViewById(R.id.live_session_list); mLiveListView.setAdapter(mLivestreamAdapter); mLiveListView.setOnItemClickListener(this); mLiveListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); mLiveListView.setSelector(android.R.color.transparent); getSupportActionBar().hide(); // Sync data from Conference API new SyncOperationTask().execute((Void) null); } /** * Reloads all data in the activity and fragments from a given uri */ private void reloadFromUri(Uri newUri) { if (newUri != null && newUri.getPathSegments().size() >= 2) { mSessionId = Sessions.getSessionId(newUri); getSupportLoaderManager().restartLoader(SessionSummaryQuery._TOKEN, null, this); } } @Override public void onBackPressed() { if (mIsFullscreen) { // Exit full screen mode on back key mYouTubePlayer.setFullscreen(false); } else { super.onBackPressed(); } } @Override public void onItemClick(AdapterView<?> adapterView, View view, int itemPosition, long itemId) { final Cursor cursor = (Cursor) mLivestreamAdapter.getItem(itemPosition); final String sessionId = cursor.getString(SessionsQuery.SESSION_ID); if (sessionId != null) { reloadFromUri(Sessions.buildSessionUri(sessionId)); } } @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: final long currentTime = UIUtils.getCurrentTime(this); String selection = Sessions.LIVESTREAM_SELECTION + " and " + Sessions.AT_TIME_SELECTION; String[] selectionArgs = Sessions.buildAtTimeSelectionArgs(currentTime); return new CursorLoader(this, Sessions.buildWithTracksUri(), SessionsQuery.PROJECTION, selection, selectionArgs, null); case UPCOMING_SESSIONS_QUERY_ID: final long newCurrentTime = UIUtils.getCurrentTime(this); String sessionsSelection = Sessions.LIVESTREAM_SELECTION + " and " + Sessions.UPCOMING_SELECTION; String[] sessionsSelectionArgs = Sessions.buildUpcomingSelectionArgs(newCurrentTime); return new CursorLoader(this, Sessions.buildWithTracksUri(), SessionsQuery.PROJECTION, sessionsSelection, sessionsSelectionArgs, null); } return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { mHandler.removeCallbacks(mNextSessionStartsInCountdownRunnable); switch (loader.getId()) { case SessionSummaryQuery._TOKEN: loadSession(data); break; case SessionsQuery._TOKEN: mLivestreamAdapter.swapCursor(data); final int selected = locateSelectedItem(data); if (data.getCount() == 0) { handleNoLiveSessionsAvailable(); } else { mLiveListView.setSelection(selected); mLiveListView.requestFocus(selected); final Cursor cursor = (Cursor) mLivestreamAdapter.getItem(selected); final String sessionId = cursor.getString(SessionsQuery.SESSION_ID); if (sessionId != null) { reloadFromUri(Sessions.buildSessionUri(sessionId)); } } break; case UPCOMING_SESSIONS_QUERY_ID: if (data != null && data.getCount() > 0) { data.moveToFirst(); handleUpdateNextUpcomingSession(data); } break; } } public void handleNoLiveSessionsAvailable() { getSupportLoaderManager().initLoader(UPCOMING_SESSIONS_QUERY_ID, null, this); updateSessionViews(PROMO_VIDEO_URL, getString(R.string.missed_io_title), getString(R.string.missed_io_subtitle), UIUtils.CONFERENCE_HASHTAG); //Make link in abstract view clickable TextView abstractLinkTextView = (TextView) findViewById(R.id.session_abstract); abstractLinkTextView.setMovementMethod(new LinkMovementMethod()); } private String mNextSessionTitle; private long mNextSessionStartTime; private final Runnable mNextSessionStartsInCountdownRunnable = new Runnable() { public void run() { int remainingSec = (int) Math.max(0, (mNextSessionStartTime - UIUtils.getCurrentTime( GoogleTVSessionLivestreamActivity.this)) / 1000); final int secs = remainingSec % 86400; final int days = remainingSec / 86400; final String str; if (days == 0) { str = getResources().getString( R.string.starts_in_template_0_days, DateUtils.formatElapsedTime(secs)); } else { str = getResources().getQuantityString( R.plurals.starts_in_template, days, days, DateUtils.formatElapsedTime(secs)); } updateSessionSummaryFragment(mNextSessionTitle, str); if (remainingSec == 0) { // Next session starting now! mHandler.postDelayed(mRefreshSessionsRunnable, 1000); return; } // Repost ourselves to keep updating countdown mHandler.postDelayed(mNextSessionStartsInCountdownRunnable, 1000); } }; private final Runnable mRefreshSessionsRunnable = new Runnable() { @Override public void run() { getSupportLoaderManager().restartLoader(SessionsQuery._TOKEN, null, GoogleTVSessionLivestreamActivity.this); } }; public void handleUpdateNextUpcomingSession(Cursor data) { mNextSessionTitle = getString(R.string.next_live_stream_session_template, data.getString(SessionsQuery.TITLE)); mNextSessionStartTime = data.getLong(SessionsQuery.BLOCK_START); updateSessionViews(PROMO_VIDEO_URL, mNextSessionTitle, "", UIUtils.CONFERENCE_HASHTAG); // Begin countdown til next session mHandler.post(mNextSessionStartsInCountdownRunnable); } /** * Locates which item should be selected in the action bar drop-down spinner based on the * current active session uri */ private int locateSelectedItem(Cursor data) { int selected = 0; if (data != null && mSessionId != null) { while (data.moveToNext()) { 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 onLoaded(String s) { } @Override public void onPlaying() { } @Override public void onPaused() { } @Override public void onBuffering(boolean b) { } @Override public void onEnded() { mHandler.post(mRefreshSessionsRunnable); } @Override public void onError() { Toast.makeText(this, R.string.session_livestream_error, Toast.LENGTH_LONG).show(); LOGE(TAG, getString(R.string.session_livestream_error)); } private void loadSession(Cursor data) { if (data != null && data.moveToFirst()) { // Schedule a data refresh after the session ends. // NOTE: using postDelayed instead of postAtTime helps during debugging, using // mock times. mHandler.postDelayed(mRefreshSessionsRunnable, data.getLong(SessionSummaryQuery.BLOCK_END) + 1000 - UIUtils.getCurrentTime(this)); updateSessionViews( data.getString(SessionSummaryQuery.LIVESTREAM_URL), data.getString(SessionSummaryQuery.TITLE), data.getString(SessionSummaryQuery.ABSTRACT), data.getString(SessionSummaryQuery.HASHTAGS)); } } /** * 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) { if (youtubeUrl == null) { // Get out, nothing to do here Toast.makeText(this, R.string.error_tv_no_url, Toast.LENGTH_SHORT).show(); LOGE(TAG, getString(R.string.error_tv_no_url)); return; } String youtubeVideoId = youtubeUrl; if (youtubeUrl.startsWith("http")) { final Uri youTubeUri = Uri.parse(youtubeUrl); youtubeVideoId = youTubeUri.getQueryParameter("v"); } playVideo(youtubeVideoId); if (mTrackPlay) { EasyTracker.getTracker().trackView("Live Streaming: " + title); LOGD("Tracker", "Live Streaming: " + title); } updateSessionSummaryFragment(title, sessionAbstract); mLiveListView.requestFocus(); } private void updateSessionSummaryFragment(String title, String sessionAbstract) { SessionSummaryFragment sessionSummaryFragment = (SessionSummaryFragment) getSupportFragmentManager().findFragmentByTag(TAG_SESSION_SUMMARY); if (sessionSummaryFragment != null) { sessionSummaryFragment.setSessionSummaryInfo(title, sessionAbstract); } } private void playVideo(String videoId) { if ((mYouTubeVideoId == null || !mYouTubeVideoId.equals(videoId)) && !TextUtils.isEmpty(videoId)) { mYouTubeVideoId = videoId; mYouTubePlayer.loadVideo(mYouTubeVideoId); mTrackPlay = true; } else { mTrackPlay = false; } } private void layoutFullscreenVideo(boolean fullscreen) { if (mIsFullscreen != fullscreen) { mIsFullscreen = fullscreen; mYouTubePlayer.setFullscreen(fullscreen); layoutGoogleTVFullScreen(fullscreen); // Full screen layout changes for all form factors final LayoutParams params = (LayoutParams) mPlayerContainer.getLayoutParams(); if (fullscreen) { params.height = LayoutParams.MATCH_PARENT; mMainLayout.setPadding(0, 0, 0, 0); } else { params.height = LayoutParams.WRAP_CONTENT; } mPlayerContainer.setLayoutParams(params); } } /** * Adjusts tablet layouts for full screen video. * * @param fullscreen True to layout in full screen, false to switch to regular layout */ private void layoutGoogleTVFullScreen(boolean fullscreen) { if (fullscreen) { mExtraLayout.setVisibility(View.GONE); mSummaryLayout.setVisibility(View.GONE); mMainLayout.setPadding(0, 0, 0, 0); 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); mMainLayout.setPadding(padding, padding, padding, padding); mVideoLayout.setBackgroundResource(R.drawable.grey_frame_on_white); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.setMargins(padding, padding, padding, padding); mVideoLayout.setLayoutParams(videoLayoutParams); } } /** * Adapter that backs the action bar drop-down spinner. */ private class LivestreamAdapter extends CursorAdapter { private LayoutInflater mLayoutInflater; public LivestreamAdapter(Context context) { super(context, null, false); 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 side list view return mLayoutInflater.inflate( R.layout.list_item_live_session, parent, false); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { // Inflate view that appears in the side list view return mLayoutInflater.inflate(R.layout.list_item_live_session, parent, false); } @Override public void bindView(View view, Context context, Cursor cursor) { final TextView titleView = (TextView) view.findViewById(R.id.live_session_title); final TextView subTitleView = (TextView) view.findViewById(R.id.live_session_subtitle); 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); } cursor.getInt(SessionsQuery.TRACK_COLOR); String sessionTitle = cursor.getString(SessionsQuery.TITLE); if (subTitleView != null) { titleView.setText(trackName); subTitleView.setText(sessionTitle); } else { // Selected view titleView.setText(getString(R.string.session_livestream_title) + ": " + trackName); } } } // Enabling media keys for Google TV Devices @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_MEDIA_PAUSE: mYouTubePlayer.pause(); return true; case KeyEvent.KEYCODE_MEDIA_PLAY: mYouTubePlayer.play(); return true; case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: mYouTubePlayer.seekRelativeMillis(20000); return true; case KeyEvent.KEYCODE_MEDIA_REWIND: mYouTubePlayer.seekRelativeMillis(-20000); return true; default: return super.onKeyDown(keyCode, event); } } // Need to sync with the conference API to get the livestream URLs private class SyncOperationTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { // Perform a sync using SyncHelper if (mGTVSyncHelper == null) { mGTVSyncHelper = new SyncHelper(getApplicationContext()); } try { mGTVSyncHelper.performSync(null, SyncHelper.FLAG_SYNC_LOCAL | SyncHelper.FLAG_SYNC_REMOTE); } catch (IOException e) { LOGE(TAG, "Error loading data for Google I/O 2012.", e); } return null; } } /** * Single session query */ public interface SessionSummaryQuery { int _TOKEN = 0; String[] PROJECTION = { ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_ABSTRACT, ScheduleContract.Sessions.SESSION_HASHTAGS, ScheduleContract.Sessions.SESSION_LIVESTREAM_URL, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, }; int SESSION_ID = 0; int TITLE = 1; int ABSTRACT = 2; int HASHTAGS = 3; int LIVESTREAM_URL = 4; int TRACK_NAME = 5; int BLOCK_START= 6; int BLOCK_END = 7; } /** * List of sessions query */ public interface SessionsQuery { int _TOKEN = 1; String[] PROJECTION = { BaseColumns._ID, Sessions.SESSION_ID, Sessions.SESSION_TITLE, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_COLOR, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, }; int ID = 0; int SESSION_ID = 1; int TITLE = 2; int TRACK_NAME = 3; int TRACK_COLOR = 4; int BLOCK_START= 5; 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 com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.BuildConfig; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.ConsoleMessage; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; 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; /** * Shows a {@link WebView} with a map of the conference venue. */ public class MapFragment extends SherlockFragment { private static final String TAG = makeLogTag(MapFragment.class); /** * 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 SYSTEM_FEATURE_MULTITOUCH = "android.hardware.touchscreen.multitouch"; private static final String MAP_JSI_NAME = "MAP_CONTAINER"; private static final String MAP_URL = "http://ioschedmap.appspot.com/embed.html"; private static boolean CLEAR_CACHE_ON_LOAD = BuildConfig.DEBUG; private WebView mWebView; private View mLoadingSpinner; private boolean mMapInitialized = false; public interface Callbacks { public void onRoomSelected(String roomId); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onRoomSelected(String roomId) { } }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); EasyTracker.getTracker().trackView("Map"); LOGD("Tracker", "Map"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_webview_with_spinner, container, false); mLoadingSpinner = root.findViewById(R.id.loading_spinner); mWebView = (WebView) root.findViewById(R.id.webview); mWebView.setWebChromeClient(mWebChromeClient); mWebView.setWebViewClient(mWebViewClient); return root; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // Initialize web view if (CLEAR_CACHE_ON_LOAD) { mWebView.clearCache(true); } boolean hideZoomControls = getActivity().getPackageManager().hasSystemFeature(SYSTEM_FEATURE_MULTITOUCH) && UIUtils.hasHoneycomb(); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false); mWebView.loadUrl(MAP_URL + "?multitouch=" + (hideZoomControls ? 1 : 0)); mWebView.addJavascriptInterface(mMapJsiImpl, MAP_JSI_NAME); } @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 onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.map, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_refresh) { mWebView.reload(); return true; } return super.onOptionsItemSelected(item); } private void runJs(final String js) { Activity activity = getActivity(); if (activity == null) { return; } activity.runOnUiThread(new Runnable() { @Override public void run() { LOGD(TAG, "Loading javascript:" + js); mWebView.loadUrl("javascript:" + js); } }); } /** * Helper method to escape JavaScript strings. Useful when passing strings to a WebView via * "javascript:" calls. */ private static String escapeJsString(String s) { if (s == null) { return ""; } return s.replace("'", "\\'").replace("\"", "\\\""); } public void panBy(float xFraction, float yFraction) { runJs("IoMap.panBy(" + xFraction + "," + yFraction + ");"); } /** * I/O Conference Map JavaScript interface. */ private interface MapJsi { public void openContentInfo(final String roomId); public void onMapReady(); } private final WebChromeClient mWebChromeClient = new WebChromeClient() { @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { LOGD(TAG, "JS Console message: (" + consoleMessage.sourceId() + ": " + consoleMessage.lineNumber() + ") " + consoleMessage.message()); return false; } }; private final WebViewClient mWebViewClient = new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); mLoadingSpinner.setVisibility(View.VISIBLE); mWebView.setVisibility(View.INVISIBLE); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); mLoadingSpinner.setVisibility(View.GONE); mWebView.setVisibility(View.VISIBLE); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { LOGE(TAG, "Error " + errorCode + ": " + description); Toast.makeText(view.getContext(), "Error " + errorCode + ": " + description, Toast.LENGTH_LONG).show(); super.onReceivedError(view, errorCode, description, failingUrl); } }; private final MapJsi mMapJsiImpl = new MapJsi() { public void openContentInfo(final String roomId) { Activity activity = getActivity(); if (activity == null) { return; } activity.runOnUiThread(new Runnable() { @Override public void run() { mCallbacks.onRoomSelected(roomId); } }); } public void onMapReady() { LOGD(TAG, "onMapReady"); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); String showRoomId = null; if (!mMapInitialized && intent.hasExtra(EXTRA_ROOM)) { showRoomId = intent.getStringExtra(EXTRA_ROOM); } if (showRoomId != null) { runJs("IoMap.showLocationById('" + escapeJsString(showRoomId) + "');"); } mMapInitialized = 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.ui; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.BeamUtils; /** * Beam easter egg landing screen. */ public class BeamActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_beam); } @Override protected void onResume() { super.onResume(); if (BeamUtils.wasLaunchedThroughBeamFirstTime(this, getIntent())) { BeamUtils.setBeamUnlocked(this); showUnlockDialog(); } } void showUnlockDialog() { new AlertDialog.Builder(this) .setTitle(R.string.just_beamed) .setMessage(R.string.beam_unlocked_default) .setNegativeButton(R.string.close, null) .setPositiveButton(R.string.view_beam_session, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { BeamUtils.launchBeamSession(BeamActivity.this); di.dismiss(); } }) .create() .show(); } void showHelpDialog() { new AlertDialog.Builder(this) .setTitle(R.string.title_beam) .setMessage(R.string.beam_unlocked_help) .setNegativeButton(R.string.close, null) .setPositiveButton(R.string.view_beam_session, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { BeamUtils.launchBeamSession(BeamActivity.this); di.dismiss(); } }) .create() .show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.beam, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_beam_help) { showHelpDialog(); return true; } return super.onOptionsItemSelected(item); } }
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.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.UIUtils; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.MenuItem; import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.nfc.NfcAdapter; import android.nfc.NfcEvent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.NavUtils; /** * A base activity that handles common functionality in the app. */ public abstract class BaseActivity extends SherlockFragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EasyTracker.getTracker().setContext(this); // If we're not on Google TV and we're not authenticated, finish this activity // and show the authentication screen. if (!UIUtils.isGoogleTV(this)) { if (!AccountUtils.isAuthenticated(this)) { AccountUtils.startAuthenticationFlow(this, getIntent()); finish(); } } // If Android Beam APIs are available, set up the Beam easter egg as the default Beam // content. This can be overridden by subclasses. if (UIUtils.hasICS()) { BeamUtils.setDefaultBeamUri(this); if (!BeamUtils.isBeamUnlocked(this)) { BeamUtils.setBeamCompleteCallback(this, new NfcAdapter.OnNdefPushCompleteCallback() { @Override @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public void onNdefPushComplete(NfcEvent event) { onBeamSent(); } }); } } getSupportActionBar().setHomeButtonEnabled(true); } private void onBeamSent() { if (!BeamUtils.isBeamUnlocked(this)) { BeamUtils.setBeamUnlocked(this); runOnUiThread(new Runnable() { @Override public void run() { new AlertDialog.Builder(BaseActivity.this) .setTitle(R.string.just_beamed) .setMessage(R.string.beam_unlocked_default) .setNegativeButton(R.string.close, null) .setPositiveButton(R.string.view_beam_session, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { BeamUtils.launchBeamSession(BaseActivity.this); di.dismiss(); } }) .create() .show(); } }); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if (this instanceof HomeActivity) { return false; } NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } /** * Sets the icon color using some fancy blending mode trickery. */ protected void setActionBarColor(int color) { if (color == 0) { color = 0xffffffff; } final Resources res = getResources(); Drawable maskDrawable = res.getDrawable(R.drawable.actionbar_icon_mask); if (!(maskDrawable instanceof BitmapDrawable)) { return; } Bitmap maskBitmap = ((BitmapDrawable) maskDrawable).getBitmap(); final int width = maskBitmap.getWidth(); final int height = maskBitmap.getHeight(); Bitmap outBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(outBitmap); canvas.drawBitmap(maskBitmap, 0, 0, null); Paint maskedPaint = new Paint(); maskedPaint.setColor(color); maskedPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)); canvas.drawRect(0, 0, width, height, maskedPaint); BitmapDrawable outDrawable = new BitmapDrawable(res, outBitmap); getSupportActionBar().setIcon(outDrawable); } /** * Converts an intent into a {@link Bundle} suitable for use as fragment arguments. */ public static Bundle intentToFragmentArguments(Intent intent) { Bundle arguments = new Bundle(); if (intent == null) { return arguments; } final Uri data = intent.getData(); if (data != null) { arguments.putParcelable("_uri", data); } final Bundle extras = intent.getExtras(); if (extras != null) { arguments.putAll(intent.getExtras()); } return arguments; } /** * Converts a fragment arguments bundle into an intent. */ public static Intent fragmentArgumentsToIntent(Bundle arguments) { Intent intent = new Intent(); if (arguments == null) { return intent; } final Uri data = arguments.getParcelable("_uri"); if (data != null) { intent.setData(data); } intent.putExtras(arguments); intent.removeExtra("_uri"); return intent; } @Override protected void onStart() { super.onStart(); EasyTracker.getTracker().trackActivityStart(this); } @Override protected void onStop() { super.onStop(); EasyTracker.getTracker().trackActivityStop(this); } }
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(R.layout.activity_singlepane_empty); 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"); } } /** * 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 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.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import com.google.android.apps.iosched.util.actionmodecompat.ActionMode; import com.google.android.apps.iosched.util.actionmodecompat.MultiChoiceModeListener; import com.actionbarsherlock.app.SherlockListFragment; import android.app.Activity; import android.content.Context; import android.content.Intent; 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.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.text.Spannable; import android.text.TextUtils; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.LinkedHashSet; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; 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. This fragment supports multiple-selection * using the contextual action bar (on API 11+ devices), and also supports a separate 'activated' * state for indicating the currently-opened detail view on tablet devices. */ public class SessionsFragment extends SherlockListFragment implements LoaderManager.LoaderCallbacks<Cursor>, 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 boolean mHasSetEmptyText = false; private int mSessionQueryToken; private LinkedHashSet<Integer> mSelectedSessionPositions = new LinkedHashSet<Integer>(); private Handler mHandler = new Handler(); 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); } reloadFromArguments(getArguments()); } protected void reloadFromArguments(Bundle arguments) { // Teardown from previous arguments setListAdapter(null); // Load new arguments final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments); final Uri sessionsUri = intent.getData(); if (sessionsUri == null) { return; } 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 onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (!mHasSetEmptyText) { // Could be a bug, but calling this twice makes it become visible // when it shouldn't // be visible. setEmptyText(getString(R.string.empty_sessions)); mHasSetEmptyText = true; } ActionMode.setMultiChoiceMode(getListView(), getActivity(), 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; activity.getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mObserver); } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; getActivity().getContentResolver().unregisterContentObserver(mObserver); } @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); } } /** {@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); final Uri sessionsUri = intent.getData(); Loader<Cursor> loader = null; if (id == SessionsQuery._TOKEN) { loader = new CursorLoader(getActivity(), sessionsUri, SessionsQuery.PROJECTION, null, null, ScheduleContract.Sessions.DEFAULT_SORT); } else if (id == SearchQuery._TOKEN) { loader = new CursorLoader(getActivity(), sessionsUri, SearchQuery.PROJECTION, null, 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().trackView("Session Block: " + title); LOGD("Tracker", "Session Block: " + title); } } } else { LOGD(TAG, "Query complete, Not Actionable: " + token); cursor.close(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } // MultiChoiceModeListener interface @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { SessionsHelper helper = new SessionsHelper(getActivity()); mode.finish(); switch (item.getItemId()) { case R.id.menu_map: { // multiple selection not supported int position = mSelectedSessionPositions.iterator().next(); Cursor cursor = (Cursor) mAdapter.getItem(position); String roomId = cursor.getString(SessionsQuery.ROOM_ID); helper.startMapActivity(roomId); String title = cursor.getString(SessionsQuery.TITLE); EasyTracker.getTracker().trackEvent( "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 : mSelectedSessionPositions) { 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().trackEvent( "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 = mSelectedSessionPositions.iterator().next(); // 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: StringBuilder hashtags = new StringBuilder(); for (int position : mSelectedSessionPositions) { Cursor cursor = (Cursor) mAdapter.getItem(position); String term = cursor.getString(SessionsQuery.HASHTAGS); if (!term.startsWith("#")) { term = "#" + term; } if (hashtags.length() > 0) { hashtags.append(" OR "); } hashtags.append(term); String title = cursor.getString(SessionsQuery.TITLE); EasyTracker.getTracker().trackEvent( "Session", "Mapped", title, 0L); LOGV(TAG, "Starred: " + title); } helper.startSocialStream(hashtags.toString()); 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); mSelectedSessionPositions.clear(); return true; } @Override public void onDestroyActionMode(ActionMode mode) {} @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { if (checked) { mSelectedSessionPositions.add(position); } else { mSelectedSessionPositions.remove(position); } int numSelectedSessions = mSelectedSessionPositions.size(); mode.setTitle(getResources().getQuantityString( R.plurals.title_selected_sessions, numSelectedSessions, numSelectedSessions)); if (numSelectedSessions == 1) { // activate all the menu item mMapMenuItem.setVisible(true); mShareMenuItem.setVisible(true); mSocialStreamMenuItem.setVisible(true); mStarredMenuItem.setVisible(true); position = mSelectedSessionPositions.iterator().next(); Cursor cursor = (Cursor) mAdapter.getItem(position); boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0; setSelectedSessionStarred(starred); } else { mMapMenuItem.setVisible(false); mShareMenuItem.setVisible(false); mSocialStreamMenuItem.setVisible(false); boolean allStarred = true; boolean allUnstarred = true; for (int pos : mSelectedSessionPositions) { 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 ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (getActivity() == null) { return; } Loader<Cursor> loader = getLoaderManager().getLoader(mSessionQueryToken); if (loader != null) { loader.forceLoad(); } } }; /** * {@link CursorAdapter} that renders a {@link SessionsQuery}. */ private class SessionsAdapter extends CursorAdapter { public SessionsAdapter(Context context) { super(context, null, false); } /** {@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; } if (sessionId.equals(mSelectedSessionId)){ UIUtils.setActivatedCompat(view, true); } else { UIUtils.setActivatedCompat(view, false); } 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, 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, view.findViewById(R.id.list_item_session), titleView, subtitleView, subtitle); } } /** * {@link CursorAdapter} that renders a {@link SearchQuery}. */ private class SearchAdapter extends CursorAdapter { public SearchAdapter(Context context) { super(context, null, false); } /** {@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, ScheduleContract.Sessions.SESSION_LEVEL, ScheduleContract.Rooms.ROOM_NAME, ScheduleContract.Rooms.ROOM_ID, ScheduleContract.Sessions.SESSION_HASHTAGS, ScheduleContract.Sessions.SESSION_URL }; int _ID = 0; int SESSION_ID = 1; int TITLE = 2; int STARRED = 3; int SEARCH_SNIPPET = 4; int LEVEL = 5; int ROOM_NAME = 6; int ROOM_ID = 7; int HASHTAGS = 8; int URL = 9; } }
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.Announcements; import com.google.android.apps.iosched.util.UIUtils; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.text.TextUtils; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; /** * A fragment used in {@link HomeActivity} that shows either a countdown, * announcements, or 'thank you' text, at different times (before/during/after * the conference). */ public class WhatsOnFragment extends Fragment implements LoaderCallbacks<Cursor> { private Handler mHandler = new Handler(); private TextView mCountdownTextView; private ViewGroup mRootView; private Cursor mAnnouncementsCursor; private LayoutInflater mInflater; private int mTitleCol = -1; private int mDateCol = -1; private int mUrlCol = -1; private static final int ANNOUNCEMENTS_LOADER_ID = 0; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mInflater = inflater; mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_whats_on, container); refresh(); return mRootView; } @Override public void onDetach() { super.onDetach(); mHandler.removeCallbacks(mCountdownRunnable); getActivity().getContentResolver().unregisterContentObserver(mObserver); } private void refresh() { mHandler.removeCallbacks(mCountdownRunnable); mRootView.removeAllViews(); final long currentTimeMillis = UIUtils.getCurrentTime(getActivity()); // Show Loading... and load the view corresponding to the current state if (currentTimeMillis < UIUtils.CONFERENCE_START_MILLIS) { setupBefore(); } else if (currentTimeMillis > UIUtils.CONFERENCE_END_MILLIS) { setupAfter(); } else { setupDuring(); } } private void setupBefore() { // Before conference, show countdown. mCountdownTextView = (TextView) mInflater .inflate(R.layout.whats_on_countdown, mRootView, false); mRootView.addView(mCountdownTextView); mHandler.post(mCountdownRunnable); } private void setupAfter() { // After conference, show canned text. mInflater.inflate(R.layout.whats_on_thank_you, mRootView, true); } private void setupDuring() { // Start background query to load announcements getLoaderManager().initLoader(ANNOUNCEMENTS_LOADER_ID, null, this); getActivity().getContentResolver().registerContentObserver( Announcements.CONTENT_URI, true, mObserver); } /** * Event that updates countdown timer. Posts itself again to * {@link #mHandler} to continue updating time. */ private final Runnable mCountdownRunnable = new Runnable() { public void run() { int remainingSec = (int) Math.max(0, (UIUtils.CONFERENCE_START_MILLIS - UIUtils .getCurrentTime(getActivity())) / 1000); final boolean conferenceStarted = remainingSec == 0; if (conferenceStarted) { // Conference started while in countdown mode, switch modes and // bail on future countdown updates. mHandler.postDelayed(new Runnable() { public void run() { refresh(); } }, 100); return; } final int secs = remainingSec % 86400; final int days = remainingSec / 86400; final String str; if (days == 0) { str = getResources().getString( R.string.whats_on_countdown_title_0, DateUtils.formatElapsedTime(secs)); } else { str = getResources().getQuantityString( R.plurals.whats_on_countdown_title, days, days, DateUtils.formatElapsedTime(secs)); } mCountdownTextView.setText(str); // Repost ourselves to keep updating countdown mHandler.postDelayed(mCountdownRunnable, 1000); } }; @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader(getActivity(), Announcements.CONTENT_URI, null, null, null, Announcements.ANNOUNCEMENT_DATE + " DESC"); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (getActivity() == null) { return; } if (data != null && data.getCount() > 0) { mTitleCol = data.getColumnIndex(Announcements.ANNOUNCEMENT_TITLE); mDateCol = data.getColumnIndex(Announcements.ANNOUNCEMENT_DATE); mUrlCol = data.getColumnIndex(Announcements.ANNOUNCEMENT_URL); showAnnouncements(data); } else { showNoAnnouncements(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { mAnnouncementsCursor = null; } /** * Show the the announcements */ private void showAnnouncements(Cursor announcements) { mAnnouncementsCursor = announcements; ViewGroup announcementsRootView = (ViewGroup) mInflater.inflate( R.layout.whats_on_announcements, mRootView, false); final ViewPager pager = (ViewPager) announcementsRootView.findViewById( R.id.announcements_pager); final View previousButton = announcementsRootView.findViewById( R.id.announcements_previous_button); final View nextButton = announcementsRootView.findViewById( R.id.announcements_next_button); final PagerAdapter adapter = new AnnouncementsAdapter(); pager.setAdapter(adapter); pager.setPageMargin( getResources().getDimensionPixelSize(R.dimen.announcements_margin_width)); pager.setPageMarginDrawable(R.drawable.announcements_divider); pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { previousButton.setEnabled(position > 0); nextButton.setEnabled(position < adapter.getCount() - 1); } }); previousButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { pager.setCurrentItem(pager.getCurrentItem() - 1); } }); nextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { pager.setCurrentItem(pager.getCurrentItem() + 1); } }); previousButton.setEnabled(false); nextButton.setEnabled(adapter.getCount() > 1); mRootView.removeAllViews(); mRootView.addView(announcementsRootView); } /** * Show a placeholder message */ private void showNoAnnouncements() { mInflater.inflate(R.layout.empty_announcements, mRootView, true); } public class AnnouncementsAdapter extends PagerAdapter { @Override public Object instantiateItem(ViewGroup pager, int position) { mAnnouncementsCursor.moveToPosition(position); LinearLayout rootView = (LinearLayout) mInflater.inflate( R.layout.pager_item_announcement, pager, false); TextView titleView = (TextView) rootView.findViewById(R.id.announcement_title); TextView subtitleView = (TextView) rootView.findViewById(R.id.announcement_ago); titleView.setText(mAnnouncementsCursor.getString(mTitleCol)); final long date = mAnnouncementsCursor.getLong(mDateCol); final String when = UIUtils.getTimeAgo(date, getActivity()); final String url = mAnnouncementsCursor.getString(mUrlCol); subtitleView.setText(when); rootView.setTag(url); if (!TextUtils.isEmpty(url)) { rootView.setClickable(true); rootView.setOnClickListener(mAnnouncementClick); } else { rootView.setClickable(false); } pager.addView(rootView, 0); return rootView; } private final OnClickListener mAnnouncementClick = new OnClickListener() { @Override public void onClick(View v) { String url = (String) v.getTag(); if (!TextUtils.isEmpty(url)) { UIUtils.safeOpenLink(getActivity(), new Intent(Intent.ACTION_VIEW, Uri.parse(url))); } } }; @Override public void destroyItem(ViewGroup pager, int position, Object view) { pager.removeView((View) view); } @Override public int getCount() { return mAnnouncementsCursor.getCount(); } @Override public boolean isViewFromObject(View view, Object object) { return view.equals(object); } @Override public int getItemPosition(Object object) { return POSITION_NONE; } } private final ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (getActivity() == null) { return; } Loader<Cursor> loader = getLoaderManager().getLoader(ANNOUNCEMENTS_LOADER_ID); if (loader != null) { loader.forceLoad(); } } }; }
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.calendar; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * {@link BroadcastReceiver} to reinitialize {@link android.app.AlarmManager} for all starred * session blocks. */ public class SessionAlarmReceiver extends BroadcastReceiver { public static final String TAG = makeLogTag(SessionAlarmReceiver.class); @Override public void onReceive(Context context, Intent intent) { Intent scheduleIntent = new Intent( SessionAlarmService.ACTION_SCHEDULE_ALL_STARRED_BLOCKS, null, context, SessionAlarmService.class); context.startService(scheduleIntent); } }
Java