code
stringlengths
3
1.18M
language
stringclasses
1 value
package com.example.android.rings_extended; import android.content.Context; import android.util.AttributeSet; import android.widget.Checkable; import android.widget.RelativeLayout; /** * A special variation of RelativeLayout that can be used as a checkable object. * This allows it to be used as the top-level view of a list view item, which * also supports checking. Otherwise, it works identically to a RelativeLayout. */ public class CheckableRelativeLayout extends RelativeLayout implements Checkable { private boolean mChecked; private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked }; public CheckableRelativeLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected int[] onCreateDrawableState(int extraSpace) { final int[] drawableState = super.onCreateDrawableState(extraSpace + 1); if (isChecked()) { mergeDrawableStates(drawableState, CHECKED_STATE_SET); } return drawableState; } public void toggle() { setChecked(!mChecked); } public boolean isChecked() { return mChecked; } public void setChecked(boolean checked) { if (mChecked != checked) { mChecked = checked; refreshDrawableState(); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.example.android.rings_extended; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.SystemClock; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup.OnHierarchyChangeListener; import android.widget.AbsListView; import android.widget.Adapter; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.HeaderViewListAdapter; import android.widget.ListView; import android.widget.AbsListView.OnScrollListener; /** * FastScrollView is meant for embedding {@link ListView}s that contain a large number of * items that can be indexed in some fashion. It displays a special scroll bar that allows jumping * quickly to indexed sections of the list in touch-mode. Only one child can be added to this * view group and it must be a {@link ListView}, with an adapter that is derived from * {@link BaseAdapter}. * * <p>This file was copied from the Contacts application. In the future it * should be provided as a standard part of the Android framework. */ public class FastScrollView extends FrameLayout implements OnScrollListener, OnHierarchyChangeListener { private Drawable mCurrentThumb; private Drawable mOverlayDrawable; private int mThumbH; private int mThumbW; private int mThumbY; private RectF mOverlayPos; // Hard coding these for now private int mOverlaySize = 104; private boolean mDragging; private ListView mList; private boolean mScrollCompleted; private boolean mThumbVisible; private int mVisibleItem; private Paint mPaint; private int mListOffset; private Object [] mSections; private String mSectionText; private boolean mDrawOverlay; private ScrollFade mScrollFade; private Handler mHandler = new Handler(); private BaseAdapter mListAdapter; private boolean mChangedBounds; interface SectionIndexer { Object[] getSections(); int getPositionForSection(int section); int getSectionForPosition(int position); } public FastScrollView(Context context) { super(context); init(context); } public FastScrollView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public FastScrollView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } private void useThumbDrawable(Drawable drawable) { mCurrentThumb = drawable; mThumbW = 64; //mCurrentThumb.getIntrinsicWidth(); mThumbH = 52; //mCurrentThumb.getIntrinsicHeight(); mChangedBounds = true; } private void init(Context context) { // Get both the scrollbar states drawables final Resources res = context.getResources(); useThumbDrawable(res.getDrawable( R.drawable.scrollbar_handle_accelerated_anim2)); mOverlayDrawable = res.getDrawable(android.R.drawable.alert_dark_frame); mScrollCompleted = true; setWillNotDraw(false); // Need to know when the ListView is added setOnHierarchyChangeListener(this); mOverlayPos = new RectF(); mScrollFade = new ScrollFade(); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setTextAlign(Paint.Align.CENTER); mPaint.setTextSize(mOverlaySize / 2); mPaint.setColor(0xFFFFFFFF); mPaint.setStyle(Paint.Style.FILL_AND_STROKE); } private void removeThumb() { mThumbVisible = false; // Draw one last time to remove thumb invalidate(); } @Override public void draw(Canvas canvas) { super.draw(canvas); if (!mThumbVisible) { // No need to draw the rest return; } final int y = mThumbY; final int viewWidth = getWidth(); final FastScrollView.ScrollFade scrollFade = mScrollFade; int alpha = -1; if (scrollFade.mStarted) { alpha = scrollFade.getAlpha(); if (alpha < ScrollFade.ALPHA_MAX / 2) { mCurrentThumb.setAlpha(alpha * 2); } int left = viewWidth - (mThumbW * alpha) / ScrollFade.ALPHA_MAX; mCurrentThumb.setBounds(left, 0, viewWidth, mThumbH); mChangedBounds = true; } canvas.translate(0, y); mCurrentThumb.draw(canvas); canvas.translate(0, -y); // If user is dragging the scroll bar, draw the alphabet overlay if (mDragging && mDrawOverlay) { mOverlayDrawable.draw(canvas); final Paint paint = mPaint; float descent = paint.descent(); final RectF rectF = mOverlayPos; canvas.drawText(mSectionText, (int) (rectF.left + rectF.right) / 2, (int) (rectF.bottom + rectF.top) / 2 + mOverlaySize / 4 - descent, paint); } else if (alpha == 0) { scrollFade.mStarted = false; removeThumb(); } else { invalidate(viewWidth - mThumbW, y, viewWidth, y + mThumbH); } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if (mCurrentThumb != null) { mCurrentThumb.setBounds(w - mThumbW, 0, w, mThumbH); } final RectF pos = mOverlayPos; pos.left = (w - mOverlaySize) / 2; pos.right = pos.left + mOverlaySize; pos.top = h / 10; // 10% from top pos.bottom = pos.top + mOverlaySize; mOverlayDrawable.setBounds((int) pos.left, (int) pos.top, (int) pos.right, (int) pos.bottom); } public void onScrollStateChanged(AbsListView view, int scrollState) { } public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (totalItemCount - visibleItemCount > 0 && !mDragging) { mThumbY = ((getHeight() - mThumbH) * firstVisibleItem) / (totalItemCount - visibleItemCount); if (mChangedBounds) { final int viewWidth = getWidth(); mCurrentThumb.setBounds(viewWidth - mThumbW, 0, viewWidth, mThumbH); mChangedBounds = false; } } mScrollCompleted = true; if (firstVisibleItem == mVisibleItem) { return; } mVisibleItem = firstVisibleItem; if (!mThumbVisible || mScrollFade.mStarted) { mThumbVisible = true; mCurrentThumb.setAlpha(ScrollFade.ALPHA_MAX); } mHandler.removeCallbacks(mScrollFade); mScrollFade.mStarted = false; if (!mDragging) { mHandler.postDelayed(mScrollFade, 1500); } } private void getSections() { Adapter adapter = mList.getAdapter(); if (adapter instanceof HeaderViewListAdapter) { mListOffset = ((HeaderViewListAdapter)adapter).getHeadersCount(); adapter = ((HeaderViewListAdapter)adapter).getWrappedAdapter(); } if (adapter instanceof SectionIndexer) { mListAdapter = (BaseAdapter) adapter; mSections = ((SectionIndexer) mListAdapter).getSections(); } } public void onChildViewAdded(View parent, View child) { if (child instanceof ListView) { mList = (ListView)child; mList.setOnScrollListener(this); getSections(); } } public void onChildViewRemoved(View parent, View child) { if (child == mList) { mList = null; mListAdapter = null; mSections = null; } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (mThumbVisible && ev.getAction() == MotionEvent.ACTION_DOWN) { if (ev.getX() > getWidth() - mThumbW && ev.getY() >= mThumbY && ev.getY() <= mThumbY + mThumbH) { mDragging = true; return true; } } return false; } private void scrollTo(float position) { int count = mList.getCount(); mScrollCompleted = false; final Object[] sections = mSections; int sectionIndex; if (sections != null && sections.length > 1) { final int nSections = sections.length; int section = (int) (position * nSections); if (section >= nSections) { section = nSections - 1; } sectionIndex = section; final SectionIndexer baseAdapter = (SectionIndexer) mListAdapter; int index = baseAdapter.getPositionForSection(section); // Given the expected section and index, the following code will // try to account for missing sections (no names starting with..) // It will compute the scroll space of surrounding empty sections // and interpolate the currently visible letter's range across the // available space, so that there is always some list movement while // the user moves the thumb. int nextIndex = count; int prevIndex = index; int prevSection = section; int nextSection = section + 1; // Assume the next section is unique if (section < nSections - 1) { nextIndex = baseAdapter.getPositionForSection(section + 1); } // Find the previous index if we're slicing the previous section if (nextIndex == index) { // Non-existent letter while (section > 0) { section--; prevIndex = baseAdapter.getPositionForSection(section); if (prevIndex != index) { prevSection = section; sectionIndex = section; break; } } } // Find the next index, in case the assumed next index is not // unique. For instance, if there is no P, then request for P's // position actually returns Q's. So we need to look ahead to make // sure that there is really a Q at Q's position. If not, move // further down... int nextNextSection = nextSection + 1; while (nextNextSection < nSections && baseAdapter.getPositionForSection(nextNextSection) == nextIndex) { nextNextSection++; nextSection++; } // Compute the beginning and ending scroll range percentage of the // currently visible letter. This could be equal to or greater than // (1 / nSections). float fPrev = (float) prevSection / nSections; float fNext = (float) nextSection / nSections; index = prevIndex + (int) ((nextIndex - prevIndex) * (position - fPrev) / (fNext - fPrev)); // Don't overflow if (index > count - 1) index = count - 1; mList.setSelectionFromTop(index + mListOffset, 0); } else { int index = (int) (position * count); mList.setSelectionFromTop(index + mListOffset, 0); sectionIndex = -1; } if (sectionIndex >= 0) { String text = mSectionText = sections[sectionIndex].toString(); mDrawOverlay = (text.length() != 1 || text.charAt(0) != ' ') && sectionIndex < sections.length; } else { mDrawOverlay = false; } } private void cancelFling() { // Cancel the list fling MotionEvent cancelFling = MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0, 0, 0); mList.onTouchEvent(cancelFling); cancelFling.recycle(); } @Override public boolean onTouchEvent(MotionEvent me) { if (me.getAction() == MotionEvent.ACTION_DOWN) { if (me.getX() > getWidth() - mThumbW && me.getY() >= mThumbY && me.getY() <= mThumbY + mThumbH) { mDragging = true; if (mListAdapter == null && mList != null) { getSections(); } cancelFling(); return true; } } else if (me.getAction() == MotionEvent.ACTION_UP) { if (mDragging) { mDragging = false; final Handler handler = mHandler; handler.removeCallbacks(mScrollFade); handler.postDelayed(mScrollFade, 1000); return true; } } else if (me.getAction() == MotionEvent.ACTION_MOVE) { if (mDragging) { final int viewHeight = getHeight(); mThumbY = (int) me.getY() - mThumbH + 10; if (mThumbY < 0) { mThumbY = 0; } else if (mThumbY + mThumbH > viewHeight) { mThumbY = viewHeight - mThumbH; } // If the previous scrollTo is still pending if (mScrollCompleted) { scrollTo((float) mThumbY / (viewHeight - mThumbH)); } return true; } } return super.onTouchEvent(me); } public class ScrollFade implements Runnable { long mStartTime; long mFadeDuration; boolean mStarted; static final int ALPHA_MAX = 255; static final long FADE_DURATION = 200; void startFade() { mFadeDuration = FADE_DURATION; mStartTime = SystemClock.uptimeMillis(); mStarted = true; } int getAlpha() { if (!mStarted) { return ALPHA_MAX; } int alpha; long now = SystemClock.uptimeMillis(); if (now > mStartTime + mFadeDuration) { alpha = 0; } else { alpha = (int) (ALPHA_MAX - ((now - mStartTime) * ALPHA_MAX) / mFadeDuration); } return alpha; } public void run() { if (!mStarted) { startFade(); invalidate(); } if (getAlpha() > 0) { final int y = mThumbY; final int viewWidth = getWidth(); invalidate(viewWidth - mThumbW, y, viewWidth, y + mThumbH); } else { mStarted = false; removeThumb(); } } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.photostream; import android.os.*; import android.os.Process; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import java.util.concurrent.CancellationException; import java.util.concurrent.atomic.AtomicInteger; /** * <p>UserTask enables proper and easy use of the UI thread. This class allows to * perform background operations and publish results on the UI thread without * having to manipulate threads and/or handlers.</p> * * <p>A user task is defined by a computation that runs on a background thread and * whose result is published on the UI thread. A user task is defined by 3 generic * types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>, * and 4 steps, called <code>begin</code>, <code>doInBackground</code>, * <code>processProgress<code> and <code>end</code>.</p> * * <h2>Usage</h2> * <p>UserTask must be subclassed to be used. The subclass will override at least * one method ({@link #doInBackground(Object[])}), and most often will override a * second one ({@link #onPostExecute(Object)}.)</p> * * <p>Here is an example of subclassing:</p> * <pre> * private class DownloadFilesTask extends UserTask&lt;URL, Integer, Long&gt; { * public File doInBackground(URL... urls) { * int count = urls.length; * long totalSize = 0; * for (int i = 0; i < count; i++) { * totalSize += Downloader.downloadFile(urls[i]); * publishProgress((int) ((i / (float) count) * 100)); * } * } * * public void onProgressUpdate(Integer... progress) { * setProgressPercent(progress[0]); * } * * public void onPostExecute(Long result) { * showDialog("Downloaded " + result + " bytes"); * } * } * </pre> * * <p>Once created, a task is executed very simply:</p> * <pre> * new DownloadFilesTask().execute(new URL[] { ... }); * </pre> * * <h2>User task's generic types</h2> * <p>The three types used by a user task are the following:</p> * <ol> * <li><code>Params</code>, the type of the parameters sent to the task upon * execution.</li> * <li><code>Progress</code>, the type of the progress units published during * the background computation.</li> * <li><code>Result</code>, the type of the result of the background * computation.</li> * </ol> * <p>Not all types are always used by a user task. To mark a type as unused, * simply use the type {@link Void}:</p> * <pre> * private class MyTask extends UserTask<Void, Void, Void) { ... } * </pre> * * <h2>The 4 steps</h2> * <p>When a user task is executed, the task goes through 4 steps:</p> * <ol> * <li>{@link #onPreExecute()}, invoked on the UI thread immediately after the task * is executed. This step is normally used to setup the task, for instance by * showing a progress bar in the user interface.</li> * <li>{@link #doInBackground(Object[])}, invoked on the background thread * immediately after {@link # onPreExecute ()} finishes executing. This step is used * to perform background computation that can take a long time. The parameters * of the user task are passed to this step. The result of the computation must * be returned by this step and will be passed back to the last step. This step * can also use {@link #publishProgress(Object[])} to publish one or more units * of progress. These values are published on the UI thread, in the * {@link #onProgressUpdate(Object[])} step.</li> * <li>{@link # onProgressUpdate (Object[])}, invoked on the UI thread after a * call to {@link #publishProgress(Object[])}. The timing of the execution is * undefined. This method is used to display any form of progress in the user * interface while the background computation is still executing. For instance, * it can be used to animate a progress bar or show logs in a text field.</li> * <li>{@link # onPostExecute (Object)}, invoked on the UI thread after the background * computation finishes. The result of the background computation is passed to * this step as a parameter.</li> * </ol> * * <h2>Threading rules</h2> * <p>There are a few threading rules that must be followed for this class to * work properly:</p> * <ul> * <li>The task instance must be created on the UI thread.</li> * <li>{@link #execute(Object[])} must be invoked on the UI thread.</li> * <li>Do not call {@link # onPreExecute ()}, {@link # onPostExecute (Object)}, * {@link #doInBackground(Object[])}, {@link # onProgressUpdate (Object[])} * manually.</li> * <li>The task can be executed only once (an exception will be thrown if * a second execution is attempted.)</li> * </ul> */ public abstract class UserTask<Params, Progress, Result> { private static final String LOG_TAG = "UserTask"; private static final int CORE_POOL_SIZE = 1; private static final int MAXIMUM_POOL_SIZE = 10; private static final int KEEP_ALIVE = 10; private static final BlockingQueue<Runnable> sWorkQueue = new LinkedBlockingQueue<Runnable>(MAXIMUM_POOL_SIZE); private static final ThreadFactory sThreadFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); public Thread newThread(Runnable r) { return new Thread(r, "UserTask #" + mCount.getAndIncrement()); } }; private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory); private static final int MESSAGE_POST_RESULT = 0x1; private static final int MESSAGE_POST_PROGRESS = 0x2; private static final int MESSAGE_POST_CANCEL = 0x3; private static final InternalHandler sHandler = new InternalHandler(); private final WorkerRunnable<Params, Result> mWorker; private final FutureTask<Result> mFuture; private volatile Status mStatus = Status.PENDING; /** * Indicates the current status of the task. Each status will be set only once * during the lifetime of a task. */ public enum Status { /** * Indicates that the task has not been executed yet. */ PENDING, /** * Indicates that the task is running. */ RUNNING, /** * Indicates that {@link UserTask#onPostExecute(Object)} has finished. */ FINISHED, } /** * Creates a new user task. This constructor must be invoked on the UI thread. */ public UserTask() { mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); return doInBackground(mParams); } }; mFuture = new FutureTask<Result>(mWorker) { @Override protected void done() { Message message; Result result = null; try { result = get(); } catch (InterruptedException e) { android.util.Log.w(LOG_TAG, e); } catch (ExecutionException e) { throw new RuntimeException("An error occured while executing doInBackground()", e.getCause()); } catch (CancellationException e) { message = sHandler.obtainMessage(MESSAGE_POST_CANCEL, new UserTaskResult<Result>(UserTask.this, (Result[]) null)); message.sendToTarget(); return; } catch (Throwable t) { throw new RuntimeException("An error occured while executing " + "doInBackground()", t); } message = sHandler.obtainMessage(MESSAGE_POST_RESULT, new UserTaskResult<Result>(UserTask.this, result)); message.sendToTarget(); } }; } /** * Returns the current status of this task. * * @return The current status. */ public final Status getStatus() { return mStatus; } /** * Override this method to perform a computation on a background thread. The * specified parameters are the parameters passed to {@link #execute(Object[])} * by the caller of this task. * * This method can call {@link #publishProgress(Object[])} to publish updates * on the UI thread. * * @param params The parameters of the task. * * @return A result, defined by the subclass of this task. * * @see #onPreExecute() * @see #onPostExecute(Object) * @see #publishProgress(Object[]) */ public abstract Result doInBackground(Params... params); /** * Runs on the UI thread before {@link #doInBackground(Object[])}. * * @see #onPostExecute(Object) * @see #doInBackground(Object[]) */ public void onPreExecute() { } /** * Runs on the UI thread after {@link #doInBackground(Object[])}. The * specified result is the value returned by {@link #doInBackground(Object[])} * or null if the task was cancelled or an exception occured. * * @param result The result of the operation computed by {@link #doInBackground(Object[])}. * * @see #onPreExecute() * @see #doInBackground(Object[]) */ @SuppressWarnings({"UnusedDeclaration"}) public void onPostExecute(Result result) { } /** * Runs on the UI thread after {@link #publishProgress(Object[])} is invoked. * The specified values are the values passed to {@link #publishProgress(Object[])}. * * @param values The values indicating progress. * * @see #publishProgress(Object[]) * @see #doInBackground(Object[]) */ @SuppressWarnings({"UnusedDeclaration"}) public void onProgressUpdate(Progress... values) { } /** * Runs on the UI thread after {@link #cancel(boolean)} is invoked. * * @see #cancel(boolean) * @see #isCancelled() */ public void onCancelled() { } /** * Returns <tt>true</tt> if this task was cancelled before it completed * normally. * * @return <tt>true</tt> if task was cancelled before it completed * * @see #cancel(boolean) */ public final boolean isCancelled() { return mFuture.isCancelled(); } /** * Attempts to cancel execution of this task. This attempt will * fail if the task has already completed, already been cancelled, * or could not be cancelled for some other reason. If successful, * and this task has not started when <tt>cancel</tt> is called, * this task should never run. If the task has already started, * then the <tt>mayInterruptIfRunning</tt> parameter determines * whether the thread executing this task should be interrupted in * an attempt to stop the task. * * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this * task should be interrupted; otherwise, in-progress tasks are allowed * to complete. * * @return <tt>false</tt> if the task could not be cancelled, * typically because it has already completed normally; * <tt>true</tt> otherwise * * @see #isCancelled() * @see #onCancelled() */ public final boolean cancel(boolean mayInterruptIfRunning) { return mFuture.cancel(mayInterruptIfRunning); } /** * Waits if necessary for the computation to complete, and then * retrieves its result. * * @return The computed result. * * @throws CancellationException If the computation was cancelled. * @throws ExecutionException If the computation threw an exception. * @throws InterruptedException If the current thread was interrupted * while waiting. */ public final Result get() throws InterruptedException, ExecutionException { return mFuture.get(); } /** * Waits if necessary for at most the given time for the computation * to complete, and then retrieves its result. * * @param timeout Time to wait before cancelling the operation. * @param unit The time unit for the timeout. * * @return The computed result. * * @throws CancellationException If the computation was cancelled. * @throws ExecutionException If the computation threw an exception. * @throws InterruptedException If the current thread was interrupted * while waiting. * @throws TimeoutException If the wait timed out. */ public final Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return mFuture.get(timeout, unit); } /** * Executes the task with the specified parameters. The task returns * itself (this) so that the caller can keep a reference to it. * * This method must be invoked on the UI thread. * * @param params The parameters of the task. * * @return This instance of UserTask. * * @throws IllegalStateException If {@link #getStatus()} returns either * {@link UserTask.Status#RUNNING} or {@link UserTask.Status#FINISHED}. */ public final UserTask<Params, Progress, Result> execute(Params... params) { if (mStatus != Status.PENDING) { switch (mStatus) { case RUNNING: throw new IllegalStateException("Cannot execute task:" + " the task is already running."); case FINISHED: throw new IllegalStateException("Cannot execute task:" + " the task has already been executed " + "(a task can be executed only once)"); } } mStatus = Status.RUNNING; onPreExecute(); mWorker.mParams = params; sExecutor.execute(mFuture); return this; } /** * This method can be invoked from {@link #doInBackground(Object[])} to * publish updates on the UI thread while the background computation is * still running. Each call to this method will trigger the execution of * {@link #onProgressUpdate(Object[])} on the UI thread. * * @param values The progress values to update the UI with. * * @see # onProgressUpdate (Object[]) * @see #doInBackground(Object[]) */ protected final void publishProgress(Progress... values) { sHandler.obtainMessage(MESSAGE_POST_PROGRESS, new UserTaskResult<Progress>(this, values)).sendToTarget(); } private void finish(Result result) { onPostExecute(result); mStatus = Status.FINISHED; } private static class InternalHandler extends Handler { @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) @Override public void handleMessage(Message msg) { UserTaskResult result = (UserTaskResult) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT: // There is only one result result.mTask.finish(result.mData[0]); break; case MESSAGE_POST_PROGRESS: result.mTask.onProgressUpdate(result.mData); break; case MESSAGE_POST_CANCEL: result.mTask.onCancelled(); break; } } } private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> { Params[] mParams; } @SuppressWarnings({"RawUseOfParameterizedType"}) private static class UserTaskResult<Data> { final UserTask mTask; final Data[] mData; UserTaskResult(UserTask task, Data... data) { mTask = task; mData = data; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.photostream; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.LayoutInflater; import android.view.ContextMenu; import android.view.MenuItem; import android.view.Menu; import android.view.KeyEvent; import android.view.animation.AnimationUtils; import android.view.animation.Animation; import android.widget.TextView; import android.widget.ListView; import android.widget.CursorAdapter; import android.widget.AdapterView; import android.widget.ProgressBar; import android.content.Intent; import android.content.Context; import android.content.ContentValues; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.HashMap; /** * Activity used to login the user. The activity asks for the user name and then add * the user to the users list upong successful login. If the login is unsuccessful, * an error message is displayed. Clicking any stored user launches PhotostreamActivity. * * This activity is also used to create Home shortcuts. When the intent * {@link Intent#ACTION_CREATE_SHORTCUT} is used to start this activity, sucessful login * returns a shortcut Intent to Home instead of proceeding to PhotostreamActivity. * * The shortcut Intent contains the real name of the user, his buddy icon, the action * {@link android.content.Intent#ACTION_VIEW} and the URI flickr://photos/nsid. */ public class LoginActivity extends Activity implements View.OnKeyListener, AdapterView.OnItemClickListener { private static final int MENU_ID_SHOW = 1; private static final int MENU_ID_DELETE = 2; private boolean mCreateShortcut; private TextView mUsername; private ProgressBar mProgress; private SQLiteDatabase mDatabase; private UsersAdapter mAdapter; private UserTask<String, Void, Flickr.User> mTask; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); schedule(); // If the activity was started with the "create shortcut" action, we // remember this to change the behavior upon successful login if (Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction())) { mCreateShortcut = true; } mDatabase = new UserDatabase(this).getWritableDatabase(); setContentView(R.layout.screen_login); setupViews(); } private void schedule() { //SharedPreferences preferences = getSharedPreferences(Preferences.NAME, MODE_PRIVATE); //if (!preferences.getBoolean(Preferences.KEY_ALARM_SCHEDULED, false)) { CheckUpdateService.schedule(this); // preferences.edit().putBoolean(Preferences.KEY_ALARM_SCHEDULED, true).commit(); //} } private void setupViews() { mUsername = (TextView) findViewById(R.id.input_username); mUsername.setOnKeyListener(this); mUsername.requestFocus(); mAdapter = new UsersAdapter(this, initializeCursor()); final ListView userList = (ListView) findViewById(R.id.list_users); userList.setAdapter(mAdapter); userList.setOnItemClickListener(this); registerForContextMenu(userList); mProgress = (ProgressBar) findViewById(R.id.progress); } private Cursor initializeCursor() { Cursor cursor = mDatabase.query(UserDatabase.TABLE_USERS, new String[] { UserDatabase._ID, UserDatabase.COLUMN_REALNAME, UserDatabase.COLUMN_NSID, UserDatabase.COLUMN_BUDDY_ICON }, null, null, null, null, UserDatabase.SORT_DEFAULT); startManagingCursor(cursor); return cursor; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.login, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case R.id.menu_item_settings: SettingsActivity.show(this); return true; case R.id.menu_item_info: Eula.showDisclaimer(this); return true; } return super.onMenuItemSelected(featureId, item); } public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP) { switch (v.getId()) { case R.id.input_username: if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { onAddUser(mUsername.getText().toString()); return true; } break; } } return false; } public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final Flickr.User user = Flickr.User.fromId(((UserDescription) view.getTag()).nsid); if (!mCreateShortcut) { onShowPhotostream(user); } else { onCreateShortcut(user); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; menu.setHeaderTitle(((TextView) info.targetView).getText()); menu.add(0, MENU_ID_SHOW, 0, R.string.context_menu_show_photostream); menu.add(0, MENU_ID_DELETE, 0, R.string.context_menu_delete_user); } @Override public boolean onContextItemSelected(MenuItem item) { final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); final UserDescription description = (UserDescription) info.targetView.getTag(); switch (item.getItemId()) { case MENU_ID_SHOW: final Flickr.User user = Flickr.User.fromId(description.nsid); onShowPhotostream(user); return true; case MENU_ID_DELETE: onRemoveUser(description.id); return true; } return super.onContextItemSelected(item); } @Override protected void onResume() { super.onResume(); if (mProgress.getVisibility() == View.VISIBLE) { mProgress.setVisibility(View.GONE); } } @Override protected void onDestroy() { super.onDestroy(); if (mTask != null && mTask.getStatus() == UserTask.Status.RUNNING) { mTask.cancel(true); } mAdapter.cleanup(); mDatabase.close(); } private void onAddUser(String username) { // When the user enters his user name, we need to find his NSID before // adding it to the list. mTask = new FindUserTask().execute(username); } private void onRemoveUser(String id) { int rows = mDatabase.delete(UserDatabase.TABLE_USERS, UserDatabase._ID + "=?", new String[] { id }); if (rows > 0) { mAdapter.refresh(); } } private void onError() { hideProgress(); mUsername.setError(getString(R.string.screen_login_error)); } private void hideProgress() { if (mProgress.getVisibility() != View.GONE) { final Animation fadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out); mProgress.setVisibility(View.GONE); mProgress.startAnimation(fadeOut); } } private void showProgress() { if (mProgress.getVisibility() != View.VISIBLE) { final Animation fadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in); mProgress.setVisibility(View.VISIBLE); mProgress.startAnimation(fadeIn); } } private void onShowPhotostream(Flickr.User user) { PhotostreamActivity.show(this, user); } /** * Creates the shortcut Intent to send back to Home. The intent is a view action * to a flickr://photos/nsid URI, with a title (real name or user name) and a * custom icon (the user's buddy icon.) * * @param user The user to create a shortcut for. */ private void onCreateShortcut(Flickr.User user) { final Cursor cursor = mDatabase.query(UserDatabase.TABLE_USERS, new String[] { UserDatabase.COLUMN_REALNAME, UserDatabase.COLUMN_USERNAME, UserDatabase.COLUMN_BUDDY_ICON }, UserDatabase.COLUMN_NSID + "=?", new String[] { user.getId() }, null, null, UserDatabase.SORT_DEFAULT); cursor.moveToFirst(); final Intent shortcutIntent = new Intent(PhotostreamActivity.ACTION); shortcutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); shortcutIntent.putExtra(PhotostreamActivity.EXTRA_NSID, user.getId()); // Sets the custom shortcut's title to the real name of the user. If no // real name was found, use the user name instead. final Intent intent = new Intent(); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); String name = cursor.getString(cursor.getColumnIndexOrThrow(UserDatabase.COLUMN_REALNAME)); if (name == null || name.length() == 0) { name = cursor.getString(cursor.getColumnIndexOrThrow(UserDatabase.COLUMN_USERNAME)); } intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name); // Sets the custom shortcut icon to the user's buddy icon. If no buddy // icon was found, use a default local buddy icon instead. byte[] data = cursor.getBlob(cursor.getColumnIndexOrThrow(UserDatabase.COLUMN_BUDDY_ICON)); Bitmap icon = BitmapFactory.decodeByteArray(data, 0, data.length); if (icon != null) { intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, icon); } else { intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.default_buddyicon)); } setResult(RESULT_OK, intent); finish(); } /** * Background task used to load the user's NSID. The task begins by showing the * progress bar, then loads the user NSID from the network and finally open * PhotostreamActivity. */ private class FindUserTask extends UserTask<String, Void, Flickr.User> { @Override public void onPreExecute() { showProgress(); } public Flickr.User doInBackground(String... params) { final String name = params[0].trim(); if (name.length() == 0) return null; final Flickr.User user = Flickr.get().findByUserName(name); if (isCancelled() || user == null) return null; Flickr.UserInfo info = Flickr.get().getUserInfo(user); if (isCancelled() || info == null) return null; String realname = info.getRealName(); if (realname == null) realname = name; final ContentValues values = new ContentValues(); values.put(UserDatabase.COLUMN_USERNAME, name); values.put(UserDatabase.COLUMN_REALNAME, realname); values.put(UserDatabase.COLUMN_NSID, user.getId()); values.put(UserDatabase.COLUMN_LAST_UPDATE, System.currentTimeMillis()); UserDatabase.writeBitmap(values, UserDatabase.COLUMN_BUDDY_ICON, info.loadBuddyIcon()); long result = -1; if (!isCancelled()) { result = mDatabase.insert(UserDatabase.TABLE_USERS, UserDatabase.COLUMN_REALNAME, values); } return result != -1 ? user : null; } @Override public void onPostExecute(Flickr.User user) { if (user == null) { onError(); } else { mAdapter.refresh(); hideProgress(); } } } private class UsersAdapter extends CursorAdapter { private final LayoutInflater mInflater; private final int mRealname; private final int mId; private final int mNsid; private final int mBuddyIcon; private final Drawable mDefaultIcon; private final HashMap<String, Drawable> mIcons = new HashMap<String, Drawable>(); public UsersAdapter(Context context, Cursor cursor) { super(context, cursor, true); mInflater = LayoutInflater.from(context); mDefaultIcon = context.getResources().getDrawable(R.drawable.default_buddyicon); mRealname = cursor.getColumnIndexOrThrow(UserDatabase.COLUMN_REALNAME); mId = cursor.getColumnIndexOrThrow(UserDatabase._ID); mNsid = cursor.getColumnIndexOrThrow(UserDatabase.COLUMN_NSID); mBuddyIcon = cursor.getColumnIndexOrThrow(UserDatabase.COLUMN_BUDDY_ICON); } public View newView(Context context, Cursor cursor, ViewGroup parent) { final View view = mInflater.inflate(R.layout.list_item_user, parent, false); final UserDescription description = new UserDescription(); view.setTag(description); return view; } public void bindView(View view, Context context, Cursor cursor) { final UserDescription description = (UserDescription) view.getTag(); description.id = cursor.getString(mId); description.nsid = cursor.getString(mNsid); final TextView textView = (TextView) view; textView.setText(cursor.getString(mRealname)); Drawable icon = mIcons.get(description.nsid); if (icon == null) { final byte[] data = cursor.getBlob(mBuddyIcon); Bitmap bitmap = null; if (data != null) bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); if (bitmap != null) { icon = new FastBitmapDrawable(bitmap); } else { icon = mDefaultIcon; } mIcons.put(description.nsid, icon); } textView.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null); } void cleanup() { for (Drawable icon : mIcons.values()) { icon.setCallback(null); } } void refresh() { getCursor().requery(); } } private static class UserDescription { String id; String nsid; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.photostream; final class Preferences { static final String NAME = "Photostream"; static final String KEY_ALARM_SCHEDULED = "photostream.scheduled"; static final String KEY_ENABLE_NOTIFICATIONS = "photostream.enable-notifications"; static final String KEY_VIBRATE = "photostream.vibrate"; static final String KEY_RINGTONE = "photostream.ringtone"; Preferences() { } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.photostream; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase; import android.content.Context; import android.content.ContentValues; import android.util.Log; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.provider.BaseColumns; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * Helper class to interact with the database that stores the Flickr contacts. */ class UserDatabase extends SQLiteOpenHelper implements BaseColumns { private static final String DATABASE_NAME = "flickr"; private static final int DATABASE_VERSION = 1; static final String TABLE_USERS = "users"; static final String COLUMN_USERNAME = "username"; static final String COLUMN_REALNAME = "realname"; static final String COLUMN_NSID = "nsid"; static final String COLUMN_BUDDY_ICON = "buddy_icon"; static final String COLUMN_LAST_UPDATE = "last_update"; static final String SORT_DEFAULT = COLUMN_USERNAME + " ASC"; private Context mContext; UserDatabase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); mContext = context; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE users (" + "_id INTEGER PRIMARY KEY, " + "username TEXT, " + "realname TEXT, " + "nsid TEXT, " + "buddy_icon BLOB," + "last_update INTEGER);"); addUser(db, "Bob Lee", "Bob Lee", "45701389@N00", R.drawable.boblee_buddyicon); addUser(db, "ericktseng", "Erick Tseng", "76701017@N00", R.drawable.ericktseng_buddyicon); addUser(db, "romainguy", "Romain Guy", "24046097@N00", R.drawable.romainguy_buddyicon); } private void addUser(SQLiteDatabase db, String userName, String realName, String nsid, int icon) { final ContentValues values = new ContentValues(); values.put(COLUMN_USERNAME, userName); values.put(COLUMN_REALNAME, realName); values.put(COLUMN_NSID, nsid); values.put(COLUMN_LAST_UPDATE, System.currentTimeMillis()); final Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), icon); writeBitmap(values, COLUMN_BUDDY_ICON, bitmap); db.insert(TABLE_USERS, COLUMN_LAST_UPDATE, values); } static void writeBitmap(ContentValues values, String name, Bitmap bitmap) { if (bitmap != null) { // Try go guesstimate how much space the icon will take when serialized // to avoid unnecessary allocations/copies during the write. int size = bitmap.getWidth() * bitmap.getHeight() * 2; ByteArrayOutputStream out = new ByteArrayOutputStream(size); try { bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); out.flush(); out.close(); values.put(name, out.toByteArray()); } catch (IOException e) { // Ignore } } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(Flickr.LOG_TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS users"); onCreate(db); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.photostream; import android.app.Activity; import android.app.NotificationManager; import android.os.Bundle; import android.content.Intent; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.animation.TranslateAnimation; import android.view.animation.Animation; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.AnimationUtils; import android.view.animation.LayoutAnimationController; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.widget.ImageView; import android.widget.ViewAnimator; import java.util.Random; import java.util.List; /** * Activity used to display a Flickr user's photostream. This activity shows a fixed * number of photos at a time. The activity is invoked either by LoginActivity, when * the application is launched normally, or by a Home shortcut, or by an Intent with * the view action and a flickr://photos/nsid URI. */ public class PhotostreamActivity extends Activity implements View.OnClickListener, Animation.AnimationListener { static final String ACTION = "com.google.android.photostream.FLICKR_STREAM"; static final String EXTRA_NOTIFICATION = "com.google.android.photostream.extra_notify_id"; static final String EXTRA_NSID = "com.google.android.photostream.extra_nsid"; static final String EXTRA_USER = "com.google.android.photostream.extra_user"; private static final String STATE_USER = "com.google.android.photostream.state_user"; private static final String STATE_PAGE = "com.google.android.photostream.state_page"; private static final String STATE_PAGE_COUNT = "com.google.android.photostream.state_pagecount"; private static final int PHOTOS_COUNT_PER_PAGE = 6; private Flickr.User mUser; private int mCurrentPage = 1; private int mPageCount = 0; private LayoutInflater mInflater; private ViewAnimator mSwitcher; private View mMenuNext; private View mMenuBack; private View mMenuSeparator; private GridLayout mGrid; private LayoutAnimationController mNextAnimation; private LayoutAnimationController mBackAnimation; private UserTask<?, ?, ?> mTask; private String mUsername; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); clearNotification(); // Try to find a user name in the saved instance state or the intent // that launched the activity. If no valid user NSID can be found, we // just close the activity. if (!initialize(savedInstanceState)) { finish(); return; } setContentView(R.layout.screen_photostream); setupViews(); loadPhotos(); } private void clearNotification() { final int notification = getIntent().getIntExtra(EXTRA_NOTIFICATION, -1); if (notification != -1) { NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.cancel(notification); } } /** * Starts the PhotostreamActivity for the specified user. * * @param context The application's environment. * @param user The user whose photos to display with a PhotostreamActivity. */ static void show(Context context, Flickr.User user) { final Intent intent = new Intent(ACTION); intent.putExtra(EXTRA_USER, user); context.startActivity(intent); } /** * Restores a previously saved state or, if missing, finds the user's NSID * from the intent used to start the activity. * * @param savedInstanceState The saved state, if any. * * @return true if a {@link com.google.android.photostream.Flickr.User} was * found either in the saved state or the intent. */ private boolean initialize(Bundle savedInstanceState) { Flickr.User user; if (savedInstanceState != null) { user = savedInstanceState.getParcelable(STATE_USER); mCurrentPage = savedInstanceState.getInt(STATE_PAGE); mPageCount = savedInstanceState.getInt(STATE_PAGE_COUNT); } else { user = getUser(); } mUser = user; return mUser != null || mUsername != null; } /** * Creates a {@link com.google.android.photostream.Flickr.User} instance * from the intent used to start this activity. * * @return The user whose photos will be displayed, or null if no * user was found. */ private Flickr.User getUser() { final Intent intent = getIntent(); final String action = intent.getAction(); Flickr.User user = null; if (ACTION.equals(action)) { final Bundle extras = intent.getExtras(); if (extras != null) { user = extras.getParcelable(EXTRA_USER); if (user == null) { final String nsid = extras.getString(EXTRA_NSID); if (nsid != null) { user = Flickr.User.fromId(nsid); } } } } else if (Intent.ACTION_VIEW.equals(action)) { final List<String> segments = intent.getData().getPathSegments(); if (segments.size() > 1) { mUsername = segments.get(1); } } return user; } private void setupViews() { mInflater = LayoutInflater.from(PhotostreamActivity.this); mNextAnimation = AnimationUtils.loadLayoutAnimation(this, R.anim.layout_slide_next); mBackAnimation = AnimationUtils.loadLayoutAnimation(this, R.anim.layout_slide_back); mSwitcher = (ViewAnimator) findViewById(R.id.switcher_menu); mMenuNext = findViewById(R.id.menu_next); mMenuBack = findViewById(R.id.menu_back); mMenuSeparator = findViewById(R.id.menu_separator); mGrid = (GridLayout) findViewById(R.id.grid_photos); mMenuNext.setOnClickListener(this); mMenuBack.setOnClickListener(this); mMenuBack.setVisibility(View.GONE); mMenuSeparator.setVisibility(View.GONE); mGrid.setClipToPadding(false); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(STATE_USER, mUser); outState.putInt(STATE_PAGE, mCurrentPage); outState.putInt(STATE_PAGE_COUNT, mPageCount); } @Override protected void onDestroy() { super.onDestroy(); if (mTask != null && mTask.getStatus() == UserTask.Status.RUNNING) { mTask.cancel(true); } } public void onClick(View v) { switch (v.getId()) { case R.id.menu_next: onNext(); break; case R.id.menu_back: onBack(); break; default: onShowPhoto((Flickr.Photo) v.getTag()); break; } } @Override public Object onRetainNonConfigurationInstance() { final GridLayout grid = mGrid; final int count = grid.getChildCount(); final LoadedPhoto[] list = new LoadedPhoto[count]; for (int i = 0; i < count; i++) { final ImageView v = (ImageView) grid.getChildAt(i); list[i] = new LoadedPhoto(((BitmapDrawable) v.getDrawable()).getBitmap(), (Flickr.Photo) v.getTag()); } return list; } private void prepareMenu(int pageCount) { final boolean backVisible = mCurrentPage > 1; final boolean nextVisible = mCurrentPage < pageCount; mMenuBack.setVisibility(backVisible ? View.VISIBLE : View.GONE); mMenuNext.setVisibility(nextVisible ? View.VISIBLE : View.GONE); mMenuSeparator.setVisibility(backVisible && nextVisible ? View.VISIBLE : View.GONE); } private void loadPhotos() { final Object data = getLastNonConfigurationInstance(); if (data == null) { mTask = new GetPhotoListTask().execute(mCurrentPage); } else { final LoadedPhoto[] photos = (LoadedPhoto[]) data; for (LoadedPhoto photo : photos) { addPhoto(photo); } prepareMenu(mPageCount); mSwitcher.showNext(); } } private void showPhotos(Flickr.PhotoList photos) { mTask = new LoadPhotosTask().execute(photos); } private void onShowPhoto(Flickr.Photo photo) { ViewPhotoActivity.show(this, photo); } private void onNext() { mCurrentPage++; animateAndLoadPhotos(mNextAnimation); } private void onBack() { mCurrentPage--; animateAndLoadPhotos(mBackAnimation); } private void animateAndLoadPhotos(LayoutAnimationController animation) { mSwitcher.showNext(); mGrid.setLayoutAnimationListener(this); mGrid.setLayoutAnimation(animation); mGrid.invalidate(); } public void onAnimationEnd(Animation animation) { mGrid.setLayoutAnimationListener(null); mGrid.setLayoutAnimation(null); mGrid.removeAllViews(); loadPhotos(); } public void onAnimationStart(Animation animation) { } public void onAnimationRepeat(Animation animation) { } private static Animation createAnimationForChild(int childIndex) { boolean firstColumn = (childIndex & 0x1) == 0; Animation translate = new TranslateAnimation( Animation.RELATIVE_TO_SELF, firstColumn ? -1.1f : 1.1f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f); translate.setInterpolator(new AccelerateDecelerateInterpolator()); translate.setFillAfter(false); translate.setDuration(300); return translate; } private void addPhoto(LoadedPhoto... value) { ImageView image = (ImageView) mInflater.inflate(R.layout.grid_item_photo, mGrid, false); image.setImageBitmap(value[0].mBitmap); image.startAnimation(createAnimationForChild(mGrid.getChildCount())); image.setTag(value[0].mPhoto); image.setOnClickListener(PhotostreamActivity.this); mGrid.addView(image); } /** * Background task used to load each individual photo. The task loads each photo * in order and publishes each loaded Bitmap as a progress unit. The tasks ends * by hiding the progress bar and showing the menu. */ private class LoadPhotosTask extends UserTask<Flickr.PhotoList, LoadedPhoto, Flickr.PhotoList> { private final Random mRandom; private LoadPhotosTask() { mRandom = new Random(); } public Flickr.PhotoList doInBackground(Flickr.PhotoList... params) { final Flickr.PhotoList list = params[0]; final int count = list.getCount(); for (int i = 0; i < count; i++) { if (isCancelled()) break; final Flickr.Photo photo = list.get(i); Bitmap bitmap = photo.loadPhotoBitmap(Flickr.PhotoSize.THUMBNAIL); if (!isCancelled()) { if (bitmap == null) { final boolean portrait = mRandom.nextFloat() >= 0.5f; bitmap = BitmapFactory.decodeResource(getResources(), portrait ? R.drawable.not_found_small_1 : R.drawable.not_found_small_2); } publishProgress(new LoadedPhoto(ImageUtilities.rotateAndFrame(bitmap), photo)); bitmap.recycle(); } } return list; } /** * Whenever a photo's Bitmap is loaded from the background thread, it is * displayed in this method by adding a new ImageView in the photos grid. * Each ImageView's tag contains the {@link com.google.android.photostream.Flickr.Photo} * it was loaded from. * * @param value The photo and its bitmap. */ @Override public void onProgressUpdate(LoadedPhoto... value) { addPhoto(value); } @Override public void onPostExecute(Flickr.PhotoList result) { mPageCount = result.getPageCount(); prepareMenu(mPageCount); mSwitcher.showNext(); mTask = null; } } /** * Background task used to load the list of photos. The tasks queries Flickr for the * list of photos to display and ends by starting the LoadPhotosTask. */ private class GetPhotoListTask extends UserTask<Integer, Void, Flickr.PhotoList> { public Flickr.PhotoList doInBackground(Integer... params) { if (mUsername != null) { mUser = Flickr.get().findByUserName(mUsername); mUsername = null; } return Flickr.get().getPublicPhotos(mUser, PHOTOS_COUNT_PER_PAGE, params[0]); } @Override public void onPostExecute(Flickr.PhotoList photoList) { showPhotos(photoList); mTask = null; } } /** * A LoadedPhoto contains the Flickr photo and the Bitmap loaded for that photo. */ private static class LoadedPhoto { Bitmap mBitmap; Flickr.Photo mPhoto; LoadedPhoto(Bitmap bitmap, Flickr.Photo photo) { mBitmap = bitmap; mPhoto = photo; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.photostream; import android.os.Bundle; import android.preference.PreferenceActivity; import android.content.Context; import android.content.Intent; public class SettingsActivity extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getPreferenceManager().setSharedPreferencesName(Preferences.NAME); addPreferencesFromResource(R.xml.preferences); } /** * Starts the PreferencesActivity for the specified user. * * @param context The application's environment. */ static void show(Context context) { final Intent intent = new Intent(context, SettingsActivity.class); context.startActivity(intent); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.photostream; import android.graphics.drawable.Drawable; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.PixelFormat; import android.graphics.ColorFilter; class FastBitmapDrawable extends Drawable { private Bitmap mBitmap; FastBitmapDrawable(Bitmap b) { mBitmap = b; } @Override public void draw(Canvas canvas) { canvas.drawBitmap(mBitmap, 0.0f, 0.0f, null); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } @Override public void setAlpha(int alpha) { } @Override public void setColorFilter(ColorFilter cf) { } @Override public int getIntrinsicWidth() { return mBitmap.getWidth(); } @Override public int getIntrinsicHeight() { return mBitmap.getHeight(); } @Override public int getMinimumWidth() { return mBitmap.getWidth(); } @Override public int getMinimumHeight() { return mBitmap.getHeight(); } public Bitmap getBitmap() { return mBitmap; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.photostream; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpVersion; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.params.HttpParams; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpProtocolParams; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.OutputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.text.SimpleDateFormat; import java.text.ParseException; import java.net.URL; import android.util.Xml; import android.view.InflateException; import android.net.Uri; import android.os.Parcelable; import android.os.Parcel; import android.graphics.Bitmap; import android.graphics.BitmapFactory; /** * Utility class to interact with the Flickr REST-based web services. * * This class uses a default Flickr API key that you should replace with your own if * you reuse this code to redistribute it with your application(s). * * This class is used as a singleton and cannot be instanciated. Instead, you must use * {@link #get()} to retrieve the unique instance of this class. */ class Flickr { static final String LOG_TAG = "Photostream"; // IMPORTANT: Replace this Flickr API key with your own private static final String API_KEY = "730e3a4f253b30adf30177df803d38c4"; private static final String API_REST_HOST = "api.flickr.com"; private static final String API_REST_URL = "/services/rest/"; private static final String API_FEED_URL = "/services/feeds/photos_public.gne"; private static final String API_PEOPLE_FIND_BY_USERNAME = "flickr.people.findByUsername"; private static final String API_PEOPLE_GET_INFO = "flickr.people.getInfo"; private static final String API_PEOPLE_GET_PUBLIC_PHOTOS = "flickr.people.getPublicPhotos"; private static final String API_PEOPLE_GET_LOCATION = "flickr.photos.geo.getLocation"; private static final String PARAM_API_KEY = "api_key"; private static final String PARAM_METHOD= "method"; private static final String PARAM_USERNAME = "username"; private static final String PARAM_USERID = "user_id"; private static final String PARAM_PER_PAGE = "per_page"; private static final String PARAM_PAGE = "page"; private static final String PARAM_EXTRAS = "extras"; private static final String PARAM_PHOTO_ID = "photo_id"; private static final String PARAM_FEED_ID = "id"; private static final String PARAM_FEED_FORMAT = "format"; private static final String VALUE_DEFAULT_EXTRAS = "date_taken"; private static final String VALUE_DEFAULT_FORMAT = "atom"; private static final String RESPONSE_TAG_RSP = "rsp"; private static final String RESPONSE_ATTR_STAT = "stat"; private static final String RESPONSE_STATUS_OK = "ok"; private static final String RESPONSE_TAG_USER = "user"; private static final String RESPONSE_ATTR_NSID = "nsid"; private static final String RESPONSE_TAG_PHOTOS = "photos"; private static final String RESPONSE_ATTR_PAGE = "page"; private static final String RESPONSE_ATTR_PAGES = "pages"; private static final String RESPONSE_TAG_PHOTO = "photo"; private static final String RESPONSE_ATTR_ID = "id"; private static final String RESPONSE_ATTR_SECRET = "secret"; private static final String RESPONSE_ATTR_SERVER = "server"; private static final String RESPONSE_ATTR_FARM = "farm"; private static final String RESPONSE_ATTR_TITLE = "title"; private static final String RESPONSE_ATTR_DATE_TAKEN = "datetaken"; private static final String RESPONSE_TAG_PERSON = "person"; private static final String RESPONSE_ATTR_ISPRO = "ispro"; private static final String RESPONSE_ATTR_ICONSERVER = "iconserver"; private static final String RESPONSE_ATTR_ICONFARM = "iconfarm"; private static final String RESPONSE_TAG_USERNAME = "username"; private static final String RESPONSE_TAG_REALNAME = "realname"; private static final String RESPONSE_TAG_LOCATION = "location"; private static final String RESPONSE_ATTR_LATITUDE = "latitude"; private static final String RESPONSE_ATTR_LONGITUDE = "longitude"; private static final String RESPONSE_TAG_PHOTOSURL = "photosurl"; private static final String RESPONSE_TAG_PROFILEURL = "profileurl"; private static final String RESPONSE_TAG_MOBILEURL = "mobileurl"; private static final String RESPONSE_TAG_FEED = "feed"; private static final String RESPONSE_TAG_UPDATED = "updated"; private static final String PHOTO_IMAGE_URL = "http://farm%s.static.flickr.com/%s/%s_%s%s.jpg"; private static final String BUDDY_ICON_URL = "http://farm%s.static.flickr.com/%s/buddyicons/%s.jpg"; private static final String DEFAULT_BUDDY_ICON_URL = "http://www.flickr.com/images/buddyicon.jpg"; private static final int IO_BUFFER_SIZE = 4 * 1024; private static final boolean FLAG_DECODE_PHOTO_STREAM_WITH_SKIA = false; private static final Flickr sInstance = new Flickr(); private HttpClient mClient; /** * Defines the size of the image to download from Flickr. * * @see com.google.android.photostream.Flickr.Photo */ enum PhotoSize { /** * Small square image (75x75 px). */ SMALL_SQUARE("_s", 75), /** * Thumbnail image (the longest side measures 100 px). */ THUMBNAIL("_t", 100), /** * Small image (the longest side measures 240 px). */ SMALL("_m", 240), /** * Medium image (the longest side measures 500 px). */ MEDIUM("", 500), /** * Large image (the longest side measures 1024 px). */ LARGE("_b", 1024); private final String mSize; private final int mLongSide; private PhotoSize(String size, int longSide) { mSize = size; mLongSide = longSide; } /** * Returns the size in pixels of the longest side of the image. * * @return THe dimension in pixels of the longest side. */ int longSide() { return mLongSide; } /** * Returns the name of the size, as defined by Flickr. For instance, * the LARGE size is defined by the String "_b". * * @return */ String size() { return mSize; } @Override public String toString() { return name() + ", longSide=" + mLongSide; } } /** * Represents the geographical location of a photo. */ static class Location { private float mLatitude; private float mLongitude; private Location(float latitude, float longitude) { mLatitude = latitude; mLongitude = longitude; } float getLatitude() { return mLatitude; } float getLongitude() { return mLongitude; } } /** * A Flickr user, in the strictest sense, is only defined by its NSID. The NSID * is usually obtained by {@link Flickr#findByUserName(String) * looking up a user by its user name}. * * To obtain more information about a given user, refer to the UserInfo class. * * @see Flickr#findByUserName(String) * @see Flickr#getUserInfo(com.google.android.photostream.Flickr.User) * @see com.google.android.photostream.Flickr.UserInfo */ static class User implements Parcelable { private final String mId; private User(String id) { mId = id; } private User(Parcel in) { mId = in.readString(); } /** * Returns the Flickr NSDID of the user. The NSID is used to identify the * user with any operation performed on Flickr. * * @return The user's NSID. */ String getId() { return mId; } /** * Creates a new instance of this class from the specified Flickr NSID. * * @param id The NSID of the Flickr user. * * @return An instance of User whose id might not be valid. */ static User fromId(String id) { return new User(id); } @Override public String toString() { return "User[" + mId + "]"; } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { dest.writeString(mId); } public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() { public User createFromParcel(Parcel in) { return new User(in); } public User[] newArray(int size) { return new User[size]; } }; } /** * A set of information for a given Flickr user. The information exposed include: * - The user's NSDID * - The user's name * - The user's real name * - The user's location * - The URL to the user's photos * - The URL to the user's profile * - The URL to the user's mobile web site * - Whether the user has a pro account */ static class UserInfo implements Parcelable { private String mId; private String mUserName; private String mRealName; private String mLocation; private String mPhotosUrl; private String mProfileUrl; private String mMobileUrl; private boolean mIsPro; private String mIconServer; private String mIconFarm; private UserInfo(String nsid) { mId = nsid; } private UserInfo(Parcel in) { mId = in.readString(); mUserName = in.readString(); mRealName = in.readString(); mLocation = in.readString(); mPhotosUrl = in.readString(); mProfileUrl = in.readString(); mMobileUrl = in.readString(); mIsPro = in.readInt() == 1; mIconServer = in.readString(); mIconFarm = in.readString(); } /** * Returns the Flickr NSID that identifies this user. * * @return The Flickr NSID. */ String getId() { return mId; } /** * Returns the user's name. This is the name that the user authenticates with, * and the name that Flickr uses in the URLs * (for instance, http://flickr.com/photos/romainguy, where romainguy is the user * name.) * * @return The user's Flickr name. */ String getUserName() { return mUserName; } /** * Returns the user's real name. The real name is chosen by the user when * creating his account and might not reflect his civil name. * * @return The real name of the user. */ String getRealName() { return mRealName; } /** * Returns the user's location, if publicly exposed. * * @return The location of the user. */ String getLocation() { return mLocation; } /** * Returns the URL to the photos of the user. For instance, * http://flickr.com/photos/romainguy. * * @return The URL to the photos of the user. */ String getPhotosUrl() { return mPhotosUrl; } /** * Returns the URL to the profile of the user. For instance, * http://flickr.com/people/romainguy/. * * @return The URL to the photos of the user. */ String getProfileUrl() { return mProfileUrl; } /** * Returns the mobile URL of the user. * * @return The mobile URL of the user. */ String getMobileUrl() { return mMobileUrl; } /** * Indicates whether the user owns a pro account. * * @return true, if the user has a pro account, false otherwise. */ boolean isPro() { return mIsPro; } /** * Returns the URL to the user's buddy icon. The buddy icon is a 48x48 * image chosen by the user. If no icon can be found, a default image * URL is returned. * * @return The URL to the user's buddy icon. */ String getBuddyIconUrl() { if (mIconFarm == null || mIconServer == null || mId == null) { return DEFAULT_BUDDY_ICON_URL; } return String.format(BUDDY_ICON_URL, mIconFarm, mIconServer, mId); } /** * Loads the user's buddy icon as a Bitmap. The user's buddy icon is loaded * from the URL returned by {@link #getBuddyIconUrl()}. The buddy icon is * not cached locally. * * @return A 48x48 bitmap if the icon was loaded successfully or null otherwise. */ Bitmap loadBuddyIcon() { Bitmap bitmap = null; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new URL(getBuddyIconUrl()).openStream(), IO_BUFFER_SIZE); if (FLAG_DECODE_PHOTO_STREAM_WITH_SKIA) { bitmap = BitmapFactory.decodeStream(in); } else { final ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE); copy(in, out); out.flush(); final byte[] data = dataStream.toByteArray(); bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); } } catch (IOException e) { android.util.Log.e(Flickr.LOG_TAG, "Could not load buddy icon: " + this, e); } finally { closeStream(in); closeStream(out); } return bitmap; } @Override public String toString() { return mRealName + " (" + mUserName + ", " + mId + ")"; } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { dest.writeString(mId); dest.writeString(mUserName); dest.writeString(mRealName); dest.writeString(mLocation); dest.writeString(mPhotosUrl); dest.writeString(mProfileUrl); dest.writeString(mMobileUrl); dest.writeInt(mIsPro ? 1 : 0); dest.writeString(mIconServer); dest.writeString(mIconFarm); } public static final Parcelable.Creator<UserInfo> CREATOR = new Parcelable.Creator<UserInfo>() { public UserInfo createFromParcel(Parcel in) { return new UserInfo(in); } public UserInfo[] newArray(int size) { return new UserInfo[size]; } }; } /** * A photo is represented by a title, the date at which it was taken and a URL. * The URL depends on the desired {@link com.google.android.photostream.Flickr.PhotoSize}. */ static class Photo implements Parcelable { private String mId; private String mSecret; private String mServer; private String mFarm; private String mTitle; private String mDate; private Photo() { } private Photo(Parcel in) { mId = in.readString(); mSecret = in.readString(); mServer = in.readString(); mFarm = in.readString(); mTitle = in.readString(); mDate = in.readString(); } /** * Returns the title of the photo, if specified. * * @return The title of the photo. The returned value can be empty or null. */ String getTitle() { return mTitle; } /** * Returns the date at which the photo was taken, formatted in the current locale * with the following pattern: MMMM d, yyyy. * * @return The title of the photo. The returned value can be empty or null. */ String getDate() { return mDate; } /** * Returns the URL to the photo for the specified size. * * @param photoSize The required size of the photo. * * @return A URL to the photo for the specified size. * * @see com.google.android.photostream.Flickr.PhotoSize */ String getUrl(PhotoSize photoSize) { return String.format(PHOTO_IMAGE_URL, mFarm, mServer, mId, mSecret, photoSize.size()); } /** * Loads a Bitmap representing the photo for the specified size. The Bitmap is loaded * from the URL returned by * {@link #getUrl(com.google.android.photostream.Flickr.PhotoSize)}. * * @param size The size of the photo to load. * * @return A Bitmap whose longest size is the same as the longest side of the * specified {@link com.google.android.photostream.Flickr.PhotoSize}, or null * if the photo could not be loaded. */ Bitmap loadPhotoBitmap(PhotoSize size) { Bitmap bitmap = null; InputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new URL(getUrl(size)).openStream(), IO_BUFFER_SIZE); if (FLAG_DECODE_PHOTO_STREAM_WITH_SKIA) { bitmap = BitmapFactory.decodeStream(in); } else { final ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE); copy(in, out); out.flush(); final byte[] data = dataStream.toByteArray(); bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); } } catch (IOException e) { android.util.Log.e(Flickr.LOG_TAG, "Could not load photo: " + this, e); } finally { closeStream(in); closeStream(out); } return bitmap; } @Override public String toString() { return mTitle + ", " + mDate + " @" + mId; } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { dest.writeString(mId); dest.writeString(mSecret); dest.writeString(mServer); dest.writeString(mFarm); dest.writeString(mTitle); dest.writeString(mDate); } public static final Parcelable.Creator<Photo> CREATOR = new Parcelable.Creator<Photo>() { public Photo createFromParcel(Parcel in) { return new Photo(in); } public Photo[] newArray(int size) { return new Photo[size]; } }; } /** * A list of {@link com.google.android.photostream.Flickr.Photo photos}. A list * represents a series of photo on a page from the user's photostream, a list is * therefore associated with a page index and a page count. The page index and the * page count both depend on the number of photos per page. */ static class PhotoList { private ArrayList<Photo> mPhotos; private int mPage; private int mPageCount; private void add(Photo photo) { mPhotos.add(photo); } /** * Returns the photo at the specified index in the current set. An * {@link ArrayIndexOutOfBoundsException} can be thrown if the index is * less than 0 or greater then or equals to {@link #getCount()}. * * @param index The index of the photo to retrieve from the list. * * @return A valid {@link com.google.android.photostream.Flickr.Photo}. */ public Photo get(int index) { return mPhotos.get(index); } /** * Returns the number of photos in the list. * * @return A positive integer, or 0 if the list is empty. */ public int getCount() { return mPhotos.size(); } /** * Returns the page index of the photos from this list. * * @return The index of the Flickr page that contains the photos of this list. */ public int getPage() { return mPage; } /** * Returns the total number of photo pages. * * @return A positive integer, or 0 if the photostream is empty. */ public int getPageCount() { return mPageCount; } } /** * Returns the unique instance of this class. * * @return The unique instance of this class. */ static Flickr get() { return sInstance; } private Flickr() { final HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); final SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); final ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry); mClient = new DefaultHttpClient(manager, params); } /** * Finds a user by its user name. This method will return an instance of * {@link com.google.android.photostream.Flickr.User} containing the user's * NSID, or null if the user could not be found. * * The returned User contains only the user's NSID. To retrieve more information * about the user, please refer to * {@link #getUserInfo(com.google.android.photostream.Flickr.User)} * * @param userName The name of the user to find. * * @return A User instance with a valid NSID, or null if the user cannot be found. * * @see #getUserInfo(com.google.android.photostream.Flickr.User) * @see com.google.android.photostream.Flickr.User * @see com.google.android.photostream.Flickr.UserInfo */ User findByUserName(String userName) { final Uri.Builder uri = buildGetMethod(API_PEOPLE_FIND_BY_USERNAME); uri.appendQueryParameter(PARAM_USERNAME, userName); final HttpGet get = new HttpGet(uri.build().toString()); final String[] userId = new String[1]; try { executeRequest(get, new ResponseHandler() { public void handleResponse(InputStream in) throws IOException { parseResponse(in, new ResponseParser() { public void parseResponse(XmlPullParser parser) throws XmlPullParserException, IOException { parseUser(parser, userId); } }); } }); if (userId[0] != null) { return new User(userId[0]); } } catch (IOException e) { android.util.Log.e(LOG_TAG, "Could not find the user with name: " + userName); } return null; } /** * Retrieves a public set of information about the specified user. The user can * either be {@link com.google.android.photostream.Flickr.User#fromId(String) created manually} * or {@link #findByUserName(String) obtained from a user name}. * * @param user The user, whose NSID is valid, to retrive public information for. * * @return An instance of {@link com.google.android.photostream.Flickr.UserInfo} or null * if the user could not be found. * * @see com.google.android.photostream.Flickr.UserInfo * @see com.google.android.photostream.Flickr.User * @see #findByUserName(String) */ UserInfo getUserInfo(User user) { final String nsid = user.getId(); final Uri.Builder uri = buildGetMethod(API_PEOPLE_GET_INFO); uri.appendQueryParameter(PARAM_USERID, nsid); final HttpGet get = new HttpGet(uri.build().toString()); try { final UserInfo info = new UserInfo(nsid); executeRequest(get, new ResponseHandler() { public void handleResponse(InputStream in) throws IOException { parseResponse(in, new ResponseParser() { public void parseResponse(XmlPullParser parser) throws XmlPullParserException, IOException { parseUserInfo(parser, info); } }); } }); return info; } catch (IOException e) { android.util.Log.e(LOG_TAG, "Could not find the user with id: " + nsid); } return null; } /** * Retrives a list of photos for the specified user. The list contains at most the * number of photos specified by <code>perPage</code>. The photos are retrieved * starting a the specified page index. For instance, if a user has 10 photos in * his photostream, calling getPublicPhotos(user, 5, 2) will return the last 5 photos * of the photo stream. * * The page index starts at 1, not 0. * * @param user The user to retrieve photos from. * @param perPage The maximum number of photos to retrieve. * @param page The index (starting at 1) of the page in the photostream. * * @return A list of at most perPage photos. * * @see com.google.android.photostream.Flickr.Photo * @see com.google.android.photostream.Flickr.PhotoList * @see #downloadPhoto(com.google.android.photostream.Flickr.Photo, * com.google.android.photostream.Flickr.PhotoSize, java.io.OutputStream) */ PhotoList getPublicPhotos(User user, int perPage, int page) { final Uri.Builder uri = buildGetMethod(API_PEOPLE_GET_PUBLIC_PHOTOS); uri.appendQueryParameter(PARAM_USERID, user.getId()); uri.appendQueryParameter(PARAM_PER_PAGE, String.valueOf(perPage)); uri.appendQueryParameter(PARAM_PAGE, String.valueOf(page)); uri.appendQueryParameter(PARAM_EXTRAS, VALUE_DEFAULT_EXTRAS); final HttpGet get = new HttpGet(uri.build().toString()); final PhotoList photos = new PhotoList(); try { executeRequest(get, new ResponseHandler() { public void handleResponse(InputStream in) throws IOException { parseResponse(in, new ResponseParser() { public void parseResponse(XmlPullParser parser) throws XmlPullParserException, IOException { parsePhotos(parser, photos); } }); } }); } catch (IOException e) { android.util.Log.e(LOG_TAG, "Could not find photos for user: " + user); } return photos; } /** * Retrieves the geographical location of the specified photo. If the photo * has no geodata associated with it, this method returns null. * * @param photo The photo to get the location of. * * @return The geo location of the photo, or null if the photo has no geodata * or the photo cannot be found. * * @see com.google.android.photostream.Flickr.Location */ Location getLocation(Flickr.Photo photo) { final Uri.Builder uri = buildGetMethod(API_PEOPLE_GET_LOCATION); uri.appendQueryParameter(PARAM_PHOTO_ID, photo.mId); final HttpGet get = new HttpGet(uri.build().toString()); final Location location = new Location(0.0f, 0.0f); try { executeRequest(get, new ResponseHandler() { public void handleResponse(InputStream in) throws IOException { parseResponse(in, new ResponseParser() { public void parseResponse(XmlPullParser parser) throws XmlPullParserException, IOException { parsePhotoLocation(parser, location); } }); } }); return location; } catch (IOException e) { android.util.Log.e(LOG_TAG, "Could not find location for photo: " + photo); } return null; } /** * Checks the specified user's feed to see if any updated occured after the * specified date. * * @param user The user whose feed must be checked. * @param reference The date after which to check for updates. * * @return True if any update occured after the reference date, false otherwise. */ boolean hasUpdates(User user, final Calendar reference) { final Uri.Builder uri = new Uri.Builder(); uri.path(API_FEED_URL); uri.appendQueryParameter(PARAM_FEED_ID, user.getId()); uri.appendQueryParameter(PARAM_FEED_FORMAT, VALUE_DEFAULT_FORMAT); final HttpGet get = new HttpGet(uri.build().toString()); final boolean[] updated = new boolean[1]; try { executeRequest(get, new ResponseHandler() { public void handleResponse(InputStream in) throws IOException { parseFeedResponse(in, new ResponseParser() { public void parseResponse(XmlPullParser parser) throws XmlPullParserException, IOException { updated[0] = parseUpdated(parser, reference); } }); } }); } catch (IOException e) { android.util.Log.e(LOG_TAG, "Could not find feed for user: " + user); } return updated[0]; } /** * Downloads the specified photo at the specified size in the specified destination. * * @param photo The photo to download. * @param size The size of the photo to download. * @param destination The output stream in which to write the downloaded photo. * * @throws IOException If any network exception occurs during the download. */ void downloadPhoto(Photo photo, PhotoSize size, OutputStream destination) throws IOException { final BufferedOutputStream out = new BufferedOutputStream(destination, IO_BUFFER_SIZE); final String url = photo.getUrl(size); final HttpGet get = new HttpGet(url); HttpEntity entity = null; try { final HttpResponse response = mClient.execute(get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { entity = response.getEntity(); entity.writeTo(out); out.flush(); } } finally { if (entity != null) { entity.consumeContent(); } } } private boolean parseUpdated(XmlPullParser parser, Calendar reference) throws IOException, XmlPullParserException { int type; String name; final int depth = parser.getDepth(); while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) { if (type != XmlPullParser.START_TAG) { continue; } name = parser.getName(); if (RESPONSE_TAG_UPDATED.equals(name)) { if (parser.next() == XmlPullParser.TEXT) { final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { final String text = parser.getText().replace('T', ' ').replace('Z', ' '); final Calendar calendar = new GregorianCalendar(); calendar.setTimeInMillis(format.parse(text).getTime()); return calendar.after(reference); } catch (ParseException e) { // Ignore } } } } return false; } private void parsePhotos(XmlPullParser parser, PhotoList photos) throws XmlPullParserException, IOException { int type; String name; SimpleDateFormat parseFormat = null; SimpleDateFormat outputFormat = null; final int depth = parser.getDepth(); while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) { if (type != XmlPullParser.START_TAG) { continue; } name = parser.getName(); if (RESPONSE_TAG_PHOTOS.equals(name)) { photos.mPage = Integer.parseInt(parser.getAttributeValue(null, RESPONSE_ATTR_PAGE)); photos.mPageCount = Integer.parseInt(parser.getAttributeValue(null, RESPONSE_ATTR_PAGES)); photos.mPhotos = new ArrayList<Photo>(); } else if (RESPONSE_TAG_PHOTO.equals(name)) { final Photo photo = new Photo(); photo.mId = parser.getAttributeValue(null, RESPONSE_ATTR_ID); photo.mSecret = parser.getAttributeValue(null, RESPONSE_ATTR_SECRET); photo.mServer = parser.getAttributeValue(null, RESPONSE_ATTR_SERVER); photo.mFarm = parser.getAttributeValue(null, RESPONSE_ATTR_FARM); photo.mTitle = parser.getAttributeValue(null, RESPONSE_ATTR_TITLE); photo.mDate = parser.getAttributeValue(null, RESPONSE_ATTR_DATE_TAKEN); if (parseFormat == null) { parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); outputFormat = new SimpleDateFormat("MMMM d, yyyy"); } try { photo.mDate = outputFormat.format(parseFormat.parse(photo.mDate)); } catch (ParseException e) { android.util.Log.w(LOG_TAG, "Could not parse photo date", e); } photos.add(photo); } } } private void parsePhotoLocation(XmlPullParser parser, Location location) throws XmlPullParserException, IOException { int type; String name; final int depth = parser.getDepth(); while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) { if (type != XmlPullParser.START_TAG) { continue; } name = parser.getName(); if (RESPONSE_TAG_LOCATION.equals(name)) { try { location.mLatitude = Float.parseFloat(parser.getAttributeValue(null, RESPONSE_ATTR_LATITUDE)); location.mLongitude = Float.parseFloat(parser.getAttributeValue(null, RESPONSE_ATTR_LONGITUDE)); } catch (NumberFormatException e) { throw new XmlPullParserException("Could not parse lat/lon", parser, e); } } } } private void parseUser(XmlPullParser parser, String[] userId) throws XmlPullParserException, IOException { int type; String name; final int depth = parser.getDepth(); while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) { if (type != XmlPullParser.START_TAG) { continue; } name = parser.getName(); if (RESPONSE_TAG_USER.equals(name)) { userId[0] = parser.getAttributeValue(null, RESPONSE_ATTR_NSID); } } } private void parseUserInfo(XmlPullParser parser, UserInfo info) throws XmlPullParserException, IOException { int type; String name; final int depth = parser.getDepth(); while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) { if (type != XmlPullParser.START_TAG) { continue; } name = parser.getName(); if (RESPONSE_TAG_PERSON.equals(name)) { info.mIsPro = "1".equals(parser.getAttributeValue(null, RESPONSE_ATTR_ISPRO)); info.mIconServer = parser.getAttributeValue(null, RESPONSE_ATTR_ICONSERVER); info.mIconFarm = parser.getAttributeValue(null, RESPONSE_ATTR_ICONFARM); } else if (RESPONSE_TAG_USERNAME.equals(name)) { if (parser.next() == XmlPullParser.TEXT) { info.mUserName = parser.getText(); } } else if (RESPONSE_TAG_REALNAME.equals(name)) { if (parser.next() == XmlPullParser.TEXT) { info.mRealName = parser.getText(); } } else if (RESPONSE_TAG_LOCATION.equals(name)) { if (parser.next() == XmlPullParser.TEXT) { info.mLocation = parser.getText(); } } else if (RESPONSE_TAG_PHOTOSURL.equals(name)) { if (parser.next() == XmlPullParser.TEXT) { info.mPhotosUrl = parser.getText(); } } else if (RESPONSE_TAG_PROFILEURL.equals(name)) { if (parser.next() == XmlPullParser.TEXT) { info.mProfileUrl = parser.getText(); } } else if (RESPONSE_TAG_MOBILEURL.equals(name)) { if (parser.next() == XmlPullParser.TEXT) { info.mMobileUrl = parser.getText(); } } } } /** * Parses a valid Flickr XML response from the specified input stream. When the Flickr * response contains the OK tag, the response is sent to the specified response parser. * * @param in The input stream containing the response sent by Flickr. * @param responseParser The parser to use when the response is valid. * * @throws IOException */ private void parseResponse(InputStream in, ResponseParser responseParser) throws IOException { final XmlPullParser parser = Xml.newPullParser(); try { parser.setInput(new InputStreamReader(in)); int type; while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { // Empty } if (type != XmlPullParser.START_TAG) { throw new InflateException(parser.getPositionDescription() + ": No start tag found!"); } String name = parser.getName(); if (RESPONSE_TAG_RSP.equals(name)) { final String value = parser.getAttributeValue(null, RESPONSE_ATTR_STAT); if (!RESPONSE_STATUS_OK.equals(value)) { throw new IOException("Wrong status: " + value); } } responseParser.parseResponse(parser); } catch (XmlPullParserException e) { final IOException ioe = new IOException("Could not parser the response"); ioe.initCause(e); throw ioe; } } /** * Parses a valid Flickr Atom feed response from the specified input stream. * * @param in The input stream containing the response sent by Flickr. * @param responseParser The parser to use when the response is valid. * * @throws IOException */ private void parseFeedResponse(InputStream in, ResponseParser responseParser) throws IOException { final XmlPullParser parser = Xml.newPullParser(); try { parser.setInput(new InputStreamReader(in)); int type; while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { // Empty } if (type != XmlPullParser.START_TAG) { throw new InflateException(parser.getPositionDescription() + ": No start tag found!"); } String name = parser.getName(); if (RESPONSE_TAG_FEED.equals(name)) { responseParser.parseResponse(parser); } else { throw new IOException("Wrong start tag: " + name); } } catch (XmlPullParserException e) { final IOException ioe = new IOException("Could not parser the response"); ioe.initCause(e); throw ioe; } } /** * Executes an HTTP request on Flickr's web service. If the response is ok, the content * is sent to the specified response handler. * * @param get The GET request to executed. * @param handler The handler which will parse the response. * * @throws IOException */ private void executeRequest(HttpGet get, ResponseHandler handler) throws IOException { HttpEntity entity = null; HttpHost host = new HttpHost(API_REST_HOST, 80, "http"); try { final HttpResponse response = mClient.execute(host, get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { entity = response.getEntity(); final InputStream in = entity.getContent(); handler.handleResponse(in); } } finally { if (entity != null) { entity.consumeContent(); } } } /** * Builds an HTTP GET request for the specified Flickr API method. The returned request * contains the web service path, the query parameter for the API KEY and the query * parameter for the specified method. * * @param method The Flickr API method to invoke. * * @return A Uri.Builder containing the GET path, the API key and the method already * encoded. */ private static Uri.Builder buildGetMethod(String method) { final Uri.Builder builder = new Uri.Builder(); builder.path(API_REST_URL).appendQueryParameter(PARAM_API_KEY, API_KEY); builder.appendQueryParameter(PARAM_METHOD, method); return builder; } /** * Copy the content of the input stream into the output stream, using a temporary * byte array buffer whose size is defined by {@link #IO_BUFFER_SIZE}. * * @param in The input stream to copy from. * @param out The output stream to copy to. * * @throws IOException If any error occurs during the copy. */ private static void copy(InputStream in, OutputStream out) throws IOException { byte[] b = new byte[IO_BUFFER_SIZE]; int read; while ((read = in.read(b)) != -1) { out.write(b, 0, read); } } /** * Closes the specified stream. * * @param stream The stream to close. */ private static void closeStream(Closeable stream) { if (stream != null) { try { stream.close(); } catch (IOException e) { android.util.Log.e(Flickr.LOG_TAG, "Could not close stream", e); } } } /** * Response handler used with * {@link Flickr#executeRequest(org.apache.http.client.methods.HttpGet, * com.google.android.photostream.Flickr.ResponseHandler)}. The handler is invoked when * a response is sent by the server. The response is made available as an input stream. */ private static interface ResponseHandler { /** * Processes the responses sent by the HTTP server following a GET request. * * @param in The stream containing the server's response. * * @throws IOException */ public void handleResponse(InputStream in) throws IOException; } /** * Response parser used with {@link Flickr#parseResponse(java.io.InputStream, * com.google.android.photostream.Flickr.ResponseParser)}. When Flickr returns a valid * response, this parser is invoked to process the XML response. */ private static interface ResponseParser { /** * Processes the XML response sent by the Flickr web service after a successful * request. * * @param parser The parser containing the XML responses. * * @throws XmlPullParserException * @throws IOException */ public void parseResponse(XmlPullParser parser) throws XmlPullParserException, IOException; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.photostream; import android.app.Service; import android.app.NotificationManager; import android.app.Notification; import android.app.PendingIntent; import android.app.AlarmManager; import android.os.IBinder; import android.os.SystemClock; import android.content.Intent; import android.content.Context; import android.content.ContentValues; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.database.Cursor; import android.net.Uri; import android.text.TextUtils; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; /** * CheckUpdateService checks every 24 hours if updates have been made to the photostreams * of the current contacts. This service simply polls an RSS feed and compares the * modification timestamp with the one stored in the database. */ public class CheckUpdateService extends Service { private static boolean DEBUG = false; // Check interval: every 24 hours private static long UPDATES_CHECK_INTERVAL = 24 * 60 * 60 * 1000; private CheckForUpdatesTask mTask; @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); (mTask = new CheckForUpdatesTask()).execute(); } @Override public void onDestroy() { super.onDestroy(); if (mTask != null && mTask.getStatus() == UserTask.Status.RUNNING) { mTask.cancel(true); } } public IBinder onBind(Intent intent) { return null; } static void schedule(Context context) { final Intent intent = new Intent(context, CheckUpdateService.class); final PendingIntent pending = PendingIntent.getService(context, 0, intent, 0); Calendar c = new GregorianCalendar(); c.add(Calendar.DAY_OF_YEAR, 1); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); final AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarm.cancel(pending); if (DEBUG) { alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 30 * 1000, pending); } else { alarm.setRepeating(AlarmManager.RTC, c.getTimeInMillis(), UPDATES_CHECK_INTERVAL, pending); } } private class CheckForUpdatesTask extends UserTask<Void, Object, Void> { private SharedPreferences mPreferences; private NotificationManager mManager; @Override public void onPreExecute() { mPreferences = getSharedPreferences(Preferences.NAME, MODE_PRIVATE); mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); } public Void doInBackground(Void... params) { final UserDatabase helper = new UserDatabase(CheckUpdateService.this); final SQLiteDatabase database = helper.getWritableDatabase(); Cursor cursor = null; try { cursor = database.query(UserDatabase.TABLE_USERS, new String[] { UserDatabase._ID, UserDatabase.COLUMN_NSID, UserDatabase.COLUMN_REALNAME, UserDatabase.COLUMN_LAST_UPDATE }, null, null, null, null, null); int idIndex = cursor.getColumnIndexOrThrow(UserDatabase._ID); int realNameIndex = cursor.getColumnIndexOrThrow(UserDatabase.COLUMN_REALNAME); int nsidIndex = cursor.getColumnIndexOrThrow(UserDatabase.COLUMN_NSID); int lastUpdateIndex = cursor.getColumnIndexOrThrow(UserDatabase.COLUMN_LAST_UPDATE); final Flickr flickr = Flickr.get(); final Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); final Calendar reference = Calendar.getInstance(); while (!isCancelled() && cursor.moveToNext()) { final String nsid = cursor.getString(nsidIndex); calendar.setTimeInMillis(cursor.getLong(lastUpdateIndex)); reference.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND)); if (flickr.hasUpdates(Flickr.User.fromId(nsid), reference)) { publishProgress(nsid, cursor.getString(realNameIndex), cursor.getInt(idIndex)); } } final ContentValues values = new ContentValues(); values.put(UserDatabase.COLUMN_LAST_UPDATE, System.currentTimeMillis()); database.update(UserDatabase.TABLE_USERS, values, null, null); } finally { if (cursor != null) cursor.close(); database.close(); } return null; } @Override public void onProgressUpdate(Object... values) { if (mPreferences.getBoolean(Preferences.KEY_ENABLE_NOTIFICATIONS, true)) { final Integer id = (Integer) values[2]; final Intent intent = new Intent(PhotostreamActivity.ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(PhotostreamActivity.EXTRA_NOTIFICATION, id); intent.putExtra(PhotostreamActivity.EXTRA_NSID, values[0].toString()); Notification notification = new Notification(R.drawable.stat_notify, getString(R.string.notification_new_photos, values[1]), System.currentTimeMillis()); notification.setLatestEventInfo(CheckUpdateService.this, getString(R.string.notification_title), getString(R.string.notification_contact_has_new_photos, values[1]), PendingIntent.getActivity(CheckUpdateService.this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)); if (mPreferences.getBoolean(Preferences.KEY_VIBRATE, false)) { notification.defaults |= Notification.DEFAULT_VIBRATE; } String ringtoneUri = mPreferences.getString(Preferences.KEY_RINGTONE, null); notification.sound = TextUtils.isEmpty(ringtoneUri) ? null : Uri.parse(ringtoneUri); mManager.notify(id, notification); } } @Override public void onPostExecute(Void aVoid) { stopSelf(); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.photostream; import android.view.ViewGroup; import android.view.View; import android.view.animation.GridLayoutAnimationController; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; /** * A GridLayout positions its children in a static grid, defined by a fixed number of rows * and columns. The size of the rows and columns is dynamically computed depending on the * size of the GridLayout itself. As a result, GridLayout children's layout parameters * are ignored. * * The number of rows and columns are specified in XML using the attributes android:numRows * and android:numColumns. * * The GridLayout cannot be used when its size is unspecified. * * @attr ref com.google.android.photostream.R.styleable#GridLayout_numColumns * @attr ref com.google.android.photostream.R.styleable#GridLayout_numRows */ public class GridLayout extends ViewGroup { private int mNumColumns; private int mNumRows; private int mColumnWidth; private int mRowHeight; public GridLayout(Context context) { this(context, null); } public GridLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public GridLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.GridLayout, defStyle, 0); mNumColumns = a.getInt(R.styleable.GridLayout_numColumns, 1); mNumRows = a.getInt(R.styleable.GridLayout_numRows, 1); a.recycle(); } @Override protected void attachLayoutAnimationParameters(View child, ViewGroup.LayoutParams params, int index, int count) { GridLayoutAnimationController.AnimationParameters animationParams = (GridLayoutAnimationController.AnimationParameters) params.layoutAnimationParameters; if (animationParams == null) { animationParams = new GridLayoutAnimationController.AnimationParameters(); params.layoutAnimationParameters = animationParams; } animationParams.count = count; animationParams.index = index; animationParams.columnsCount = mNumColumns; animationParams.rowsCount = mNumRows; animationParams.column = index % mNumColumns; animationParams.row = index / mNumColumns; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); final int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); final int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); final int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) { throw new RuntimeException("GridLayout cannot have UNSPECIFIED dimensions"); } final int width = widthSpecSize - getPaddingLeft() - getPaddingRight(); final int height = heightSpecSize - getPaddingTop() - getPaddingBottom(); final int columnWidth = mColumnWidth = width / mNumColumns; final int rowHeight = mRowHeight = height / mNumRows; final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); int childWidthSpec = MeasureSpec.makeMeasureSpec(columnWidth, MeasureSpec.EXACTLY); int childheightSpec = MeasureSpec.makeMeasureSpec(rowHeight, MeasureSpec.EXACTLY); child.measure(childWidthSpec, childheightSpec); } setMeasuredDimension(widthSpecSize, heightSpecSize); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int columns = mNumColumns; final int paddingLeft = getPaddingLeft(); final int paddingTop = getPaddingTop(); final int columnWidth = mColumnWidth; final int rowHeight = mRowHeight; final int count = getChildCount(); for (int i = 0; i < count; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { final int column = i % columns; final int row = i / columns; int childLeft = paddingLeft + column * columnWidth; int childTop = paddingTop + row * rowHeight; child.layout(childLeft, childTop, childLeft + child.getMeasuredWidth(), childTop + child.getMeasuredHeight()); } } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.photostream; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.content.ActivityNotFoundException; import android.content.pm.ResolveInfo; import android.content.ComponentName; import android.content.DialogInterface; import android.os.Bundle; import android.widget.TextView; import android.widget.ImageView; import android.widget.ViewAnimator; import android.widget.LinearLayout; import android.widget.Toast; import android.widget.ArrayAdapter; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.graphics.drawable.BitmapDrawable; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.Menu; import android.view.MenuItem; import android.view.animation.AnimationUtils; import android.view.LayoutInflater; import android.net.Uri; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.InputStream; import java.io.FileNotFoundException; import java.util.List; import java.util.ArrayList; /** * Activity that displays a photo along with its title and the date at which it was taken. * This activity also lets the user set the photo as the wallpaper. */ public class ViewPhotoActivity extends Activity implements View.OnClickListener, ViewTreeObserver.OnGlobalLayoutListener { static final String ACTION = "com.google.android.photostream.FLICKR_PHOTO"; private static final String RADAR_ACTION = "com.google.android.radar.SHOW_RADAR"; private static final String RADAR_EXTRA_LATITUDE = "latitude"; private static final String RADAR_EXTRA_LONGITUDE = "longitude"; private static final String EXTRA_PHOTO = "com.google.android.photostream.photo"; private static final String WALLPAPER_FILE_NAME = "wallpaper"; private static final int REQUEST_CROP_IMAGE = 42; private Flickr.Photo mPhoto; private ViewAnimator mSwitcher; private ImageView mPhotoView; private ViewGroup mContainer; private UserTask<?, ?, ?> mTask; private TextView mPhotoTitle; private TextView mPhotoDate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPhoto = getPhoto(); setContentView(R.layout.screen_photo); setupViews(); } /** * Starts the ViewPhotoActivity for the specified photo. * * @param context The application's environment. * @param photo The photo to display and optionally set as a wallpaper. */ static void show(Context context, Flickr.Photo photo) { final Intent intent = new Intent(ACTION); intent.putExtra(EXTRA_PHOTO, photo); context.startActivity(intent); } @Override protected void onDestroy() { super.onDestroy(); if (mTask != null && mTask.getStatus() != UserTask.Status.RUNNING) { mTask.cancel(true); } } private void setupViews() { mContainer = (ViewGroup) findViewById(R.id.container_photo); mSwitcher = (ViewAnimator) findViewById(R.id.switcher_menu); mPhotoView = (ImageView) findViewById(R.id.image_photo); mPhotoTitle = (TextView) findViewById(R.id.caption_title); mPhotoDate = (TextView) findViewById(R.id.caption_date); findViewById(R.id.menu_back).setOnClickListener(this); findViewById(R.id.menu_set).setOnClickListener(this); mPhotoTitle.setText(mPhoto.getTitle()); mPhotoDate.setText(mPhoto.getDate()); mContainer.setVisibility(View.INVISIBLE); // Sets up a view tree observer. The photo will be scaled using the size // of one of our views so we must wait for the first layout pass to be // done to make sure we have the correct size. mContainer.getViewTreeObserver().addOnGlobalLayoutListener(this); } /** * Loads the photo after the first layout. The photo is scaled using the * dimension of the ImageView that will ultimately contain the photo's * bitmap. We make sure that the ImageView is laid out at least once to * get its correct size. */ public void onGlobalLayout() { mContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this); loadPhoto(mPhotoView.getMeasuredWidth(), mPhotoView.getMeasuredHeight()); } /** * Loads the photo either from the last known instance or from the network. * Loading it from the last known instance allows for fast display rotation * without having to download the photo from the network again. * * @param width The desired maximum width of the photo. * @param height The desired maximum height of the photo. */ private void loadPhoto(int width, int height) { final Object data = getLastNonConfigurationInstance(); if (data == null) { mTask = new LoadPhotoTask().execute(mPhoto, width, height); } else { mPhotoView.setImageBitmap((Bitmap) data); mSwitcher.showNext(); } } /** * Loads the {@link com.google.android.photostream.Flickr.Photo} to display * from the intent used to start the activity. * * @return The photo to display, or null if the photo cannot be found. */ public Flickr.Photo getPhoto() { final Intent intent = getIntent(); final Bundle extras = intent.getExtras(); Flickr.Photo photo = null; if (extras != null) { photo = extras.getParcelable(EXTRA_PHOTO); } return photo; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.view_photo, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case R.id.menu_item_radar: onShowRadar(); break; } return super.onMenuItemSelected(featureId, item); } private void onShowRadar() { new ShowRadarTask().execute(mPhoto); } public void onClick(View v) { switch (v.getId()) { case R.id.menu_back: onBack(); break; case R.id.menu_set: onSet(); break; } } private void onSet() { mTask = new CropWallpaperTask().execute(mPhoto); } private void onBack() { finish(); } /** * If we successfully loaded a photo, send it to our future self to allow * for fast display rotation. By doing so, we avoid reloading the photo * from the network when the activity is taken down and recreated upon * display rotation. * * @return The Bitmap displayed in the ImageView, or null if the photo * wasn't loaded. */ @Override public Object onRetainNonConfigurationInstance() { final Drawable d = mPhotoView.getDrawable(); return d != null ? ((BitmapDrawable) d).getBitmap() : null; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Spawns a new task to set the wallpaper in a background thread when/if // we receive a successful result from the image cropper. if (requestCode == REQUEST_CROP_IMAGE) { if (resultCode == RESULT_OK) { mTask = new SetWallpaperTask().execute(); } else { cleanupWallpaper(); showWallpaperError(); } } } private void showWallpaperError() { Toast.makeText(ViewPhotoActivity.this, R.string.error_cannot_save_file, Toast.LENGTH_SHORT).show(); } private void showWallpaperSuccess() { Toast.makeText(ViewPhotoActivity.this, R.string.success_wallpaper_set, Toast.LENGTH_SHORT).show(); } private void cleanupWallpaper() { deleteFile(WALLPAPER_FILE_NAME); mSwitcher.showNext(); } /** * Background task to load the photo from Flickr. The task loads the bitmap, * then scale it to the appropriate dimension. The task ends by readjusting * the activity's layout so that everything aligns correctly. */ private class LoadPhotoTask extends UserTask<Object, Void, Bitmap> { public Bitmap doInBackground(Object... params) { Bitmap bitmap = ((Flickr.Photo) params[0]).loadPhotoBitmap(Flickr.PhotoSize.MEDIUM); if (bitmap == null) { bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.not_found); } final int width = (Integer) params[1]; final int height = (Integer) params[2]; final Bitmap framed = ImageUtilities.scaleAndFrame(bitmap, width, height); bitmap.recycle(); return framed; } @Override public void onPostExecute(Bitmap result) { mPhotoView.setImageBitmap(result); // Find by how many pixels the title and date must be shifted on the // horizontal axis to be left aligned with the photo final int offsetX = (mPhotoView.getMeasuredWidth() - result.getWidth()) / 2; // Forces the ImageView to have the same size as its embedded bitmap // This will remove the empty space between the title/date pair and // the photo itself LinearLayout.LayoutParams params; params = (LinearLayout.LayoutParams) mPhotoView.getLayoutParams(); params.height = result.getHeight(); params.weight = 0.0f; mPhotoView.setLayoutParams(params); params = (LinearLayout.LayoutParams) mPhotoTitle.getLayoutParams(); params.leftMargin = offsetX; mPhotoTitle.setLayoutParams(params); params = (LinearLayout.LayoutParams) mPhotoDate.getLayoutParams(); params.leftMargin = offsetX; mPhotoDate.setLayoutParams(params); mSwitcher.showNext(); mContainer.startAnimation(AnimationUtils.loadAnimation(ViewPhotoActivity.this, R.anim.fade_in)); mContainer.setVisibility(View.VISIBLE); mTask = null; } } /** * Background task to crop a large version of the image. The cropped result will * be set as a wallpaper. The tasks sarts by showing the progress bar, then * downloads the large version of hthe photo into a temporary file and ends by * sending an intent to the Camera application to crop the image. */ private class CropWallpaperTask extends UserTask<Flickr.Photo, Void, Boolean> { private File mFile; private Uri _captureUri; private boolean startCrop; // this is something to keep our information class CropOption { CharSequence TITLE; Drawable ICON; Intent CROP_APP; } // we will present the available selection in a list dialog, so we need an adapter class CropOptionAdapter extends ArrayAdapter<CropOption> { private List<CropOption> _items; private Context _ctx; CropOptionAdapter(Context ctx, List<CropOption> items) { super(ctx, R.layout.crop_option, items); _items = items; _ctx = ctx; } @Override public View getView( int position, View convertView, ViewGroup parent ) { if ( convertView == null ) convertView = LayoutInflater.from( _ctx ).inflate( R.layout.crop_option, null ); CropOption item = _items.get( position ); if ( item != null ) { ( ( ImageView ) convertView.findViewById( R.id.crop_icon ) ).setImageDrawable( item.ICON ); ( ( TextView ) convertView.findViewById( R.id.crop_name ) ).setText( item.TITLE ); return convertView; } return null; } } @Override public void onPreExecute() { mFile = getFileStreamPath(WALLPAPER_FILE_NAME); mSwitcher.showNext(); } public Boolean doInBackground(Flickr.Photo... params) { boolean success = false; OutputStream out = null; try { out = openFileOutput(mFile.getName(), MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE); Flickr.get().downloadPhoto(params[0], Flickr.PhotoSize.LARGE, out); success = true; } catch (FileNotFoundException e) { android.util.Log.e(Flickr.LOG_TAG, "Could not download photo", e); success = false; } catch (IOException e) { android.util.Log.e(Flickr.LOG_TAG, "Could not download photo", e); success = false; } finally { if (out != null) { try { out.close(); } catch (IOException e) { success = false; } } } return success; } @Override public void onPostExecute(Boolean result) { if (!result) { cleanupWallpaper(); showWallpaperError(); } else { final int width = getWallpaperDesiredMinimumWidth(); final int height = getWallpaperDesiredMinimumHeight(); // Initilize the default _captureUri = Uri.fromFile(mFile); startCrop = false; try { final List<CropOption> cropOptions = new ArrayList<CropOption>(); // this 2 lines are all you need to find the intent!!! Intent intent = new Intent( "com.android.camera.action.CROP" ); intent.setType( "image/*" ); List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 ); if ( list.size() == 0 ) { // I tend to put any kind of text to be presented to the user as a resource for easier translation (if it ever comes to that...) Toast.makeText(ViewPhotoActivity.this, getText( R.string.error_crop_option ), Toast.LENGTH_LONG ).show(); // this is the URI returned from the camera, it could be a file or a content URI, the crop app will take any _captureUri = null; // leave the picture there } else { intent.setData( _captureUri ); intent.putExtra("outputX", width); intent.putExtra("outputY", height); intent.putExtra("aspectX", width); intent.putExtra("aspectY", height); intent.putExtra("scale", true); intent.putExtra("noFaceDetection", true); intent.putExtra("output", Uri.parse("file:/" + mFile.getAbsolutePath())); //intent.putExtra( "", true ); // I seem to have lost the option to have the crop app auto rotate the image, any takers? intent.putExtra( "return-data", false ); for ( ResolveInfo res : list ) { final CropOption co = new CropOption(); co.TITLE = getPackageManager().getApplicationLabel( res.activityInfo.applicationInfo ); co.ICON = getPackageManager().getApplicationIcon( res.activityInfo.applicationInfo ); co.CROP_APP = new Intent( intent ); co.CROP_APP.setComponent( new ComponentName( res.activityInfo.packageName, res.activityInfo.name ) ); cropOptions.add( co ); } // set up the chooser dialog CropOptionAdapter adapter = new CropOptionAdapter( ViewPhotoActivity.this, cropOptions ); AlertDialog.Builder builder = new AlertDialog.Builder( ViewPhotoActivity.this ); builder.setTitle( R.string.choose_crop_title ); builder.setAdapter( adapter, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int item ) { startCrop = true; startActivityForResult( cropOptions.get( item ).CROP_APP, REQUEST_CROP_IMAGE); } } ); builder.setOnCancelListener( new DialogInterface.OnCancelListener() { @Override public void onCancel( DialogInterface dialog ) { if (startCrop == true) { // we don't want to keep the capture around if we cancel the crop because // we don't want it anymore if ( _captureUri != null) { getContentResolver().delete( _captureUri, null, null ); _captureUri = null; } } else { // User canceled the selection of a Crop Application cleanupWallpaper(); showWallpaperError(); } } } ); AlertDialog alert = builder.create(); alert.show(); } } catch ( Exception e ) { android.util.Log.e(Flickr.LOG_TAG, "processing capture", e ); } } mTask = null; } } /** * Background task to set the cropped image as the wallpaper. The task simply * open the temporary file and sets it as the new wallpaper. The task ends by * deleting the temporary file and display a message to the user. */ private class SetWallpaperTask extends UserTask<Void, Void, Boolean> { public Boolean doInBackground(Void... params) { boolean success = false; InputStream in = null; try { in = openFileInput(WALLPAPER_FILE_NAME); setWallpaper(in); success = true; } catch (IOException e) { success = false; } finally { if (in != null) { try { in.close(); } catch (IOException e) { success = false; } } } return success; } @Override public void onPostExecute(Boolean result) { cleanupWallpaper(); if (!result) { showWallpaperError(); } else { showWallpaperSuccess(); } mTask = null; } } private class ShowRadarTask extends UserTask<Flickr.Photo, Void, Flickr.Location> { public Flickr.Location doInBackground(Flickr.Photo... params) { return Flickr.get().getLocation(params[0]); } @Override public void onPostExecute(Flickr.Location location) { if (location != null) { final Intent intent = new Intent(RADAR_ACTION); intent.putExtra(RADAR_EXTRA_LATITUDE, location.getLatitude()); intent.putExtra(RADAR_EXTRA_LONGITUDE, location.getLongitude()); try { startActivity(intent); } catch (ActivityNotFoundException e) { Toast.makeText(ViewPhotoActivity.this, R.string.error_cannot_find_radar, Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(ViewPhotoActivity.this, R.string.error_cannot_find_location, Toast.LENGTH_SHORT).show(); } } } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.photostream; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.SharedPreferences; import java.io.IOException; import java.io.BufferedReader; import java.io.Closeable; import java.io.InputStreamReader; /** * Displays an EULA ("End User License Agreement") that the user has to accept before * using the application. Your application should call {@link Eula#showEula(android.app.Activity)} * in the onCreate() method of the first activity. If the user accepts the EULA, it will never * be shown again. If the user refuses, {@link android.app.Activity#finish()} is invoked * on your activity. */ class Eula { private static final String PREFERENCE_EULA_ACCEPTED = "eula.accepted"; private static final String PREFERENCES_EULA = "eula"; /** * Displays the EULA if necessary. This method should be called from the onCreate() * method of your main Activity. * * @param activity The Activity to finish if the user rejects the EULA. */ static void showEula(final Activity activity) { final SharedPreferences preferences = activity.getSharedPreferences(PREFERENCES_EULA, Activity.MODE_PRIVATE); if (!preferences.getBoolean(PREFERENCE_EULA_ACCEPTED, false)) { final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.eula_title); builder.setCancelable(true); builder.setPositiveButton(R.string.eula_accept, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { accept(preferences); } }); builder.setNegativeButton(R.string.eula_refuse, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { refuse(activity); } }); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { refuse(activity); } }); // UNCOMMENT TO ENABLE EULA //builder.setMessage(readFile(activity, R.raw.eula)); builder.create().show(); } } private static void accept(SharedPreferences preferences) { preferences.edit().putBoolean(PREFERENCE_EULA_ACCEPTED, true).commit(); } private static void refuse(Activity activity) { activity.finish(); } static void showDisclaimer(Activity activity) { final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setMessage(readFile(activity, R.raw.disclaimer)); builder.setCancelable(true); builder.setTitle(R.string.disclaimer_title); builder.setPositiveButton(R.string.disclaimer_accept, null); builder.create().show(); } private static CharSequence readFile(Activity activity, int id) { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader( activity.getResources().openRawResource(id))); String line; StringBuilder buffer = new StringBuilder(); while ((line = in.readLine()) != null) buffer.append(line).append('\n'); return buffer; } catch (IOException e) { return ""; } finally { closeStream(in); } } /** * Closes the specified stream. * * @param stream The stream to close. */ private static void closeStream(Closeable stream) { if (stream != null) { try { stream.close(); } catch (IOException e) { // Ignore } } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.photostream; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import java.util.Random; /** * This class contains various utilities to manipulate Bitmaps. The methods of this class, * although static, are not thread safe and cannot be invoked by several threads at the * same time. Synchronization is required by the caller. */ final class ImageUtilities { private static final float PHOTO_BORDER_WIDTH = 3.0f; private static final int PHOTO_BORDER_COLOR = 0xffffffff; private static final float ROTATION_ANGLE_MIN = 2.5f; private static final float ROTATION_ANGLE_EXTRA = 5.5f; private static final Random sRandom = new Random(); private static final Paint sPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); private static final Paint sStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG); static { sStrokePaint.setStrokeWidth(PHOTO_BORDER_WIDTH); sStrokePaint.setStyle(Paint.Style.STROKE); sStrokePaint.setColor(PHOTO_BORDER_COLOR); } /** * Rotate specified Bitmap by a random angle. The angle is either negative or positive, * and ranges, in degrees, from 2.5 to 8. After rotation a frame is overlaid on top * of the rotated image. * * This method is not thread safe. * * @param bitmap The Bitmap to rotate and apply a frame onto. * * @return A new Bitmap whose dimension are different from the original bitmap. */ static Bitmap rotateAndFrame(Bitmap bitmap) { final boolean positive = sRandom.nextFloat() >= 0.5f; final float angle = (ROTATION_ANGLE_MIN + sRandom.nextFloat() * ROTATION_ANGLE_EXTRA) * (positive ? 1.0f : -1.0f); final double radAngle = Math.toRadians(angle); final int bitmapWidth = bitmap.getWidth(); final int bitmapHeight = bitmap.getHeight(); final double cosAngle = Math.abs(Math.cos(radAngle)); final double sinAngle = Math.abs(Math.sin(radAngle)); final int strokedWidth = (int) (bitmapWidth + 2 * PHOTO_BORDER_WIDTH); final int strokedHeight = (int) (bitmapHeight + 2 * PHOTO_BORDER_WIDTH); final int width = (int) (strokedHeight * sinAngle + strokedWidth * cosAngle); final int height = (int) (strokedWidth * sinAngle + strokedHeight * cosAngle); final float x = (width - bitmapWidth) / 2.0f; final float y = (height - bitmapHeight) / 2.0f; final Bitmap decored = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); final Canvas canvas = new Canvas(decored); canvas.rotate(angle, width / 2.0f, height / 2.0f); canvas.drawBitmap(bitmap, x, y, sPaint); canvas.drawRect(x, y, x + bitmapWidth, y + bitmapHeight, sStrokePaint); return decored; } /** * Scales the specified Bitmap to fit within the specified dimensions. After scaling, * a frame is overlaid on top of the scaled image. * * This method is not thread safe. * * @param bitmap The Bitmap to scale to fit the specified dimensions and to apply * a frame onto. * @param width The maximum width of the new Bitmap. * @param height The maximum height of the new Bitmap. * * @return A scaled version of the original bitmap, whose dimension are less than or * equal to the specified width and height. */ static Bitmap scaleAndFrame(Bitmap bitmap, int width, int height) { final int bitmapWidth = bitmap.getWidth(); final int bitmapHeight = bitmap.getHeight(); final float scale = Math.min((float) width / (float) bitmapWidth, (float) height / (float) bitmapHeight); final int scaledWidth = (int) (bitmapWidth * scale); final int scaledHeight = (int) (bitmapHeight * scale); final Bitmap decored = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true); final Canvas canvas = new Canvas(decored); final int offset = (int) (PHOTO_BORDER_WIDTH / 2); sStrokePaint.setAntiAlias(false); canvas.drawRect(offset, offset, scaledWidth - offset - 1, scaledHeight - offset - 1, sStrokePaint); sStrokePaint.setAntiAlias(true); return decored; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.photostream; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; /** * This broadcast receiver is awoken after boot and registers the service that * checks for new photos from all the known contacts. */ public class BootReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { CheckUpdateService.schedule(context); } } }
Java
/* * Copyright (C) 2008 Jason Tomlinson. * * 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.example.amazed; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.Log; /** * Maze drawn on screen, each new level is loaded once the previous level has * been completed. */ public class Maze { // maze tile size and dimension private final static int TILE_SIZE = 16; private final static int MAZE_COLS = 20; private final static int MAZE_ROWS = 26; // tile types public final static int PATH_TILE = 0; public final static int VOID_TILE = 1; public final static int EXIT_TILE = 2; // tile colors private final static int VOID_COLOR = Color.BLACK; // maze level data private static int[] mMazeData; // number of level public final static int MAX_LEVELS = 10; // current tile attributes private Rect mRect = new Rect(); private int mRow; private int mCol; private int mX; private int mY; // tile bitmaps private Bitmap mImgPath; private Bitmap mImgExit; /** * Maze constructor. * * @param context * Application context used to load images. */ Maze(Activity activity) { // load bitmaps. mImgPath = BitmapFactory.decodeResource(activity.getApplicationContext().getResources(), R.drawable.path); mImgExit = BitmapFactory.decodeResource(activity.getApplicationContext().getResources(), R.drawable.exit); } /** * Load specified maze level. * * @param activity * Activity controlled the maze, we use this load the level data * @param newLevel * Maze level to be loaded. */ void load(Activity activity, int newLevel) { // maze data is stored in the assets folder as level1.txt, level2.txt // etc.... String mLevel = "level" + newLevel + ".txt"; InputStream is = null; try { // construct our maze data array. mMazeData = new int[MAZE_ROWS * MAZE_COLS]; // attempt to load maze data. is = activity.getAssets().open(mLevel); // we need to loop through the input stream and load each tile for // the current maze. for (int i = 0; i < mMazeData.length; i++) { // data is stored in unicode so we need to convert it. mMazeData[i] = Character.getNumericValue(is.read()); // skip the "," and white space in our human readable file. is.read(); is.read(); } } catch (Exception e) { Log.i("Maze", "load exception: " + e); } finally { closeStream(is); } } /** * Draw the maze. * * @param canvas * Canvas object to draw too. * @param paint * Paint object used to draw with. */ public void draw(Canvas canvas, Paint paint) { // loop through our maze and draw each tile individually. for (int i = 0; i < mMazeData.length; i++) { // calculate the row and column of the current tile. mRow = i / MAZE_COLS; mCol = i % MAZE_COLS; // convert the row and column into actual x,y co-ordinates so we can // draw it on screen. mX = mCol * TILE_SIZE; mY = mRow * TILE_SIZE; // draw the actual tile based on type. if (mMazeData[i] == PATH_TILE) canvas.drawBitmap(mImgPath, mX, mY, paint); else if (mMazeData[i] == EXIT_TILE) canvas.drawBitmap(mImgExit, mX, mY, paint); else if (mMazeData[i] == VOID_TILE) { // since our "void" tile is purely black lets draw a rectangle // instead of using an image. // tile attributes we are going to paint. mRect.left = mX; mRect.top = mY; mRect.right = mX + TILE_SIZE; mRect.bottom = mY + TILE_SIZE; paint.setColor(VOID_COLOR); canvas.drawRect(mRect, paint); } } } /** * Determine which cell the marble currently occupies. * * @param x * Current x co-ordinate. * @param y * Current y co-ordinate. * @return The actual cell occupied by the marble. */ public int getCellType(int x, int y) { // convert the x,y co-ordinate into row and col values. int mCellCol = x / TILE_SIZE; int mCellRow = y / TILE_SIZE; // location is the row,col coordinate converted so we know where in the // maze array to look. int mLocation = 0; // if we are beyond the 1st row need to multiple by the number of // columns. if (mCellRow > 0) mLocation = mCellRow * MAZE_COLS; // add the column location. mLocation += mCellCol; return mMazeData[mLocation]; } /** * Closes the specified stream. * * @param stream * The stream to close. */ private static void closeStream(Closeable stream) { if (stream != null) { try { stream.close(); } catch (IOException e) { // Ignore } } } }
Java
/* * Copyright (C) 2008 Jason Tomlinson. * * 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.example.amazed; import android.app.Activity; import android.os.Bundle; import android.view.Window; /** * Activity responsible for controlling the application. */ public class AmazedActivity extends Activity { // custom view private AmazedView mView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // remove title bar. requestWindowFeature(Window.FEATURE_NO_TITLE); // setup our view, give it focus and display. mView = new AmazedView(getApplicationContext(), this); mView.setFocusable(true); setContentView(mView); } @Override protected void onResume() { super.onResume(); mView.registerListener(); } @Override public void onSaveInstanceState(Bundle icicle) { super.onSaveInstanceState(icicle); mView.unregisterListener(); } }
Java
/* * Copyright (C) 2008 Jason Tomlinson. * * 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.example.amazed; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.View; /** * Marble drawn in the maze. */ public class Marble { // View controlling the marble. private View mView; // marble attributes // x,y are private because we need boundary checking on any new values to // make sure they are valid. private int mX = 0; private int mY = 0; private int mRadius = 8; private int mColor = Color.WHITE; private int mLives = 5; /** * Marble constructor. * * @param view * View controlling the marble */ public Marble(View view) { this.mView = view; init(); } /** * Setup marble starting co-ords. */ public void init() { mX = mRadius * 6; mY = mRadius * 6; } /** * Draw the marble. * * @param canvas * Canvas object to draw too. * @param paint * Paint object used to draw with. */ public void draw(Canvas canvas, Paint paint) { paint.setColor(mColor); canvas.drawCircle(mX, mY, mRadius, paint); } /** * Attempt to update the marble with a new x value, boundary checking * enabled to make sure the new co-ordinate is valid. * * @param newX * Incremental value to add onto current x co-ordinate. */ public void updateX(float newX) { mX += newX; // boundary checking, don't want the marble rolling off-screen. if (mX + mRadius >= mView.getWidth()) mX = mView.getWidth() - mRadius; else if (mX - mRadius < 0) mX = mRadius; } /** * Attempt to update the marble with a new y value, boundary checking * enabled to make sure the new co-ordinate is valid. * * @param newY * Incremental value to add onto current y co-ordinate. */ public void updateY(float newY) { mY -= newY; // boundary checking, don't want the marble rolling off-screen. if (mY + mRadius >= mView.getHeight()) mY = mView.getHeight() - mRadius; else if (mY - mRadius < 0) mY = mRadius; } /** * Marble has died */ public void death() { mLives--; } /** * Set the number of lives for the marble * * @param Number * of lives */ public void setLives(int val) { mLives = val; } /** * @return Number of lives left */ public int getLives() { return mLives; } /** * @return Current x co-ordinate. */ public int getX() { return mX; } /** * @return Current y co-ordinate. */ public int getY() { return mY; } }
Java
/* * Copyright (C) 2008 Jason Tomlinson. * * 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.example.amazed; import android.app.Activity; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.hardware.SensorListener; import android.hardware.SensorManager; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; /** * Custom view used to draw the maze and marble. Responds to accelerometer * updates to roll the marble around the screen. */ public class AmazedView extends View { // Game objects private Marble mMarble; private Maze mMaze; private Activity mActivity; // canvas we paint to. private Canvas mCanvas; private Paint mPaint; private Typeface mFont = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD); private int mTextPadding = 10; private int mHudTextY = 440; // game states private final static int NULL_STATE = -1; private final static int GAME_INIT = 0; private final static int GAME_RUNNING = 1; private final static int GAME_OVER = 2; private final static int GAME_COMPLETE = 3; private final static int GAME_LANDSCAPE = 4; // current state of the game private static int mCurState = NULL_STATE; // game strings private final static int TXT_LIVES = 0; private final static int TXT_LEVEL = 1; private final static int TXT_TIME = 2; private final static int TXT_TAP_SCREEN = 3; private final static int TXT_GAME_COMPLETE = 4; private final static int TXT_GAME_OVER = 5; private final static int TXT_TOTAL_TIME = 6; private final static int TXT_GAME_OVER_MSG_A = 7; private final static int TXT_GAME_OVER_MSG_B = 8; private final static int TXT_RESTART = 9; private final static int TXT_LANDSCAPE_MODE = 10; private static String mStrings[]; // this prevents the user from dying instantly when they start a level if // the device is tilted. private boolean mWarning = false; // screen dimensions private int mCanvasWidth = 0; private int mCanvasHeight = 0; private int mCanvasHalfWidth = 0; private int mCanvasHalfHeight = 0; // are we running in portrait mode. private boolean mPortrait; // current level private int mlevel = 1; // timing used for scoring. private long mTotalTime = 0; private long mStartTime = 0; private long mEndTime = 0; // sensor manager used to control the accelerometer sensor. private SensorManager mSensorManager; // accelerometer sensor values. private float mAccelX = 0; private float mAccelY = 0; private float mAccelZ = 0; // this is never used but just in-case future // versions make use of it. // accelerometer buffer, currently set to 0 so even the slightest movement // will roll the marble. private float mSensorBuffer = 0; // http://code.google.com/android/reference/android/hardware/SensorManager.html#SENSOR_ACCELEROMETER // for an explanation on the values reported by SENSOR_ACCELEROMETER. private final SensorListener mSensorAccelerometer = new SensorListener() { // method called whenever new sensor values are reported. public void onSensorChanged(int sensor, float[] values) { // grab the values required to respond to user movement. mAccelX = values[0]; mAccelY = values[1]; mAccelZ = values[2]; } // reports when the accuracy of sensor has change // SENSOR_STATUS_ACCURACY_HIGH = 3 // SENSOR_STATUS_ACCURACY_LOW = 1 // SENSOR_STATUS_ACCURACY_MEDIUM = 2 // SENSOR_STATUS_UNRELIABLE = 0 //calibration required. public void onAccuracyChanged(int sensor, int accuracy) { // currently not used } }; /** * Custom view constructor. * * @param context * Application context * @param activity * Activity controlling the view */ public AmazedView(Context context, Activity activity) { super(context); mActivity = activity; // init paint and make is look "nice" with anti-aliasing. mPaint = new Paint(); mPaint.setTextSize(14); mPaint.setTypeface(mFont); mPaint.setAntiAlias(true); // setup accelerometer sensor manager. mSensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE); // register our accelerometer so we can receive values. // SENSOR_DELAY_GAME is the recommended rate for games mSensorManager.registerListener(mSensorAccelerometer, SensorManager.SENSOR_ACCELEROMETER, SensorManager.SENSOR_DELAY_GAME); // setup our maze and marble. mMaze = new Maze(mActivity); mMarble = new Marble(this); // load array from /res/values/strings.xml mStrings = getResources().getStringArray(R.array.gameStrings); // set the starting state of the game. switchGameState(GAME_INIT); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // get new screen dimensions. mCanvasWidth = w; mCanvasHeight = h; mCanvasHalfWidth = w / 2; mCanvasHalfHeight = h / 2; // are we in portrait or landscape mode now? // you could use bPortrait = !bPortrait however in the future who know's // how many different ways a device screen may be rotated. if (mCanvasHeight > mCanvasWidth) mPortrait = true; else { mPortrait = false; switchGameState(GAME_LANDSCAPE); } } /** * Called every cycle, used to process current game state. */ public void gameTick() { // very basic state machine, makes a good foundation for a more complex // game. switch (mCurState) { case GAME_INIT: // prepare a new game for the user. initNewGame(); switchGameState(GAME_RUNNING); case GAME_RUNNING: // update our marble. if (!mWarning) updateMarble(); break; } // redraw the screen once our tick function is complete. invalidate(); } /** * Reset game variables in preparation for a new game. */ public void initNewGame() { mMarble.setLives(5); mTotalTime = 0; mlevel = 0; initLevel(); } /** * Initialize the next level. */ public void initLevel() { if (mlevel < mMaze.MAX_LEVELS) { // setup the next level. mWarning = true; mlevel++; mMaze.load(mActivity, mlevel); mMarble.init(); } else { // user has finished the game, update state machine. switchGameState(GAME_COMPLETE); } } /** * Called from gameTick(), update marble x,y based on latest values obtained * from the Accelerometer sensor. AccelX and accelY are values received from * the accelerometer, higher values represent the device tilted at a more * acute angle. */ public void updateMarble() { // we CAN give ourselves a buffer to stop the marble from rolling even // though we think the device is "flat". if (mAccelX > mSensorBuffer || mAccelX < -mSensorBuffer) mMarble.updateX(mAccelX); if (mAccelY > mSensorBuffer || mAccelY < -mSensorBuffer) mMarble.updateY(mAccelY); // check which cell the marble is currently occupying. if (mMaze.getCellType(mMarble.getX(), mMarble.getY()) == mMaze.VOID_TILE) { // user entered the "void". if (mMarble.getLives() > 0) { // user still has some lives remaining, restart the level. mMarble.death(); mMarble.init(); mWarning = true; } else { // user has no more lives left, end of game. mEndTime = System.currentTimeMillis(); mTotalTime += mEndTime - mStartTime; switchGameState(GAME_OVER); } } else if (mMaze.getCellType(mMarble.getX(), mMarble.getY()) == mMaze.EXIT_TILE) { // user has reached the exit tiles, prepare the next level. mEndTime = System.currentTimeMillis(); mTotalTime += mEndTime - mStartTime; initLevel(); } } @Override public boolean onTouchEvent(MotionEvent event) { // we only want to handle down events . if (event.getAction() == MotionEvent.ACTION_DOWN) { if (mCurState == GAME_OVER || mCurState == GAME_COMPLETE) { // re-start the game. mCurState = GAME_INIT; } else if (mCurState == GAME_RUNNING) { // in-game, remove the pop-up text so user can play. mWarning = false; mStartTime = System.currentTimeMillis(); } } return true; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // quit application if user presses the back key. if (keyCode == KeyEvent.KEYCODE_BACK) cleanUp(); return true; } @Override public void onDraw(Canvas canvas) { // update our canvas reference. mCanvas = canvas; // clear the screen. mPaint.setColor(Color.WHITE); mCanvas.drawRect(0, 0, mCanvasWidth, mCanvasHeight, mPaint); // simple state machine, draw screen depending on the current state. switch (mCurState) { case GAME_RUNNING: // draw our maze first since everything else appears "on top" of it. mMaze.draw(mCanvas, mPaint); // draw our marble and hud. mMarble.draw(mCanvas, mPaint); // draw hud drawHUD(); break; case GAME_OVER: drawGameOver(); break; case GAME_COMPLETE: drawGameComplete(); break; case GAME_LANDSCAPE: drawLandscapeMode(); break; } gameTick(); } /** * Called from onDraw(), draws the in-game HUD */ public void drawHUD() { mPaint.setColor(Color.BLACK); mPaint.setTextAlign(Paint.Align.LEFT); mCanvas.drawText(mStrings[TXT_TIME] + ": " + (mTotalTime / 1000), mTextPadding, mHudTextY, mPaint); mPaint.setTextAlign(Paint.Align.CENTER); mCanvas.drawText(mStrings[TXT_LEVEL] + ": " + mlevel, mCanvasHalfWidth, mHudTextY, mPaint); mPaint.setTextAlign(Paint.Align.RIGHT); mCanvas.drawText(mStrings[TXT_LIVES] + ": " + mMarble.getLives(), mCanvasWidth - mTextPadding, mHudTextY, mPaint); // do we need to display the warning message to save the user from // possibly dying instantly. if (mWarning) { mPaint.setColor(Color.BLUE); mCanvas .drawRect(0, mCanvasHalfHeight - 15, mCanvasWidth, mCanvasHalfHeight + 5, mPaint); mPaint.setColor(Color.WHITE); mPaint.setTextAlign(Paint.Align.CENTER); mCanvas.drawText(mStrings[TXT_TAP_SCREEN], mCanvasHalfWidth, mCanvasHalfHeight, mPaint); } } /** * Called from onDraw(), draws the game over screen. */ public void drawGameOver() { mPaint.setColor(Color.BLACK); mPaint.setTextAlign(Paint.Align.CENTER); mCanvas.drawText(mStrings[TXT_GAME_OVER], mCanvasHalfWidth, mCanvasHalfHeight, mPaint); mCanvas.drawText(mStrings[TXT_TOTAL_TIME] + ": " + (mTotalTime / 1000) + "s", mCanvasHalfWidth, mCanvasHalfHeight + mPaint.getFontSpacing(), mPaint); mCanvas.drawText(mStrings[TXT_GAME_OVER_MSG_A] + " " + (mlevel - 1) + " " + mStrings[TXT_GAME_OVER_MSG_B], mCanvasHalfWidth, mCanvasHalfHeight + (mPaint.getFontSpacing() * 2), mPaint); mCanvas.drawText(mStrings[TXT_RESTART], mCanvasHalfWidth, mCanvasHeight - (mPaint.getFontSpacing() * 3), mPaint); } /** * Called from onDraw(), draws the game complete screen. */ public void drawGameComplete() { mPaint.setColor(Color.BLACK); mPaint.setTextAlign(Paint.Align.CENTER); mCanvas.drawText(mStrings[GAME_COMPLETE], mCanvasHalfWidth, mCanvasHalfHeight, mPaint); mCanvas.drawText(mStrings[TXT_TOTAL_TIME] + ": " + (mTotalTime / 1000) + "s", mCanvasHalfWidth, mCanvasHalfHeight + mPaint.getFontSpacing(), mPaint); mCanvas.drawText(mStrings[TXT_RESTART], mCanvasHalfWidth, mCanvasHeight - (mPaint.getFontSpacing() * 3), mPaint); } /** * Called from onDraw(), displays a message asking the user to return the * device back to portrait mode. */ public void drawLandscapeMode() { mPaint.setColor(Color.WHITE); mPaint.setTextAlign(Paint.Align.CENTER); mCanvas.drawRect(0, 0, mCanvasWidth, mCanvasHeight, mPaint); mPaint.setColor(Color.BLACK); mCanvas.drawText(mStrings[TXT_LANDSCAPE_MODE], mCanvasHalfWidth, mCanvasHalfHeight, mPaint); } /** * Updates the current game state with a new state. At the moment this is * very basic however if the game was to get more complicated the code * required for changing game states could grow quickly. * * @param newState * New game state */ public void switchGameState(int newState) { mCurState = newState; } /** * Register the accelerometer sensor so we can use it in-game. */ public void registerListener() { mSensorManager.registerListener(mSensorAccelerometer, SensorManager.SENSOR_ACCELEROMETER, SensorManager.SENSOR_DELAY_GAME); } /** * Unregister the accelerometer sensor otherwise it will continue to operate * and report values. */ public void unregisterListener() { mSensorManager.unregisterListener(mSensorAccelerometer); } /** * Clean up the custom view and exit the application. */ public void cleanUp() { mMarble = null; mMaze = null; mStrings = null; unregisterListener(); mActivity.finish(); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.photostream; import android.os.*; import android.os.Process; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import java.util.concurrent.CancellationException; import java.util.concurrent.atomic.AtomicInteger; /** * <p>UserTask enables proper and easy use of the UI thread. This class allows to * perform background operations and publish results on the UI thread without * having to manipulate threads and/or handlers.</p> * * <p>A user task is defined by a computation that runs on a background thread and * whose result is published on the UI thread. A user task is defined by 3 generic * types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>, * and 4 steps, called <code>begin</code>, <code>doInBackground</code>, * <code>processProgress<code> and <code>end</code>.</p> * * <h2>Usage</h2> * <p>UserTask must be subclassed to be used. The subclass will override at least * one method ({@link #doInBackground(Object[])}), and most often will override a * second one ({@link #onPostExecute(Object)}.)</p> * * <p>Here is an example of subclassing:</p> * <pre> * private class DownloadFilesTask extends UserTask&lt;URL, Integer, Long&gt; { * public File doInBackground(URL... urls) { * int count = urls.length; * long totalSize = 0; * for (int i = 0; i < count; i++) { * totalSize += Downloader.downloadFile(urls[i]); * publishProgress((int) ((i / (float) count) * 100)); * } * } * * public void processProgress(Integer... progress) { * setProgressPercent(progress[0]); * } * * public void end(Long result) { * showDialog("Downloaded " + result + " bytes"); * } * } * </pre> * * <p>Once created, a task is executed very simply:</p> * <pre> * new DownloadFilesTask().execute(new URL[] { ... }); * </pre> * * <h2>User task's generic types</h2> * <p>The three types used by a user task are the following:</p> * <ol> * <li><code>Params</code>, the type of the parameters sent to the task upon * execution.</li> * <li><code>Progress</code>, the type of the progress units published during * the background computation.</li> * <li><code>Result</code>, the type of the result of the background * computation.</li> * </ol> * <p>Not all types are always used by a user task. To mark a type as unused, * simply use the type {@link Void}:</p> * <pre> * private class MyTask extends UserTask<Void, Void, Void) { ... } * </pre> * * <h2>The 4 steps</h2> * <p>When a user task is executed, the task goes through 4 steps:</p> * <ol> * <li>{@link #onPreExecute()}, invoked on the UI thread immediately after the task * is executed. This step is normally used to setup the task, for instance by * showing a progress bar in the user interface.</li> * <li>{@link #doInBackground(Object[])}, invoked on the background thread * immediately after {@link # onPreExecute ()} finishes executing. This step is used * to perform background computation that can take a long time. The parameters * of the user task are passed to this step. The result of the computation must * be returned by this step and will be passed back to the last step. This step * can also use {@link #publishProgress(Object[])} to publish one or more units * of progress. These values are published on the UI thread, in the * {@link #onProgressUpdate(Object[])} step.</li> * <li>{@link # onProgressUpdate (Object[])}, invoked on the UI thread after a * call to {@link #publishProgress(Object[])}. The timing of the execution is * undefined. This method is used to display any form of progress in the user * interface while the background computation is still executing. For instance, * it can be used to animate a progress bar or show logs in a text field.</li> * <li>{@link # onPostExecute (Object)}, invoked on the UI thread after the background * computation finishes. The result of the background computation is passed to * this step as a parameter.</li> * </ol> * * <h2>Threading rules</h2> * <p>There are a few threading rules that must be followed for this class to * work properly:</p> * <ul> * <li>The task instance must be created on the UI thread.</li> * <li>{@link #execute(Object[])} must be invoked on the UI thread.</li> * <li>Do not call {@link # onPreExecute ()}, {@link # onPostExecute (Object)}, * {@link #doInBackground(Object[])}, {@link # onProgressUpdate (Object[])} * manually.</li> * <li>The task can be executed only once (an exception will be thrown if * a second execution is attempted.)</li> * </ul> */ public abstract class UserTask<Params, Progress, Result> { private static final String LOG_TAG = "UserTask"; private static final int CORE_POOL_SIZE = 1; private static final int MAXIMUM_POOL_SIZE = 10; private static final int KEEP_ALIVE = 10; private static final BlockingQueue<Runnable> sWorkQueue = new LinkedBlockingQueue<Runnable>(MAXIMUM_POOL_SIZE); private static final ThreadFactory sThreadFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); public Thread newThread(Runnable r) { return new Thread(r, "UserTask #" + mCount.getAndIncrement()); } }; private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory); private static final int MESSAGE_POST_RESULT = 0x1; private static final int MESSAGE_POST_PROGRESS = 0x2; private static final int MESSAGE_POST_CANCEL = 0x3; private static final InternalHandler sHandler = new InternalHandler(); private final WorkerRunnable<Params, Result> mWorker; private final FutureTask<Result> mFuture; private volatile Status mStatus = Status.PENDING; /** * Indicates the current status of the task. Each status will be set only once * during the lifetime of a task. */ public enum Status { /** * Indicates that the task has not been executed yet. */ PENDING, /** * Indicates that the task is running. */ RUNNING, /** * Indicates that {@link UserTask#onPostExecute(Object)} has finished. */ FINISHED, } /** * Creates a new user task. This constructor must be invoked on the UI thread. */ public UserTask() { mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); return doInBackground(mParams); } }; mFuture = new FutureTask<Result>(mWorker) { @Override protected void done() { Message message; Result result = null; try { result = get(); } catch (InterruptedException e) { android.util.Log.w(LOG_TAG, e); } catch (ExecutionException e) { throw new RuntimeException("An error occured while executing doInBackground()", e.getCause()); } catch (CancellationException e) { message = sHandler.obtainMessage(MESSAGE_POST_CANCEL, new UserTaskResult<Result>(UserTask.this, (Result[]) null)); message.sendToTarget(); return; } catch (Throwable t) { throw new RuntimeException("An error occured while executing " + "doInBackground()", t); } message = sHandler.obtainMessage(MESSAGE_POST_RESULT, new UserTaskResult<Result>(UserTask.this, result)); message.sendToTarget(); } }; } /** * Returns the current status of this task. * * @return The current status. */ public final Status getStatus() { return mStatus; } /** * Override this method to perform a computation on a background thread. The * specified parameters are the parameters passed to {@link #execute(Object[])} * by the caller of this task. * * This method can call {@link #publishProgress(Object[])} to publish updates * on the UI thread. * * @param params The parameters of the task. * * @return A result, defined by the subclass of this task. * * @see #onPreExecute() * @see #onPostExecute(Object) * @see #publishProgress(Object[]) */ public abstract Result doInBackground(Params... params); /** * Runs on the UI thread before {@link #doInBackground(Object[])}. * * @see #onPostExecute(Object) * @see #doInBackground(Object[]) */ public void onPreExecute() { } /** * Runs on the UI thread after {@link #doInBackground(Object[])}. The * specified result is the value returned by {@link #doInBackground(Object[])} * or null if the task was cancelled or an exception occured. * * @param result The result of the operation computed by {@link #doInBackground(Object[])}. * * @see #onPreExecute() * @see #doInBackground(Object[]) */ @SuppressWarnings({"UnusedDeclaration"}) public void onPostExecute(Result result) { } /** * Runs on the UI thread after {@link #publishProgress(Object[])} is invoked. * The specified values are the values passed to {@link #publishProgress(Object[])}. * * @param values The values indicating progress. * * @see #publishProgress(Object[]) * @see #doInBackground(Object[]) */ @SuppressWarnings({"UnusedDeclaration"}) public void onProgressUpdate(Progress... values) { } /** * Runs on the UI thread after {@link #cancel(boolean)} is invoked. * * @see #cancel(boolean) * @see #isCancelled() */ public void onCancelled() { } /** * Returns <tt>true</tt> if this task was cancelled before it completed * normally. * * @return <tt>true</tt> if task was cancelled before it completed * * @see #cancel(boolean) */ public final boolean isCancelled() { return mFuture.isCancelled(); } /** * Attempts to cancel execution of this task. This attempt will * fail if the task has already completed, already been cancelled, * or could not be cancelled for some other reason. If successful, * and this task has not started when <tt>cancel</tt> is called, * this task should never run. If the task has already started, * then the <tt>mayInterruptIfRunning</tt> parameter determines * whether the thread executing this task should be interrupted in * an attempt to stop the task. * * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this * task should be interrupted; otherwise, in-progress tasks are allowed * to complete. * * @return <tt>false</tt> if the task could not be cancelled, * typically because it has already completed normally; * <tt>true</tt> otherwise * * @see #isCancelled() * @see #onCancelled() */ public final boolean cancel(boolean mayInterruptIfRunning) { return mFuture.cancel(mayInterruptIfRunning); } /** * Waits if necessary for the computation to complete, and then * retrieves its result. * * @return The computed result. * * @throws CancellationException If the computation was cancelled. * @throws ExecutionException If the computation threw an exception. * @throws InterruptedException If the current thread was interrupted * while waiting. */ public final Result get() throws InterruptedException, ExecutionException { return mFuture.get(); } /** * Waits if necessary for at most the given time for the computation * to complete, and then retrieves its result. * * @param timeout Time to wait before cancelling the operation. * @param unit The time unit for the timeout. * * @return The computed result. * * @throws CancellationException If the computation was cancelled. * @throws ExecutionException If the computation threw an exception. * @throws InterruptedException If the current thread was interrupted * while waiting. * @throws TimeoutException If the wait timed out. */ public final Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return mFuture.get(timeout, unit); } /** * Executes the task with the specified parameters. The task returns * itself (this) so that the caller can keep a reference to it. * * This method must be invoked on the UI thread. * * @param params The parameters of the task. * * @return This instance of UserTask. * * @throws IllegalStateException If {@link #getStatus()} returns either * {@link UserTask.Status#RUNNING} or {@link UserTask.Status#FINISHED}. */ public final UserTask<Params, Progress, Result> execute(Params... params) { if (mStatus != Status.PENDING) { switch (mStatus) { case RUNNING: throw new IllegalStateException("Cannot execute task:" + " the task is already running."); case FINISHED: throw new IllegalStateException("Cannot execute task:" + " the task has already been executed " + "(a task can be executed only once)"); } } mStatus = Status.RUNNING; onPreExecute(); mWorker.mParams = params; sExecutor.execute(mFuture); return this; } /** * This method can be invoked from {@link #doInBackground(Object[])} to * publish updates on the UI thread while the background computation is * still running. Each call to this method will trigger the execution of * {@link #onProgressUpdate(Object[])} on the UI thread. * * @param values The progress values to update the UI with. * * @see # onProgressUpdate (Object[]) * @see #doInBackground(Object[]) */ protected final void publishProgress(Progress... values) { sHandler.obtainMessage(MESSAGE_POST_PROGRESS, new UserTaskResult<Progress>(this, values)).sendToTarget(); } private void finish(Result result) { onPostExecute(result); mStatus = Status.FINISHED; } private static class InternalHandler extends Handler { @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) @Override public void handleMessage(Message msg) { UserTaskResult result = (UserTaskResult) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT: // There is only one result result.mTask.finish(result.mData[0]); break; case MESSAGE_POST_PROGRESS: result.mTask.onProgressUpdate(result.mData); break; case MESSAGE_POST_CANCEL: result.mTask.onCancelled(); break; } } } private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> { Params[] mParams; } @SuppressWarnings({"RawUseOfParameterizedType"}) private static class UserTaskResult<Data> { final UserTask mTask; final Data[] mData; UserTaskResult(UserTask task, Data... data) { mTask = task; mData = data; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.anycut; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Toast; /** * The activity that shows up in the list of all applications. It has a button * allowing the user to create a new shortcut, and guides them to using Any Cut * through long pressing on the location of the desired shortcut. */ public class FrontDoorActivity extends Activity implements OnClickListener { private static final int REQUEST_SHORTCUT = 1; @Override protected void onCreate(Bundle savedState) { super.onCreate(savedState); setContentView(R.layout.front_door); // Setup the new shortcut button View view = findViewById(R.id.newShortcut); if (view != null) { view.setOnClickListener(this); } } public void onClick(View view) { switch (view.getId()) { case R.id.newShortcut: { // Start the activity to create a shortcut intent Intent intent = new Intent(this, CreateShortcutActivity.class); startActivityForResult(intent, REQUEST_SHORTCUT); break; } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent result) { if (resultCode != RESULT_OK) { return; } switch (requestCode) { case REQUEST_SHORTCUT: { // Boradcast an intent that tells the home screen to create a new shortcut result.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); sendBroadcast(result); // Inform the user that the shortcut has been created Toast.makeText(this, R.string.shortcutCreated, Toast.LENGTH_SHORT).show(); } } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.anycut; import java.util.ArrayList; import java.util.Collections; import java.util.List; import android.app.Activity; import android.app.ListActivity; import android.content.ComponentName; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.google.android.photostream.UserTask; /** * Presents a list of activities to choose from. This list only contains activities * that have ACTION_MAIN, since other types may require data as input. */ public class ActivityPickerActivity extends ListActivity { PackageManager mPackageManager; /** * This class is used to wrap ResolveInfo so that it can be filtered using * ArrayAdapter's built int filtering logic, which depends on toString(). */ private final class ResolveInfoWrapper { private ResolveInfo mInfo; public ResolveInfoWrapper(ResolveInfo info) { mInfo = info; } @Override public String toString() { return mInfo.loadLabel(mPackageManager).toString(); } public ResolveInfo getInfo() { return mInfo; } } private class ActivityAdapter extends ArrayAdapter<ResolveInfoWrapper> { LayoutInflater mInflater; public ActivityAdapter(Activity activity, ArrayList<ResolveInfoWrapper> activities) { super(activity, 0, activities); mInflater = activity.getLayoutInflater(); } @Override public View getView(int position, View convertView, ViewGroup parent) { final ResolveInfoWrapper info = getItem(position); View view = convertView; if (view == null) { // Inflate the view and cache the pointer to the text view view = mInflater.inflate(android.R.layout.simple_list_item_1, parent, false); view.setTag(view.findViewById(android.R.id.text1)); } final TextView textView = (TextView) view.getTag(); textView.setText(info.getInfo().loadLabel(mPackageManager)); return view; } } private final class LoadingTask extends UserTask<Object, Object, ActivityAdapter> { @Override public void onPreExecute() { setProgressBarIndeterminateVisibility(true); } @Override public ActivityAdapter doInBackground(Object... params) { // Load the activities Intent queryIntent = new Intent(Intent.ACTION_MAIN); List<ResolveInfo> list = mPackageManager.queryIntentActivities(queryIntent, 0); // Sort the list Collections.sort(list, new ResolveInfo.DisplayNameComparator(mPackageManager)); // Make the wrappers ArrayList<ResolveInfoWrapper> activities = new ArrayList<ResolveInfoWrapper>(list.size()); for(ResolveInfo item : list) { activities.add(new ResolveInfoWrapper(item)); } return new ActivityAdapter(ActivityPickerActivity.this, activities); } @Override public void onPostExecute(ActivityAdapter result) { setProgressBarIndeterminateVisibility(false); setListAdapter(result); } } @Override protected void onCreate(Bundle savedState) { super.onCreate(savedState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.list); getListView().setTextFilterEnabled(true); mPackageManager = getPackageManager(); // Start loading the data new LoadingTask().execute((Object[]) null); } @Override protected void onListItemClick(ListView list, View view, int position, long id) { ResolveInfoWrapper wrapper = (ResolveInfoWrapper) getListAdapter().getItem(position); ResolveInfo info = wrapper.getInfo(); // Build the intent for the chosen activity Intent intent = new Intent(); intent.setComponent(new ComponentName(info.activityInfo.applicationInfo.packageName, info.activityInfo.name)); Intent result = new Intent(); result.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent); // Set the name of the activity result.putExtra(Intent.EXTRA_SHORTCUT_NAME, info.loadLabel(mPackageManager)); // Build the icon info for the activity Drawable drawable = info.loadIcon(mPackageManager); if (drawable instanceof BitmapDrawable) { BitmapDrawable bd = (BitmapDrawable) drawable; result.putExtra(Intent.EXTRA_SHORTCUT_ICON, bd.getBitmap()); } // ShortcutIconResource iconResource = new ShortcutIconResource(); // iconResource.packageName = info.activityInfo.packageName; // iconResource.resourceName = getResources().getResourceEntryName(info.getIconResource()); // result.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); // Set the result setResult(RESULT_OK, result); finish(); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.anycut; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.EditText; /** * A simple activity to allow the user to manually type in an Intent. */ public class CustomShortcutCreatorActivity extends Activity implements View.OnClickListener { @Override protected void onCreate(Bundle savedState) { super.onCreate(savedState); setContentView(R.layout.custom_shortcut_creator); findViewById(R.id.ok).setOnClickListener(this); findViewById(R.id.cancel).setOnClickListener(this); } public void onClick(View view) { switch (view.getId()) { case R.id.ok: { Intent intent = createShortcutIntent(); setResult(RESULT_OK, intent); finish(); break; } case R.id.cancel: { setResult(RESULT_CANCELED); finish(); break; } } } private Intent createShortcutIntent() { Intent intent = new Intent(); EditText view; view = (EditText) findViewById(R.id.action); intent.setAction(view.getText().toString()); view = (EditText) findViewById(R.id.data); String data = view.getText().toString(); view = (EditText) findViewById(R.id.type); String type = view.getText().toString(); boolean dataEmpty = TextUtils.isEmpty(data); boolean typeEmpty = TextUtils.isEmpty(type); if (!dataEmpty && typeEmpty) { intent.setData(Uri.parse(data)); } else if (!typeEmpty && dataEmpty) { intent.setType(type); } else if (!typeEmpty && !dataEmpty) { intent.setDataAndType(Uri.parse(data), type); } return new Intent().putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.anycut; import android.app.Dialog; import android.app.ListActivity; import android.content.ContentUris; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.provider.Contacts; import android.provider.Contacts.People; import android.provider.Contacts.Phones; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; /** * Presents the user with a list of types of shortucts that can be created. * When Any Cut is launched through the home screen this is the activity that comes up. */ public class CreateShortcutActivity extends ListActivity implements DialogInterface.OnClickListener, Dialog.OnCancelListener { private static final boolean ENABLE_ACTION_ICON_OVERLAYS = false; private static final int REQUEST_PHONE = 1; private static final int REQUEST_TEXT = 2; private static final int REQUEST_ACTIVITY = 3; private static final int REQUEST_CUSTOM = 4; private static final int LIST_ITEM_DIRECT_CALL = 0; private static final int LIST_ITEM_DIRECT_TEXT = 1; private static final int LIST_ITEM_ACTIVITY = 2; private static final int LIST_ITEM_CUSTOM = 3; private static final int DIALOG_SHORTCUT_EDITOR = 1; private Intent mEditorIntent; @Override public void onCreate(Bundle savedState) { super.onCreate(savedState); setListAdapter(ArrayAdapter.createFromResource(this, R.array.mainMenu, android.R.layout.simple_list_item_1)); } @Override protected void onListItemClick(ListView list, View view, int position, long id) { switch (position) { case LIST_ITEM_DIRECT_CALL: { Intent intent = new Intent(Intent.ACTION_PICK, Phones.CONTENT_URI); intent.putExtra(Contacts.Intents.UI.TITLE_EXTRA_KEY, getText(R.string.callShortcutActivityTitle)); startActivityForResult(intent, REQUEST_PHONE); break; } case LIST_ITEM_DIRECT_TEXT: { Intent intent = new Intent(Intent.ACTION_PICK, Phones.CONTENT_URI); intent.putExtra(Contacts.Intents.UI.TITLE_EXTRA_KEY, getText(R.string.textShortcutActivityTitle)); startActivityForResult(intent, REQUEST_TEXT); break; } case LIST_ITEM_ACTIVITY: { Intent intent = new Intent(); intent.setClass(this, ActivityPickerActivity.class); startActivityForResult(intent, REQUEST_ACTIVITY); break; } case LIST_ITEM_CUSTOM: { Intent intent = new Intent(); intent.setClass(this, CustomShortcutCreatorActivity.class); startActivityForResult(intent, REQUEST_CUSTOM); break; } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent result) { if (resultCode != RESULT_OK) { return; } switch (requestCode) { case REQUEST_PHONE: { startShortcutEditor(generatePhoneShortcut(result, R.drawable.sym_action_call, "tel", Intent.ACTION_CALL)); break; } case REQUEST_TEXT: { startShortcutEditor(generatePhoneShortcut(result, R.drawable.sym_action_sms, "smsto", Intent.ACTION_SENDTO)); break; } case REQUEST_ACTIVITY: case REQUEST_CUSTOM: { startShortcutEditor(result); break; } } } @Override protected Dialog onCreateDialog(int dialogId) { switch (dialogId) { case DIALOG_SHORTCUT_EDITOR: { return new ShortcutEditorDialog(this, this, this); } } return super.onCreateDialog(dialogId); } @Override protected void onPrepareDialog(int dialogId, Dialog dialog) { switch (dialogId) { case DIALOG_SHORTCUT_EDITOR: { if (mEditorIntent != null) { // If the editor intent hasn't been set already set it ShortcutEditorDialog editor = (ShortcutEditorDialog) dialog; editor.setIntent(mEditorIntent); mEditorIntent = null; } } } } /** * Starts the shortcut editor * * @param shortcutIntent The shortcut intent to edit */ private void startShortcutEditor(Intent shortcutIntent) { mEditorIntent = shortcutIntent; showDialog(DIALOG_SHORTCUT_EDITOR); } public void onCancel(DialogInterface dialog) { // Remove the dialog, it won't be used again removeDialog(DIALOG_SHORTCUT_EDITOR); } public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON1) { // OK button ShortcutEditorDialog editor = (ShortcutEditorDialog) dialog; Intent shortcut = editor.getIntent(); setResult(RESULT_OK, shortcut); finish(); } // Remove the dialog, it won't be used again removeDialog(DIALOG_SHORTCUT_EDITOR); } /** * Returns an Intent describing a direct text message shortcut. * * @param result The result from the phone number picker * @return an Intent describing a phone number shortcut */ private Intent generatePhoneShortcut(Intent result, int actionResId, String scheme, String action) { Uri phoneUri = result.getData(); long personId = 0; String name = null; String number = null; int type; Cursor cursor = getContentResolver().query(phoneUri, new String[] { Phones.PERSON_ID, Phones.DISPLAY_NAME, Phones.NUMBER, Phones.TYPE }, null, null, null); try { cursor.moveToFirst(); personId = cursor.getLong(0); name = cursor.getString(1); number = cursor.getString(2); type = cursor.getInt(3); } finally { if (cursor != null) { cursor.close(); } } Intent intent = new Intent(); Uri personUri = ContentUris.withAppendedId(People.CONTENT_URI, personId); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, generatePhoneNumberIcon(personUri, type, actionResId)); // Make the URI a direct tel: URI so that it will always continue to work phoneUri = Uri.fromParts(scheme, number, null); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(action, phoneUri)); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name); return intent; } /** * Generates a phone number shortcut icon. Adds an overlay describing the type of the phone * number, and if there is a photo also adds the call action icon. * * @param personUri The person the phone number belongs to * @param type The type of the phone number * @param actionResId The ID for the action resource * @return The bitmap for the icon */ private Bitmap generatePhoneNumberIcon(Uri personUri, int type, int actionResId) { final Resources r = getResources(); boolean drawPhoneOverlay = true; Bitmap photo = People.loadContactPhoto(this, personUri, 0, null); if (photo == null) { // If there isn't a photo use the generic phone action icon instead Bitmap phoneIcon = getPhoneActionIcon(r, actionResId); if (phoneIcon != null) { photo = phoneIcon; drawPhoneOverlay = false; } else { return null; } } // Setup the drawing classes int iconSize = (int) r.getDimension(android.R.dimen.app_icon_size); Bitmap icon = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(icon); // Copy in the photo Paint photoPaint = new Paint(); photoPaint.setDither(true); photoPaint.setFilterBitmap(true); Rect src = new Rect(0,0, photo.getWidth(),photo.getHeight()); Rect dst = new Rect(0,0, iconSize,iconSize); canvas.drawBitmap(photo, src, dst, photoPaint); // Create an overlay for the phone number type String overlay = null; switch (type) { case Phones.TYPE_HOME: overlay = "H"; break; case Phones.TYPE_MOBILE: overlay = "M"; break; case Phones.TYPE_WORK: overlay = "W"; break; case Phones.TYPE_PAGER: overlay = "P"; break; case Phones.TYPE_OTHER: overlay = "O"; break; } if (overlay != null) { Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); textPaint.setTextSize(20.0f); textPaint.setTypeface(Typeface.DEFAULT_BOLD); textPaint.setColor(r.getColor(R.color.textColorIconOverlay)); textPaint.setShadowLayer(3f, 1, 1, r.getColor(R.color.textColorIconOverlayShadow)); canvas.drawText(overlay, 2, 16, textPaint); } // Draw the phone action icon as an overlay if (ENABLE_ACTION_ICON_OVERLAYS && drawPhoneOverlay) { Bitmap phoneIcon = getPhoneActionIcon(r, actionResId); if (phoneIcon != null) { src.set(0,0, phoneIcon.getWidth(),phoneIcon.getHeight()); int iconWidth = icon.getWidth(); dst.set(iconWidth - 20, -1, iconWidth, 19); canvas.drawBitmap(phoneIcon, src, dst, photoPaint); } } return icon; } /** * Returns the icon for the phone call action. * * @param r The resources to load the icon from * @param resId The resource ID to load * @return the icon for the phone call action */ private Bitmap getPhoneActionIcon(Resources r, int resId) { Drawable phoneIcon = r.getDrawable(resId); if (phoneIcon instanceof BitmapDrawable) { BitmapDrawable bd = (BitmapDrawable) phoneIcon; return bd.getBitmap(); } else { return null; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.anycut; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.content.Intent.ShortcutIconResource; import android.graphics.Bitmap; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import android.widget.ImageView; /** * A dialog that can edit a shortcut intent. For now the icon is displayed, and only * the name may be edited. */ public class ShortcutEditorDialog extends AlertDialog implements OnClickListener, TextWatcher { static final String STATE_INTENT = "intent"; private boolean mCreated = false; private Intent mIntent; private ImageView mIconView; private EditText mNameView; private OnClickListener mOnClick; private OnCancelListener mOnCancel; public ShortcutEditorDialog(Context context, OnClickListener onClick, OnCancelListener onCancel) { super(context); mOnClick = onClick; mOnCancel = onCancel; // Setup the dialog View view = getLayoutInflater().inflate(R.layout.shortcut_editor, null, false); setTitle(R.string.shortcutEditorTitle); setButton(context.getText(android.R.string.ok), this); setButton2(context.getText(android.R.string.cancel), mOnClick); setOnCancelListener(mOnCancel); setCancelable(true); setView(view); mIconView = (ImageView) view.findViewById(R.id.shortcutIcon); mNameView = (EditText) view.findViewById(R.id.shortcutName); } public void onClick(DialogInterface dialog, int which) { if (which == BUTTON1) { String name = mNameView.getText().toString(); if (TextUtils.isEmpty(name)) { // Don't allow an empty name mNameView.setError(getContext().getText(R.string.errorEmptyName)); return; } mIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name); } mOnClick.onClick(dialog, which); } @Override protected void onCreate(Bundle state) { super.onCreate(state); if (state != null) { mIntent = state.getParcelable(STATE_INTENT); } mCreated = true; // If an intent is set make sure to load it now that it's safe if (mIntent != null) { loadIntent(mIntent); } } @Override public Bundle onSaveInstanceState() { Bundle state = super.onSaveInstanceState(); state.putParcelable(STATE_INTENT, getIntent()); return state; } public void beforeTextChanged(CharSequence s, int start, int count, int after) { // Do nothing } public void onTextChanged(CharSequence s, int start, int before, int count) { // Do nothing } public void afterTextChanged(Editable text) { if (text.length() == 0) { mNameView.setError(getContext().getText(R.string.errorEmptyName)); } else { mNameView.setError(null); } } /** * Saves the current state of the editor into the intent and returns it. * * @return the intent for the shortcut being edited */ public Intent getIntent() { mIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, mNameView.getText().toString()); return mIntent; } /** * Reads the state of the shortcut from the intent and sets up the editor * * @param intent A shortcut intent to edit */ public void setIntent(Intent intent) { mIntent = intent; if (mCreated) { loadIntent(intent); } } /** * Loads the editor state from a shortcut intent. * * @param intent The shortcut intent to load the editor from */ private void loadIntent(Intent intent) { // Show the icon Bitmap iconBitmap = intent.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); if (iconBitmap != null) { mIconView.setImageBitmap(iconBitmap); } else { ShortcutIconResource iconRes = intent.getParcelableExtra( Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (iconRes != null) { int res = getContext().getResources().getIdentifier(iconRes.resourceName, null, iconRes.packageName); mIconView.setImageResource(res); } else { mIconView.setVisibility(View.INVISIBLE); } } // Fill in the name field for editing mNameView.addTextChangedListener(this); mNameView.setText(intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME)); // Ensure the intent has the proper flags intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } }
Java
/* * 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.android.heightmapprofiler; import com.android.heightmapprofiler.R; import android.app.AlertDialog; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; /** * Main entry point for the HeightMapTest application. */ public class MainMenu extends PreferenceActivity implements Preference.OnPreferenceClickListener { private static final int ACTIVITY_TEST = 0; private static final int RESULTS_DIALOG = 0; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.preferences); Preference runTestButton = getPreferenceManager().findPreference("runtest"); if (runTestButton != null) { runTestButton.setOnPreferenceClickListener(this); } } /** Creates the test results dialog and fills in a dummy message. */ @Override protected Dialog onCreateDialog(int id) { Dialog dialog = null; if (id == RESULTS_DIALOG) { String dummy = "No results yet."; CharSequence sequence = dummy.subSequence(0, dummy.length() -1); dialog = new AlertDialog.Builder(this) .setTitle(R.string.dialog_title) .setPositiveButton(R.string.dialog_ok, null) .setMessage(sequence) .create(); } return dialog; } /** * Replaces the dummy message in the test results dialog with a string that * describes the actual test results. */ protected void onPrepareDialog (int id, Dialog dialog) { if (id == RESULTS_DIALOG) { // Extract final timing information from the profiler. final ProfileRecorder profiler = ProfileRecorder.sSingleton; final long frameVerts = profiler.getAverageVerts(); final long frameTime = profiler.getAverageTime(ProfileRecorder.PROFILE_FRAME); final long frameMin = profiler.getMinTime(ProfileRecorder.PROFILE_FRAME); final long frameMax = profiler.getMaxTime(ProfileRecorder.PROFILE_FRAME); final long drawTime = profiler.getAverageTime(ProfileRecorder.PROFILE_DRAW); final long drawMin = profiler.getMinTime(ProfileRecorder.PROFILE_DRAW); final long drawMax = profiler.getMaxTime(ProfileRecorder.PROFILE_DRAW); final long simTime = profiler.getAverageTime(ProfileRecorder.PROFILE_SIM); final long simMin = profiler.getMinTime(ProfileRecorder.PROFILE_SIM); final long simMax = profiler.getMaxTime(ProfileRecorder.PROFILE_SIM); final float fps = frameTime > 0 ? 1000.0f / frameTime : 0.0f; String result = "Frame: " + frameTime + "ms (" + fps + " fps)\n" + "\t\tMin: " + frameMin + "ms\t\tMax: " + frameMax + "\n" + "Draw: " + drawTime + "ms\n" + "\t\tMin: " + drawMin + "ms\t\tMax: " + drawMax + "\n" + "Sim: " + simTime + "ms\n" + "\t\tMin: " + simMin + "ms\t\tMax: " + simMax + "\n" + "\nVerts per frame: ~" + frameVerts + "\n"; CharSequence sequence = result.subSequence(0, result.length() -1); AlertDialog alertDialog = (AlertDialog)dialog; alertDialog.setMessage(sequence); } } /** Shows the results dialog when the test activity closes. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); showDialog(RESULTS_DIALOG); } public boolean onPreferenceClick(Preference preference) { Intent i = new Intent(this, HeightMapTest.class); startActivityForResult(i, ACTIVITY_TEST); return true; } }
Java
/* * 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.android.heightmapprofiler; import android.os.SystemClock; /** * Implements a simple runtime profiler. The profiler records start and stop * times for several different types of profiles and can then return min, max * and average execution times per type. Profile types are independent and may * be nested in calling code. This object is a singleton for convenience. */ public class ProfileRecorder { // A type for recording actual draw command time. public static final int PROFILE_DRAW = 0; // A type for recording the time it takes to run a single simulation step. public static final int PROFILE_SIM = 2; // A type for recording the total amount of time spent rendering a frame. public static final int PROFILE_FRAME = 3; private static final int PROFILE_COUNT = PROFILE_FRAME + 1; private ProfileRecord[] mProfiles; private int mFrameCount; private long mVertexCount; public static ProfileRecorder sSingleton = new ProfileRecorder(); public ProfileRecorder() { mProfiles = new ProfileRecord[PROFILE_COUNT]; for (int x = 0; x < PROFILE_COUNT; x++) { mProfiles[x] = new ProfileRecord(); } } /** Starts recording execution time for a specific profile type.*/ public final void start(int profileType) { if (profileType < PROFILE_COUNT) { mProfiles[profileType].start(SystemClock.uptimeMillis()); } } /** Stops recording time for this profile type. */ public final void stop(int profileType) { if (profileType < PROFILE_COUNT) { mProfiles[profileType].stop(SystemClock.uptimeMillis()); } } /** Indicates the end of the frame.*/ public final void endFrame() { mFrameCount++; } /* Flushes all recorded timings from the profiler. */ public final void resetAll() { for (int x = 0; x < PROFILE_COUNT; x++) { mProfiles[x].reset(); } mFrameCount = 0; mVertexCount = 0L; } /* Returns the average execution time, in milliseconds, for a given type. */ public long getAverageTime(int profileType) { long time = 0; if (profileType < PROFILE_COUNT) { time = mProfiles[profileType].getAverageTime(mFrameCount); } return time; } /* Returns the minimum execution time in milliseconds for a given type. */ public long getMinTime(int profileType) { long time = 0; if (profileType < PROFILE_COUNT) { time = mProfiles[profileType].getMinTime(); } return time; } /* Returns the maximum execution time in milliseconds for a given type. */ public long getMaxTime(int profileType) { long time = 0; if (profileType < PROFILE_COUNT) { time = mProfiles[profileType].getMaxTime(); } return time; } public long getTotalVerts() { return mVertexCount; } public long getAverageVerts() { return mVertexCount / mFrameCount; } public void addVerts(long vertCount) { mVertexCount += vertCount; } /** * A simple class for storing timing information about a single profile * type. */ protected class ProfileRecord { private long mStartTime; private long mTotalTime; private long mMinTime; private long mMaxTime; public void start(long time) { mStartTime = time; } public void stop(long time) { if (mStartTime > 0) { final long timeDelta = time - mStartTime; mTotalTime += timeDelta; if (mMinTime == 0 || timeDelta < mMinTime) { mMinTime = timeDelta; } if (mMaxTime == 0 || timeDelta > mMaxTime) { mMaxTime = timeDelta; } } } public long getAverageTime(int frameCount) { long time = frameCount > 0 ? mTotalTime / frameCount : 0; return time; } public long getMinTime() { return mMinTime; } public long getMaxTime() { return mMaxTime; } public void startNewProfilePeriod() { mTotalTime = 0; } public void reset() { mTotalTime = 0; mStartTime = 0; mMinTime = 0; mMaxTime = 0; } } }
Java
/* * Copyright (C) 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.android.heightmapprofiler; import javax.microedition.khronos.opengles.GL10; import android.graphics.Bitmap; // This class manages a regular grid of LandTile objects. In this sample, // all the objects are the same mesh. In a real game, they would probably be // different to create a more interesting landscape. // This class also abstracts the concept of tiles away from the rest of the // code, so that the collision system (amongst others) can query the height of any // given point in the world. public class LandTileMap { private MeshLibrary mMeshLibrary = new MeshLibrary(); private LandTile[] mTiles; private LandTile mSkybox; private float mWorldWidth; private float mWorldHeight; private int mTilesAcross; private int mSkyboxTexture; private boolean mUseColors; private boolean mUseTexture; private NativeRenderer mNativeRenderer; public LandTileMap( int tilesAcross, int tilesDown, Bitmap heightmap, Bitmap lightmap, boolean useColors, boolean useTexture, boolean useLods, int maxSubdivisions, boolean useFixedPoint) { Grid[] lodMeshes; int lodLevels = 1; if (useLods) { lodLevels = LandTile.LOD_LEVELS; } lodMeshes = new Grid[lodLevels]; final int subdivisionSizeStep = maxSubdivisions / lodLevels; for (int x = 0; x < lodLevels; x++) { final int subdivisions = subdivisionSizeStep * (lodLevels - x); lodMeshes[x] = HeightMapMeshMaker.makeGrid( heightmap, lightmap, subdivisions, LandTile.TILE_SIZE, LandTile.TILE_SIZE, LandTile.TILE_HEIGHT_THRESHOLD, useFixedPoint); } mMeshLibrary.addMesh(lodMeshes); LandTile[] tiles = new LandTile[tilesAcross * tilesDown]; for (int x = 0; x < tilesAcross; x++) { for (int y = 0; y < tilesDown; y++) { LandTile tile = new LandTile(useLods, maxSubdivisions); tile.setLods(lodMeshes, heightmap); tiles[x * tilesAcross + y] = tile; tile.setPosition(x * LandTile.TILE_SIZE, 0.0f, y * LandTile.TILE_SIZE); } } mTiles = tiles; mWorldWidth = tilesAcross * LandTile.TILE_SIZE; mWorldHeight = tilesDown * LandTile.TILE_SIZE; mTilesAcross = tilesAcross; mUseColors = useColors; mUseTexture = useTexture; } public void setLandTextures( int landTextures[] ) { for( LandTile landTile : mTiles ) { landTile.setLODTextures( landTextures ); } } public void setupSkybox(Bitmap heightmap, boolean useFixedPoint) { if (mSkybox == null) { mSkybox = new LandTile(mWorldWidth, 1024, mWorldHeight, 1, 16, 1000000.0f); mMeshLibrary.addMesh(mSkybox.generateLods(heightmap, null, useFixedPoint)); mSkybox.setPosition(0.0f, 0.0f, 0.0f); } } public float getHeight(float worldX, float worldZ) { float height = 0.0f; if (worldX > 0.0f && worldX < mWorldWidth && worldZ > 0.0f && worldZ < mWorldHeight) { int tileX = (int)(worldX / LandTile.TILE_SIZE); int tileY = (int)(worldZ / LandTile.TILE_SIZE); height = mTiles[tileX * mTilesAcross + tileY].getHeight(worldX, worldZ); } return height; } public void setTextures(int[] landTextures, int skyboxTexture) { setLandTextures( landTextures ); mSkyboxTexture = skyboxTexture; if (mNativeRenderer != null) { final int count = mTiles.length; for (int x = 0; x < count; x++) { mNativeRenderer.registerTile(landTextures, mTiles[x], false); } if (mSkybox != null) { // Work around since registerTile() takes an array of textures int textures[] = new int[1]; textures[0] = skyboxTexture; mNativeRenderer.registerTile(textures, mSkybox, true); } } } public void draw(GL10 gl, Vector3 cameraPosition) { if (mNativeRenderer != null) { mNativeRenderer.draw(true, true); } else { if (mSkyboxTexture != 0) { gl.glBindTexture(GL10.GL_TEXTURE_2D, mSkyboxTexture); } Grid.beginDrawing(gl, mUseTexture, mUseColors); if (mSkybox != null) { gl.glDepthMask(false); gl.glDisable(GL10.GL_DEPTH_TEST); mSkybox.draw(gl, cameraPosition); gl.glDepthMask(true); gl.glEnable(GL10.GL_DEPTH_TEST); } final int count = mTiles.length; for (int x = 0; x < count; x++) { mTiles[x].draw(gl, cameraPosition); } Grid.endDrawing(gl); } } public void generateHardwareBuffers(GL10 gl) { mMeshLibrary.generateHardwareBuffers(gl); } public void setNativeRenderer(NativeRenderer nativeRenderer) { mNativeRenderer = nativeRenderer; } }
Java
/* * 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.android.heightmapprofiler; import android.os.SystemClock; // Very simple game runtime. Implements basic movement and collision detection with the landscape. public class Game implements Runnable { private Vector3 mCameraPosition = new Vector3(100.0f, 128.0f, 400.0f); private Vector3 mTargetPosition = new Vector3(350.0f, 128.0f, 650.0f); private Vector3 mWorkVector = new Vector3(); private float mCameraXZAngle; private float mCameraYAngle; private float mCameraLookAtDistance = (float)Math.sqrt(mTargetPosition.distance2(mCameraPosition)); private boolean mCameraDirty = true; private boolean mRunning = true; private boolean mPaused = false; private Object mPauseLock = new Object(); private LandTileMap mTileMap; private final static float CAMERA_ORBIT_SPEED = 0.3f; private final static float CAMERA_MOVE_SPEED = 5.0f; private final static float VIEWER_HEIGHT = 15.0f; private SimpleGLRenderer mSimpleRenderer; public Game(SimpleGLRenderer renderer, LandTileMap tiles) { mSimpleRenderer = renderer; mTileMap = tiles; } public void run() { while (mRunning) { ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_SIM); long startTime = SystemClock.uptimeMillis(); if (mCameraDirty) { // snap the camera to the floor float height = mTileMap.getHeight(mCameraPosition.x, mCameraPosition.z); mCameraPosition.y = height + VIEWER_HEIGHT; updateCamera(); } long endTime = SystemClock.uptimeMillis(); ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_SIM); if (endTime - startTime < 16) { // we're running too fast! sleep for a bit to let the render thread do some work. try { Thread.sleep(16 - (endTime - startTime)); } catch (InterruptedException e) { // Interruptions are not a big deal here. } } synchronized(mPauseLock) { if (mPaused) { while (mPaused) { try { mPauseLock.wait(); } catch (InterruptedException e) { // OK if this is interrupted. } } } } } } synchronized private void updateCamera() { mWorkVector.set((float)Math.cos(mCameraXZAngle), (float)Math.sin(mCameraYAngle), (float)Math.sin(mCameraXZAngle)); mWorkVector.multiply(mCameraLookAtDistance); mWorkVector.add(mCameraPosition); mTargetPosition.set(mWorkVector); mSimpleRenderer.setCameraPosition(mCameraPosition.x, mCameraPosition.y, mCameraPosition.z); mSimpleRenderer.setCameraLookAtPosition(mTargetPosition.x, mTargetPosition.y, mTargetPosition.z); mCameraDirty = false; } synchronized public void rotate(float x, float y) { if (x != 0.0f) { mCameraXZAngle += x * CAMERA_ORBIT_SPEED; mCameraDirty = true; } if (y != 0.0f) { mCameraYAngle += y * CAMERA_ORBIT_SPEED; mCameraDirty = true; } } synchronized public void move(float amount) { mWorkVector.set(mTargetPosition); mWorkVector.subtract(mCameraPosition); mWorkVector.normalize(); mWorkVector.multiply(amount * CAMERA_MOVE_SPEED); mCameraPosition.add(mWorkVector); mTargetPosition.add(mWorkVector); mCameraDirty = true; } public void pause() { synchronized(mPauseLock) { mPaused = true; } } public void resume() { synchronized(mPauseLock) { mPaused = false; mPauseLock.notifyAll(); } } }
Java
/* * 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.android.heightmapprofiler; import javax.microedition.khronos.opengles.GL10; import android.graphics.Bitmap; // This class defines a single land tile. It is built from // a height map image and may contain several meshes defining different levels // of detail. public class LandTile { public final static float TILE_SIZE = 512; private final static float HALF_TILE_SIZE = TILE_SIZE / 2; public final static float TILE_HEIGHT_THRESHOLD = 0.4f; private final static int MAX_SUBDIVISIONS = 24; private final static float LOD_STEP_SIZE = 300.0f; public final static int LOD_LEVELS = 4; private final static float MAX_LOD_DISTANCE = LOD_STEP_SIZE * (LOD_LEVELS - 1); private final static float MAX_LOD_DISTANCE2 = MAX_LOD_DISTANCE * MAX_LOD_DISTANCE; private Grid mLODMeshes[]; private int mLODTextures[]; private Vector3 mPosition = new Vector3(); private Vector3 mCenterPoint = new Vector3(); private Bitmap mHeightMap; private float mHeightMapScaleX; private float mHeightMapScaleY; private int mLodLevels = LOD_LEVELS; private int mMaxSubdivisions = MAX_SUBDIVISIONS; private float mTileSizeX = TILE_SIZE; private float mTileSizeZ = TILE_SIZE; private float mHalfTileSizeX = HALF_TILE_SIZE; private float mHalfTileSizeZ = HALF_TILE_SIZE; private float mTileHeightScale = TILE_HEIGHT_THRESHOLD; private float mMaxLodDistance = MAX_LOD_DISTANCE; private float mMaxLodDistance2 = MAX_LOD_DISTANCE2; public LandTile() { } public LandTile(boolean useLods, int maxSubdivisions ) { if (!useLods) { mLodLevels = 1; } mMaxSubdivisions = maxSubdivisions; } public LandTile(float sizeX, float sizeY, float sizeZ, int lodLevelCount, int maxSubdivisions, float maxLodDistance) { mTileSizeX = sizeX; mTileSizeZ = sizeZ; mTileHeightScale = (1.0f / 255.0f) * sizeY; mLodLevels = lodLevelCount; mMaxSubdivisions = maxSubdivisions; mMaxLodDistance = maxLodDistance; mMaxLodDistance2 = maxLodDistance * maxLodDistance; mHalfTileSizeX = sizeX / 2.0f; mHalfTileSizeZ = sizeZ / 2.0f; } public void setLods(Grid[] lodMeshes, Bitmap heightmap) { mHeightMap = heightmap; mHeightMapScaleX = heightmap.getWidth() / mTileSizeX; mHeightMapScaleY = heightmap.getHeight() / mTileSizeZ; mLODMeshes = lodMeshes; } public void setLODTextures( int LODTextures[] ) { mLODTextures = LODTextures; } public Grid[] generateLods(Bitmap heightmap, Bitmap lightmap, boolean useFixedPoint) { final int subdivisionSizeStep = mMaxSubdivisions / mLodLevels; mLODMeshes = new Grid[mLodLevels]; for (int x = 0; x < mLodLevels; x++) { final int subdivisions = subdivisionSizeStep * (mLodLevels - x); mLODMeshes[x] = HeightMapMeshMaker.makeGrid(heightmap, lightmap, subdivisions, mTileSizeX, mTileSizeZ, mTileHeightScale, useFixedPoint); } mHeightMap = heightmap; mHeightMapScaleX = heightmap.getWidth() / mTileSizeX; mHeightMapScaleY = heightmap.getHeight() / mTileSizeZ; return mLODMeshes; } public final void setPosition(float x, float y, float z) { mPosition.set(x, y, z); mCenterPoint.set(x + mHalfTileSizeX, y, z + mHalfTileSizeZ); } public final void setPosition(Vector3 position) { mPosition.set(position); mCenterPoint.set(position.x + mHalfTileSizeX, position.y, position.z + mHalfTileSizeZ); } public final Vector3 getPosition() { return mPosition; } public final Vector3 getCenterPoint() { return mCenterPoint; } public final Grid[] getLods() { return mLODMeshes; } public final float getMaxLodDistance() { return mMaxLodDistance; } public float getHeight(float worldSpaceX, float worldSpaceZ) { final float tileSpaceX = worldSpaceX - mPosition.x; final float tileSpaceY = worldSpaceZ - mPosition.z; final float imageSpaceX = tileSpaceX * mHeightMapScaleX; final float imageSpaceY = tileSpaceY * mHeightMapScaleY; float height = 0.0f; if (imageSpaceX >= 0.0f && imageSpaceX < mHeightMap.getWidth() && imageSpaceY >= 0.0f && imageSpaceY < mHeightMap.getHeight()) { height = HeightMapMeshMaker.getBilinearFilteredHeight(mHeightMap, imageSpaceX, imageSpaceY, mTileHeightScale); } return height; } public void draw(GL10 gl, Vector3 cameraPosition) { mCenterPoint.y = cameraPosition.y; // HACK! final float distanceFromCamera2 = cameraPosition.distance2(mCenterPoint); int lod = mLodLevels - 1; if (distanceFromCamera2 < mMaxLodDistance2) { final int bucket = (int)((distanceFromCamera2 / mMaxLodDistance2) * mLodLevels); lod = Math.min(bucket, mLodLevels - 1); } gl.glPushMatrix(); gl.glTranslatef(mPosition.x, mPosition.y, mPosition.z); // TODO - should add some code to keep state of current Texture and only set it if a new texture is needed - // may be taken care of natively by OpenGL lib. if( mLODTextures != null ) { // Check to see if we have different LODs to choose from (i.e. Text LOD feature is turned on). If not then // just select the default texture if( mLODTextures.length == 1 ) { gl.glBindTexture(GL10.GL_TEXTURE_2D, mLODTextures[0]); } // if the LOD feature is enabled, use lod value to select correct texture to use else { gl.glBindTexture(GL10.GL_TEXTURE_2D, mLODTextures[lod]); } } ProfileRecorder.sSingleton.addVerts(mLODMeshes[lod].getVertexCount()); mLODMeshes[lod].draw(gl, true, true); gl.glPopMatrix(); } }
Java
/* * 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.android.heightmapprofiler; /** * Simple 3D vector class. Handles basic vector math for 3D vectors. */ public final class Vector3 { public float x; public float y; public float z; public static final Vector3 ZERO = new Vector3(0, 0, 0); public Vector3() { } public Vector3(float xValue, float yValue, float zValue) { set(xValue, yValue, zValue); } public Vector3(Vector3 other) { set(other); } public final void add(Vector3 other) { x += other.x; y += other.y; z += other.z; } public final void add(float otherX, float otherY, float otherZ) { x += otherX; y += otherY; z += otherZ; } public final void subtract(Vector3 other) { x -= other.x; y -= other.y; z -= other.z; } public final void multiply(float magnitude) { x *= magnitude; y *= magnitude; z *= magnitude; } public final void multiply(Vector3 other) { x *= other.x; y *= other.y; z *= other.z; } public final void divide(float magnitude) { if (magnitude != 0.0f) { x /= magnitude; y /= magnitude; z /= magnitude; } } public final void set(Vector3 other) { x = other.x; y = other.y; z = other.z; } public final void set(float xValue, float yValue, float zValue) { x = xValue; y = yValue; z = zValue; } public final float dot(Vector3 other) { return (x * other.x) + (y * other.y) + (z * other.z); } public final float length() { return (float) Math.sqrt(length2()); } public final float length2() { return (x * x) + (y * y) + (z * z); } public final float distance2(Vector3 other) { float dx = x - other.x; float dy = y - other.y; float dz = z - other.z; return (dx * dx) + (dy * dy) + (dz * dz); } public final float normalize() { final float magnitude = length(); // TODO: I'm choosing safety over speed here. if (magnitude != 0.0f) { x /= magnitude; y /= magnitude; z /= magnitude; } return magnitude; } public final void zero() { set(0.0f, 0.0f, 0.0f); } }
Java
/* * 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.android.heightmapprofiler; import android.graphics.Bitmap; import android.graphics.Color; // This class generates vertex arrays based on grayscale images. // It defines 1.0 (white) as the tallest point and 0.0 (black) as the lowest point, // and builds a mesh that represents that topology. public class HeightMapMeshMaker { public static final Grid makeGrid(Bitmap drawable, Bitmap lightmap, int subdivisions, float width, float height, float scale, boolean fixedPoint) { Grid grid = null; final float subdivisionRange = subdivisions - 1; final float vertexSizeX = width / subdivisionRange; final float vertexSizeZ = height / subdivisionRange; if (drawable != null) { grid = new Grid(subdivisions, subdivisions, fixedPoint); final float heightMapScaleX = drawable.getWidth() / subdivisionRange; final float heightMapScaleY = drawable.getHeight() / subdivisionRange; final float lightMapScaleX = lightmap != null ? lightmap.getWidth() / subdivisions : 0.0f; final float lightMapScaleY = lightmap != null ? lightmap.getHeight() / subdivisions : 0.0f; final float[] vertexColor = { 1.0f, 1.0f, 1.0f, 1.0f }; for (int i = 0; i < subdivisions; i++) { final float u = (float)(i + 1) / subdivisions; for (int j = 0; j < subdivisions; j++) { final float v = (float)(j + 1) / subdivisions; final float vertexHeight = getBilinearFilteredHeight(drawable, (heightMapScaleX * i), (heightMapScaleY * j), scale); if (lightmap != null) { final int lightColor = lightmap.getPixel((int)(lightMapScaleX * i), (int)(lightMapScaleY * j)); final float colorScale = 1.0f / 255.0f; vertexColor[0] = colorScale * Color.red(lightColor); vertexColor[1] = colorScale * Color.green(lightColor); vertexColor[2] = colorScale * Color.blue(lightColor); vertexColor[3] = colorScale * Color.alpha(lightColor); } grid.set(i, j, i * vertexSizeX, vertexHeight, j * vertexSizeZ, u, v, vertexColor); } } } return grid; } // In order to get a smooth gradation between pixels from a low-resolution height map, // this function uses a bilinear filter to calculate a weighted average of four pixels // surrounding the requested point. public static final float getBilinearFilteredHeight(Bitmap drawable, float x, float y, float scale) { final int topLeftPixelX = clamp((int)Math.floor(x), 0, drawable.getWidth() - 1); final int topLeftPixelY = clamp((int)Math.floor(y), 0, drawable.getHeight() - 1); final int bottomRightPixelX = clamp((int)Math.ceil(x), 0, drawable.getWidth() - 1); final int bottomRightPixelY = clamp((int)Math.ceil(y), 0, drawable.getHeight() - 1); final float topLeftWeightX = x - topLeftPixelX; final float topLeftWeightY = y - topLeftPixelY; final float bottomRightWeightX = 1.0f - topLeftWeightX; final float bottomRightWeightY = 1.0f - topLeftWeightY; final int topLeft = drawable.getPixel(topLeftPixelX, topLeftPixelY); final int topRight = drawable.getPixel(bottomRightPixelX, topLeftPixelY); final int bottomLeft = drawable.getPixel(topLeftPixelX, bottomRightPixelY); final int bottomRight = drawable.getPixel(bottomRightPixelX, bottomRightPixelY); final float red1 = bottomRightWeightX * Color.red(topLeft) + topLeftWeightX * Color.red(topRight); final float red2 = bottomRightWeightX * Color.red(bottomLeft) + topLeftWeightX * Color.red(bottomRight); final float red = bottomRightWeightY * red1 + topLeftWeightY * red2; final float height = red * scale; return height; } private static final int clamp(int value, int min, int max) { return value < min ? min : (value > max ? max : value); } }
Java
/* * 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.android.heightmapprofiler; import java.util.ArrayList; import javax.microedition.khronos.opengles.GL10; // This is a central repository for all vertex arrays. It handles // generation and invalidation of VBOs from each mesh. public class MeshLibrary { // This sample only has one type of mesh, Grid, but in a real game you might have // multiple types of objects managing vertex arrays (animated objects, objects loaded from // files, etc). This class could easily be modified to work with some basic Mesh class // in that case. private ArrayList<Grid[]> mMeshes = new ArrayList<Grid[]>(); public int addMesh(Grid[] lods) { int index = mMeshes.size(); mMeshes.add(lods); return index; } public Grid[] getMesh(int index) { Grid[] mesh = null; if (index >= 0 && index < mMeshes.size()) { mesh = mMeshes.get(index); } return mesh; } public void generateHardwareBuffers(GL10 gl) { final int count = mMeshes.size(); for (int x = 0; x < count; x++) { Grid[] lods = mMeshes.get(x); assert lods != null; for (int y = 0; y < lods.length; y++) { Grid lod = lods[y]; if (lod != null) { lod.invalidateHardwareBuffers(); lod.generateHardwareBuffers(gl); } } } } public void freeHardwareBuffers(GL10 gl) { final int count = mMeshes.size(); for (int x = 0; x < count; x++) { Grid[] lods = mMeshes.get(x); assert lods != null; for (int y = 0; y < lods.length; y++) { Grid lod = lods[y]; if (lod != null) { lod.releaseHardwareBuffers(gl); } } } } }
Java
/* * 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.android.heightmapprofiler; // This is a thin interface for a renderer implemented in C++ using the NDK. public class NativeRenderer { private Vector3 mCameraPosition = new Vector3(); private Vector3 mLookAtPosition = new Vector3(); private boolean mCameraDirty = false; static { System.loadLibrary("heightmapprofiler"); } public NativeRenderer() { nativeReset(); } public void setCamera(Vector3 camera, Vector3 lookat) { mCameraPosition = camera; mLookAtPosition = lookat; mCameraDirty = true; } public void registerTile(int textures[], LandTile tile, boolean isSkybox) { final Grid[] lods = tile.getLods(); final Vector3 position = tile.getPosition(); final Vector3 center = tile.getCenterPoint(); final int index = nativeAddTile(textures[0], lods.length, tile.getMaxLodDistance(), position.x, position.y, position.z, center.x, center.y, center.z); if (index >= 0) { for (int x = 0; x < lods.length; x++) { nativeAddLod(index, lods[x].getVertexBuffer(), lods[x].getTextureBuffer(), lods[x].getIndexBuffer(), lods[x].getColorBuffer(), lods[x].getIndexCount(), lods[x].getFixedPoint()); } if (isSkybox) { nativeSetSkybox(index); } for( int i = 1; i < textures.length; ++i ) { nativeAddTextureLod( index, i, textures[i]); } } } public void registerSkybox(int texture, Grid mesh, Vector3 position, Vector3 centerPoint) { } public void draw(boolean useTexture, boolean useColor) { nativeRender(mCameraPosition.x, mCameraPosition.y, mCameraPosition.z, mLookAtPosition.x, mLookAtPosition.y, mLookAtPosition.z, useTexture, useColor, mCameraDirty); mCameraDirty = false; } private static native void nativeReset(); private static native int nativeAddTile(int texture, int lodCount, float maxLodDistance, float x, float y, float z, float centerX, float centerY, float centerZ); private static native void nativeAddLod(int index, int vertexBuffer, int textureBuffer, int indexBuffer, int colorBuffer, int indexCount, boolean useFixedPoint); private static native void nativeSetSkybox(int index); private static native void nativeRender(float cameraX, float cameraY, float cameraZ, float lookAtX, float lookAtY, float lookAtZ, boolean useTexture, boolean useColor, boolean cameraDirty); private static native void nativeAddTextureLod(int tileIndex, int lod, int textureName); }
Java
/* * 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.android.heightmapprofiler; import android.opengl.GLSurfaceView; import com.android.heightmapprofiler.SimpleGLRenderer; import com.android.heightmapprofiler.R; import android.app.Activity; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.KeyEvent; import android.view.MotionEvent; // The main entry point for the actual landscape rendering test. // This class pulls options from the preferences set in the MainMenu // activity and builds the landscape accordingly. public class HeightMapTest extends Activity { private GLSurfaceView mGLSurfaceView; private SimpleGLRenderer mSimpleRenderer; private Game mGame; private Thread mGameThread; private float mLastScreenX; private float mLastScreenY; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mGLSurfaceView = new GLSurfaceView(this); mGLSurfaceView.setEGLConfigChooser(true); mSimpleRenderer = new SimpleGLRenderer(this); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); final boolean runGame = prefs.getBoolean("runsim", true); final boolean bigWorld = prefs.getBoolean("bigworld", true); final boolean skybox = prefs.getBoolean("skybox", true); final boolean texture = prefs.getBoolean("texture", true); final boolean vertexColors = prefs.getBoolean("colors", true); final boolean useTextureLods = prefs.getBoolean("lodTexture", true); final boolean textureMips = prefs.getBoolean("textureMips", true); final boolean useColorTextureLods = prefs.getBoolean("lodTextureColored", false ); final int maxTextureSize = Integer.parseInt(prefs.getString("maxTextureSize", "512")); final String textureFilter = prefs.getString("textureFiltering", "bilinear"); final boolean useLods = prefs.getBoolean("lod", true); final int complexity = Integer.parseInt(prefs.getString("complexity", "24")); final boolean useFixedPoint = prefs.getBoolean("fixed", false); final boolean useVbos = prefs.getBoolean("vbo", true); final boolean useNdk = prefs.getBoolean("ndk", false); BitmapDrawable heightMapDrawable = (BitmapDrawable)getResources().getDrawable(R.drawable.heightmap); Bitmap heightmap = heightMapDrawable.getBitmap(); Bitmap lightmap = null; if (vertexColors != false) { BitmapDrawable lightMapDrawable = (BitmapDrawable)getResources().getDrawable(R.drawable.lightmap); lightmap = lightMapDrawable.getBitmap(); } LandTileMap tileMap = null; if (bigWorld) { final int tilesX = 4; final int tilesY = 4; tileMap = new LandTileMap(tilesX, tilesY, heightmap, lightmap, vertexColors, texture, useLods, complexity, useFixedPoint); } else { tileMap = new LandTileMap(1, 1, heightmap, lightmap, vertexColors, texture, useLods, complexity, useFixedPoint); } if (skybox) { BitmapDrawable skyboxDrawable = (BitmapDrawable)getResources().getDrawable(R.drawable.skybox); Bitmap skyboxBitmap = skyboxDrawable.getBitmap(); tileMap.setupSkybox(skyboxBitmap, useFixedPoint); } if (useNdk) { NativeRenderer renderer = new NativeRenderer(); tileMap.setNativeRenderer(renderer); mSimpleRenderer.setNativeRenderer(renderer); } ProfileRecorder.sSingleton.resetAll(); mSimpleRenderer.setUseHardwareBuffers(useVbos); if (texture) { mSimpleRenderer.setTiles(tileMap, R.drawable.road_texture, R.drawable.skybox_texture); mSimpleRenderer.setUseTextureLods( useTextureLods, textureMips ); mSimpleRenderer.setColorTextureLods( useColorTextureLods ); mSimpleRenderer.setMaxTextureSize(maxTextureSize); if (textureFilter == "nearest") { mSimpleRenderer.setTextureFilter(SimpleGLRenderer.FILTER_NEAREST_NEIGHBOR); } else if (textureFilter == "trilinear") { mSimpleRenderer.setTextureFilter(SimpleGLRenderer.FILTER_TRILINEAR); } else { mSimpleRenderer.setTextureFilter(SimpleGLRenderer.FILTER_BILINEAR); } } else { mSimpleRenderer.setTiles(tileMap, 0, 0); } mGLSurfaceView.setRenderer(mSimpleRenderer); setContentView(mGLSurfaceView); if (runGame) { mGame = new Game(mSimpleRenderer, tileMap); mGameThread = new Thread(mGame); mGameThread.start(); } } @Override protected void onPause() { super.onPause(); mGLSurfaceView.onPause(); if (mGame != null) { mGame.pause(); } } @Override protected void onResume() { super.onResume(); mGLSurfaceView.onResume(); if (mGame != null) { mGame.resume(); } } @Override public boolean onTrackballEvent(MotionEvent event) { if (mGame != null) { mGame.rotate(event.getRawX(), -event.getRawY()); } return true; } @Override public boolean onTouchEvent(MotionEvent event) { if (mGame != null) { if (event.getAction() == MotionEvent.ACTION_DOWN) { mGame.move(1.0f); } else if (event.getAction() == MotionEvent.ACTION_MOVE) { float xDelta = event.getX() - mLastScreenX; float yDelta = event.getY() - mLastScreenY; mGame.move(1.0f); // Scale the values we got down to make control usable. // A real game would probably figure out scale factors based // on the size of the screen rather than hard-coded constants // like this. mGame.rotate(xDelta * 0.01f, -yDelta * 0.005f); } } mLastScreenX = event.getX(); mLastScreenY = event.getY(); try { Thread.sleep(16); } catch (InterruptedException e) { // TODO Auto-generated catch block } return true; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (mGame != null) { final float speed = 1.0f; switch (keyCode) { case KeyEvent.KEYCODE_DPAD_DOWN: mGame.rotate(0.0f, -speed); return true; case KeyEvent.KEYCODE_DPAD_LEFT: mGame.rotate(-speed, 0.0f); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: mGame.rotate(speed, 0.0f); return true; case KeyEvent.KEYCODE_DPAD_UP: mGame.rotate(0.0f, speed); return true; } } return super.onKeyDown(keyCode, event); } }
Java
/* * 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.android.heightmapprofiler; import java.io.IOException; import java.io.InputStream; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.opengl.GLSurfaceView; import android.opengl.GLU; import android.opengl.GLUtils; import android.util.Log; /** * An OpenGL ES renderer based on the GLSurfaceView rendering framework. This * class is responsible for drawing a list of renderables to the screen every * frame. It also manages loading of textures and (when VBOs are used) the * allocation of vertex buffer objects. */ public class SimpleGLRenderer implements GLSurfaceView.Renderer { // Texture filtering modes. public final static int FILTER_NEAREST_NEIGHBOR = 0; public final static int FILTER_BILINEAR = 1; public final static int FILTER_TRILINEAR = 2; // Specifies the format our textures should be converted to upon load. private static BitmapFactory.Options sBitmapOptions = new BitmapFactory.Options(); // Pre-allocated arrays to use at runtime so that allocation during the // test can be avoided. private int[] mTextureNameWorkspace; // A reference to the application context. private Context mContext; private LandTileMap mTiles; private int mTextureResource; private int mTextureResource2; private int mTextureId2; private Vector3 mCameraPosition = new Vector3(); private Vector3 mLookAtPosition = new Vector3(); private Object mCameraLock = new Object(); private boolean mCameraDirty; private NativeRenderer mNativeRenderer; // Determines the use of vertex buffer objects. private boolean mUseHardwareBuffers; private boolean mUseTextureLods = false; private boolean mUseHardwareMips = false; boolean mColorTextureLods = false; private int mTextureFilter = FILTER_BILINEAR; private int mMaxTextureSize = 0; public SimpleGLRenderer(Context context) { // Pre-allocate and store these objects so we can use them at runtime // without allocating memory mid-frame. mTextureNameWorkspace = new int[1]; // Set our bitmaps to 16-bit, 565 format. sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565; mContext = context; mUseHardwareBuffers = true; } public void setTiles(LandTileMap tiles, int textureResource, int textureResource2) { mTextureResource = textureResource; mTextureResource2 = textureResource2; mTiles = tiles; } /** Draws the landscape. */ public void onDrawFrame(GL10 gl) { ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_FRAME); ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_FRAME); if (mTiles != null) { // Clear the screen. Note that a real application probably would only clear the depth buffer // (or maybe not even that). if (mNativeRenderer == null) { gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); } // If the camera has moved since the last frame, rebuild our projection matrix. if (mCameraDirty){ synchronized (mCameraLock) { if (mNativeRenderer != null) { mNativeRenderer.setCamera(mCameraPosition, mLookAtPosition); } else { gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); GLU.gluLookAt(gl, mCameraPosition.x, mCameraPosition.y, mCameraPosition.z, mLookAtPosition.x, mLookAtPosition.y, mLookAtPosition.z, 0.0f, 1.0f, 0.0f); } mCameraDirty = false; } } ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_DRAW); // Draw the landscape. mTiles.draw(gl, mCameraPosition); ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_DRAW); } ProfileRecorder.sSingleton.endFrame(); } /* Called when the size of the window changes. */ public void onSurfaceChanged(GL10 gl, int width, int height) { gl.glViewport(0, 0, width, height); /* * Set our projection matrix. This doesn't have to be done each time we * draw, but usually a new projection needs to be set when the viewport * is resized. */ float ratio = (float)width / height; gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); GLU.gluPerspective(gl, 60.0f, ratio, 2.0f, 3000.0f); mCameraDirty = true; } public void setCameraPosition(float x, float y, float z) { synchronized (mCameraLock) { mCameraPosition.set(x, y, z); mCameraDirty = true; } } public void setCameraLookAtPosition(float x, float y, float z) { synchronized (mCameraLock) { mLookAtPosition.set(x, y, z); mCameraDirty = true; } } public void setUseHardwareBuffers(boolean vbos) { mUseHardwareBuffers = vbos; } /** * Called to turn on Levels of Detail option for rendering textures * * @param mUseTextureLods */ public void setUseTextureLods(boolean useTextureLods, boolean useHardwareMips) { mUseTextureLods = useTextureLods; mUseHardwareMips = useHardwareMips; } /** * Turns on/off color the LOD bitmap textures based on their distance from view. * This feature is useful since it helps visualize the LOD being used while viewing the scene. * * @param colorTextureLods */ public void setColorTextureLods(boolean colorTextureLods) { this.mColorTextureLods = colorTextureLods; } public void setNativeRenderer(NativeRenderer render) { mNativeRenderer = render; } public void setMaxTextureSize(int maxTextureSize) { mMaxTextureSize = maxTextureSize; } public void setTextureFilter(int filter) { mTextureFilter = filter; } /** * Called whenever the surface is created. This happens at startup, and * may be called again at runtime if the device context is lost (the screen * goes to sleep, etc). This function must fill the contents of vram with * texture data and (when using VBOs) hardware vertex arrays. */ public void onSurfaceCreated(GL10 gl, EGLConfig config) { int[] textureNames = null; /* * Some one-time OpenGL initialization can be made here probably based * on features of this particular context */ gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); gl.glClearColor(0.5f, 0.5f, 0.5f, 1); gl.glDisable(GL10.GL_DITHER); gl.glDisable(GL10.GL_CULL_FACE); gl.glShadeModel(GL10.GL_SMOOTH); gl.glEnable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_TEXTURE_2D); // set up some fog. gl.glEnable(GL10.GL_FOG); gl.glFogf(GL10.GL_FOG_MODE, GL10.GL_LINEAR); float fogColor[] = { 0.5f, 0.5f, 0.5f, 1.0f }; gl.glFogfv(GL10.GL_FOG_COLOR, fogColor, 0); gl.glFogf(GL10.GL_FOG_DENSITY, 0.15f); gl.glFogf(GL10.GL_FOG_START, 800.0f); gl.glFogf(GL10.GL_FOG_END, 2048.0f); gl.glHint(GL10.GL_FOG_HINT, GL10.GL_FASTEST); gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); // load textures and buffers here if (mUseHardwareBuffers && mTiles != null) { mTiles.generateHardwareBuffers(gl); } if (mTextureResource != 0) { textureNames = loadBitmap( mContext, gl, mTextureResource, mUseTextureLods, mUseHardwareMips ); } if (mTextureResource2 != 0) { mTextureId2 = loadBitmap(mContext, gl, mTextureResource2); } mTiles.setTextures(textureNames, mTextureId2); } /** * Loads a bitmap into OpenGL and sets up the common parameters for * 2D texture maps. */ protected int loadBitmap(Context context, GL10 gl, int resourceId) { int textureName = -1; InputStream is = context.getResources().openRawResource(resourceId); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions); } finally { try { is.close(); } catch (IOException e) { // Ignore. } } if (mMaxTextureSize > 0 && Math.max(bitmap.getWidth(), bitmap.getHeight()) != mMaxTextureSize) { // we're assuming all our textures are square. sue me. Bitmap tempBitmap = Bitmap.createScaledBitmap( bitmap, mMaxTextureSize, mMaxTextureSize, false ); bitmap.recycle(); bitmap = tempBitmap; } textureName = loadBitmapIntoOpenGL(context, gl, bitmap, false); bitmap.recycle(); return textureName; } /** * Loads a bitmap into OpenGL and sets up the common parameters for * 2D texture maps. * * @param context * @param resourceId * @param numLevelsOfDetail number of detail textures to generate * * @return a array of OpenGL texture names corresponding to the different levels of detail textures */ protected int[] loadBitmap(Context context, GL10 gl, int resourceId, boolean generateMips, boolean useHardwareMips ) { InputStream is = context.getResources().openRawResource(resourceId); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions); } finally { try { is.close(); } catch (IOException e) { // Ignore. } } if (mMaxTextureSize > 0 && Math.max(bitmap.getWidth(), bitmap.getHeight()) != mMaxTextureSize) { // we're assuming all our textures are square. sue me. Bitmap tempBitmap = Bitmap.createScaledBitmap( bitmap, mMaxTextureSize, mMaxTextureSize, false ); bitmap.recycle(); bitmap = tempBitmap; } final int minSide = Math.min(bitmap.getWidth(), bitmap.getHeight()); int numLevelsOfDetail = 1; if (generateMips) { for (int side = minSide / 2; side > 0; side /= 2) { numLevelsOfDetail++; } } int textureNames[]; if (generateMips && !useHardwareMips) { textureNames = new int[numLevelsOfDetail]; } else { textureNames = new int[1]; } textureNames[0] = loadBitmapIntoOpenGL(context, gl, bitmap, useHardwareMips); // Scale down base bitmap by powers of two to create lower resolution textures for( int i = 1; i < numLevelsOfDetail; ++i ) { int scale = (int)Math.pow(2, i); int dstWidth = bitmap.getWidth() / scale; int dstHeight = bitmap.getHeight() / scale; Bitmap tempBitmap = Bitmap.createScaledBitmap( bitmap, dstWidth, dstHeight, false ); // Set each LOD level to a different color to help visualization if( mColorTextureLods ) { int color = 0; switch( (int)(i % 4) ) { case 1: color = Color.RED; break; case 2: color = Color.YELLOW; break; case 3: color = Color.BLUE; break; } tempBitmap.eraseColor( color ); } if (!useHardwareMips) { textureNames[i] = loadBitmapIntoOpenGL( context, gl, tempBitmap, false); } else { addHardwareMipmap(gl, textureNames[0], tempBitmap, i ); } tempBitmap.recycle(); } bitmap.recycle(); return textureNames; } protected void addHardwareMipmap(GL10 gl, int textureName, Bitmap bitmap, int level) { gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, level, bitmap, 0); } /** * Loads a bitmap into OpenGL and sets up the common parameters for * 2D texture maps. * * @return OpenGL texture entry id */ protected int loadBitmapIntoOpenGL(Context context, GL10 gl, Bitmap bitmap, boolean useMipmaps) { int textureName = -1; if (context != null && gl != null) { gl.glGenTextures(1, mTextureNameWorkspace, 0); textureName = mTextureNameWorkspace[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName); if (useMipmaps) { if (mTextureFilter == FILTER_TRILINEAR) { gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR_MIPMAP_LINEAR); } else { gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR_MIPMAP_NEAREST); } } else { if (mTextureFilter == FILTER_NEAREST_NEIGHBOR) { gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); } else { gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR); } } if (mTextureFilter == FILTER_NEAREST_NEIGHBOR) { gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST); } else { gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); } gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); int error = gl.glGetError(); if (error != GL10.GL_NO_ERROR) { Log.e("SimpleGLRenderer", "Texture Load GLError: " + error); } } return textureName; } }
Java
/* * 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.android.heightmapprofiler; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.CharBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; /** * A 2D rectangular mesh. Can be drawn textured or untextured. * This version is modified from the original Grid.java (found in * the SpriteText package in the APIDemos Android sample) to support hardware * vertex buffers. */ class Grid { private FloatBuffer mFloatVertexBuffer; private FloatBuffer mFloatTexCoordBuffer; private FloatBuffer mFloatColorBuffer; private IntBuffer mFixedVertexBuffer; private IntBuffer mFixedTexCoordBuffer; private IntBuffer mFixedColorBuffer; private CharBuffer mIndexBuffer; private Buffer mVertexBuffer; private Buffer mTexCoordBuffer; private Buffer mColorBuffer; private int mCoordinateSize; private int mCoordinateType; private int mW; private int mH; private int mIndexCount; private boolean mUseHardwareBuffers; private int mVertBufferIndex; private int mIndexBufferIndex; private int mTextureCoordBufferIndex; private int mColorBufferIndex; public Grid(int vertsAcross, int vertsDown, boolean useFixedPoint) { if (vertsAcross < 0 || vertsAcross >= 65536) { throw new IllegalArgumentException("vertsAcross"); } if (vertsDown < 0 || vertsDown >= 65536) { throw new IllegalArgumentException("vertsDown"); } if (vertsAcross * vertsDown >= 65536) { throw new IllegalArgumentException("vertsAcross * vertsDown >= 65536"); } mUseHardwareBuffers = false; mW = vertsAcross; mH = vertsDown; int size = vertsAcross * vertsDown; final int FLOAT_SIZE = 4; final int FIXED_SIZE = 4; final int CHAR_SIZE = 2; if (useFixedPoint) { mFixedVertexBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 3) .order(ByteOrder.nativeOrder()).asIntBuffer(); mFixedTexCoordBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 2) .order(ByteOrder.nativeOrder()).asIntBuffer(); mFixedColorBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 4) .order(ByteOrder.nativeOrder()).asIntBuffer(); mVertexBuffer = mFixedVertexBuffer; mTexCoordBuffer = mFixedTexCoordBuffer; mColorBuffer = mFixedColorBuffer; mCoordinateSize = FIXED_SIZE; mCoordinateType = GL10.GL_FIXED; } else { mFloatVertexBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 3) .order(ByteOrder.nativeOrder()).asFloatBuffer(); mFloatTexCoordBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2) .order(ByteOrder.nativeOrder()).asFloatBuffer(); mFloatColorBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 4) .order(ByteOrder.nativeOrder()).asFloatBuffer(); mVertexBuffer = mFloatVertexBuffer; mTexCoordBuffer = mFloatTexCoordBuffer; mColorBuffer = mFloatColorBuffer; mCoordinateSize = FLOAT_SIZE; mCoordinateType = GL10.GL_FLOAT; } int quadW = mW - 1; int quadH = mH - 1; int quadCount = quadW * quadH; int indexCount = quadCount * 6; mIndexCount = indexCount; mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount) .order(ByteOrder.nativeOrder()).asCharBuffer(); /* * Initialize triangle list mesh. * * [0]-----[ 1] ... * | / | * | / | * | / | * [w]-----[w+1] ... * | | * */ { int i = 0; for (int y = 0; y < quadH; y++) { for (int x = 0; x < quadW; x++) { char a = (char) (y * mW + x); char b = (char) (y * mW + x + 1); char c = (char) ((y + 1) * mW + x); char d = (char) ((y + 1) * mW + x + 1); mIndexBuffer.put(i++, a); mIndexBuffer.put(i++, b); mIndexBuffer.put(i++, c); mIndexBuffer.put(i++, b); mIndexBuffer.put(i++, c); mIndexBuffer.put(i++, d); } } } mVertBufferIndex = 0; } void set(int i, int j, float x, float y, float z, float u, float v, float[] color) { if (i < 0 || i >= mW) { throw new IllegalArgumentException("i"); } if (j < 0 || j >= mH) { throw new IllegalArgumentException("j"); } final int index = mW * j + i; final int posIndex = index * 3; final int texIndex = index * 2; final int colorIndex = index * 4; if (mCoordinateType == GL10.GL_FLOAT) { mFloatVertexBuffer.put(posIndex, x); mFloatVertexBuffer.put(posIndex + 1, y); mFloatVertexBuffer.put(posIndex + 2, z); mFloatTexCoordBuffer.put(texIndex, u); mFloatTexCoordBuffer.put(texIndex + 1, v); if (color != null) { mFloatColorBuffer.put(colorIndex, color[0]); mFloatColorBuffer.put(colorIndex + 1, color[1]); mFloatColorBuffer.put(colorIndex + 2, color[2]); mFloatColorBuffer.put(colorIndex + 3, color[3]); } } else { mFixedVertexBuffer.put(posIndex, (int)(x * (1 << 16))); mFixedVertexBuffer.put(posIndex + 1, (int)(y * (1 << 16))); mFixedVertexBuffer.put(posIndex + 2, (int)(z * (1 << 16))); mFixedTexCoordBuffer.put(texIndex, (int)(u * (1 << 16))); mFixedTexCoordBuffer.put(texIndex + 1, (int)(v * (1 << 16))); if (color != null) { mFixedColorBuffer.put(colorIndex, (int)(color[0] * (1 << 16))); mFixedColorBuffer.put(colorIndex + 1, (int)(color[1] * (1 << 16))); mFixedColorBuffer.put(colorIndex + 2, (int)(color[2] * (1 << 16))); mFixedColorBuffer.put(colorIndex + 3, (int)(color[3] * (1 << 16))); } } } public static void beginDrawing(GL10 gl, boolean useTexture, boolean useColor) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); if (useTexture) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glEnable(GL10.GL_TEXTURE_2D); } else { gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glDisable(GL10.GL_TEXTURE_2D); } if (useColor) { gl.glEnableClientState(GL10.GL_COLOR_ARRAY); } else { gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } } public void draw(GL10 gl, boolean useTexture, boolean useColor) { if (!mUseHardwareBuffers) { gl.glVertexPointer(3, mCoordinateType, 0, mVertexBuffer); if (useTexture) { gl.glTexCoordPointer(2, mCoordinateType, 0, mTexCoordBuffer); } if (useColor) { gl.glColorPointer(4, mCoordinateType, 0, mColorBuffer); } gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); } else { GL11 gl11 = (GL11)gl; // draw using hardware buffers gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex); gl11.glVertexPointer(3, mCoordinateType, 0, 0); if (useTexture) { gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTextureCoordBufferIndex); gl11.glTexCoordPointer(2, mCoordinateType, 0, 0); } if (useColor) { gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mColorBufferIndex); gl11.glColorPointer(4, mCoordinateType, 0, 0); } gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex); gl11.glDrawElements(GL11.GL_TRIANGLES, mIndexCount, GL11.GL_UNSIGNED_SHORT, 0); gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0); gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); } } public static void endDrawing(GL10 gl) { gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } public boolean usingHardwareBuffers() { return mUseHardwareBuffers; } /** * When the OpenGL ES device is lost, GL handles become invalidated. * In that case, we just want to "forget" the old handles (without * explicitly deleting them) and make new ones. */ public void invalidateHardwareBuffers() { mVertBufferIndex = 0; mIndexBufferIndex = 0; mTextureCoordBufferIndex = 0; mColorBufferIndex = 0; mUseHardwareBuffers = false; } /** * Deletes the hardware buffers allocated by this object (if any). */ public void releaseHardwareBuffers(GL10 gl) { if (mUseHardwareBuffers) { if (gl instanceof GL11) { GL11 gl11 = (GL11)gl; int[] buffer = new int[1]; buffer[0] = mVertBufferIndex; gl11.glDeleteBuffers(1, buffer, 0); buffer[0] = mTextureCoordBufferIndex; gl11.glDeleteBuffers(1, buffer, 0); buffer[0] = mColorBufferIndex; gl11.glDeleteBuffers(1, buffer, 0); buffer[0] = mIndexBufferIndex; gl11.glDeleteBuffers(1, buffer, 0); } invalidateHardwareBuffers(); } } /** * Allocates hardware buffers on the graphics card and fills them with * data if a buffer has not already been previously allocated. Note that * this function uses the GL_OES_vertex_buffer_object extension, which is * not guaranteed to be supported on every device. * @param gl A pointer to the OpenGL ES context. */ public void generateHardwareBuffers(GL10 gl) { if (!mUseHardwareBuffers) { if (gl instanceof GL11) { GL11 gl11 = (GL11)gl; int[] buffer = new int[1]; // Allocate and fill the vertex buffer. gl11.glGenBuffers(1, buffer, 0); mVertBufferIndex = buffer[0]; gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex); final int vertexSize = mVertexBuffer.capacity() * mCoordinateSize; gl11.glBufferData(GL11.GL_ARRAY_BUFFER, vertexSize, mVertexBuffer, GL11.GL_STATIC_DRAW); // Allocate and fill the texture coordinate buffer. gl11.glGenBuffers(1, buffer, 0); mTextureCoordBufferIndex = buffer[0]; gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTextureCoordBufferIndex); final int texCoordSize = mTexCoordBuffer.capacity() * mCoordinateSize; gl11.glBufferData(GL11.GL_ARRAY_BUFFER, texCoordSize, mTexCoordBuffer, GL11.GL_STATIC_DRAW); // Allocate and fill the color buffer. gl11.glGenBuffers(1, buffer, 0); mColorBufferIndex = buffer[0]; gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mColorBufferIndex); final int colorSize = mColorBuffer.capacity() * mCoordinateSize; gl11.glBufferData(GL11.GL_ARRAY_BUFFER, colorSize, mColorBuffer, GL11.GL_STATIC_DRAW); // Unbind the array buffer. gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0); // Allocate and fill the index buffer. gl11.glGenBuffers(1, buffer, 0); mIndexBufferIndex = buffer[0]; gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex); // A char is 2 bytes. final int indexSize = mIndexBuffer.capacity() * 2; gl11.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, indexSize, mIndexBuffer, GL11.GL_STATIC_DRAW); // Unbind the element array buffer. gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); mUseHardwareBuffers = true; assert mVertBufferIndex != 0; assert mTextureCoordBufferIndex != 0; assert mIndexBufferIndex != 0; assert gl11.glGetError() == 0; } } } // These functions exposed to patch Grid info into native code. public final int getVertexBuffer() { return mVertBufferIndex; } public final int getTextureBuffer() { return mTextureCoordBufferIndex; } public final int getIndexBuffer() { return mIndexBufferIndex; } public final int getColorBuffer() { return mColorBufferIndex; } public final int getIndexCount() { return mIndexCount; } public boolean getFixedPoint() { return (mCoordinateType == GL10.GL_FIXED); } public long getVertexCount() { return mW * mH; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.downloader; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import org.apache.http.impl.client.DefaultHttpClient; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import java.security.MessageDigest; import android.util.Log; import android.util.Xml; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.security.NoSuchAlgorithmException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; public class DownloaderActivity extends Activity { /** * Checks if data has been downloaded. If so, returns true. If not, * starts an activity to download the data and returns false. If this * function returns false the caller should immediately return from its * onCreate method. The calling activity will later be restarted * (using a copy of its original intent) once the data download completes. * @param activity The calling activity. * @param customText A text string that is displayed in the downloader UI. * @param fileConfigUrl The URL of the download configuration URL. * @param configVersion The version of the configuration file. * @param dataPath The directory on the device where we want to store the * data. * @param userAgent The user agent string to use when fetching URLs. * @return true if the data has already been downloaded successfully, or * false if the data needs to be downloaded. */ public static boolean ensureDownloaded(Activity activity, String customText, String fileConfigUrl, String configVersion, String dataPath, String userAgent) { File dest = new File(dataPath); if (dest.exists()) { // Check version if (versionMatches(dest, configVersion)) { Log.i(LOG_TAG, "Versions match, no need to download."); return true; } } Intent intent = PreconditionActivityHelper.createPreconditionIntent( activity, DownloaderActivity.class); intent.putExtra(EXTRA_CUSTOM_TEXT, customText); intent.putExtra(EXTRA_FILE_CONFIG_URL, fileConfigUrl); intent.putExtra(EXTRA_CONFIG_VERSION, configVersion); intent.putExtra(EXTRA_DATA_PATH, dataPath); intent.putExtra(EXTRA_USER_AGENT, userAgent); PreconditionActivityHelper.startPreconditionActivityAndFinish( activity, intent); return false; } /** * Delete a directory and all its descendants. * @param directory The directory to delete * @return true if the directory was deleted successfully. */ public static boolean deleteData(String directory) { return deleteTree(new File(directory), true); } private static boolean deleteTree(File base, boolean deleteBase) { boolean result = true; if (base.isDirectory()) { for (File child : base.listFiles()) { result &= deleteTree(child, true); } } if (deleteBase) { result &= base.delete(); } return result; } private static boolean versionMatches(File dest, String expectedVersion) { Config config = getLocalConfig(dest, LOCAL_CONFIG_FILE); if (config != null) { return config.version.equals(expectedVersion); } return false; } private static Config getLocalConfig(File destPath, String configFilename) { File configPath = new File(destPath, configFilename); FileInputStream is; try { is = new FileInputStream(configPath); } catch (FileNotFoundException e) { return null; } try { Config config = ConfigHandler.parse(is); return config; } catch (Exception e) { Log.e(LOG_TAG, "Unable to read local config file", e); return null; } finally { quietClose(is); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.downloader); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.downloader_title); ((TextView) findViewById(R.id.customText)).setText( intent.getStringExtra(EXTRA_CUSTOM_TEXT)); mProgress = (TextView) findViewById(R.id.progress); mTimeRemaining = (TextView) findViewById(R.id.time_remaining); Button button = (Button) findViewById(R.id.cancel); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if (mDownloadThread != null) { mSuppressErrorMessages = true; mDownloadThread.interrupt(); } } }); startDownloadThread(); } private void startDownloadThread() { mSuppressErrorMessages = false; mProgress.setText(""); mTimeRemaining.setText(""); mDownloadThread = new Thread(new Downloader(), "Downloader"); mDownloadThread.setPriority(Thread.NORM_PRIORITY - 1); mDownloadThread.start(); } @Override protected void onResume() { super.onResume(); } @Override protected void onDestroy() { super.onDestroy(); mSuppressErrorMessages = true; mDownloadThread.interrupt(); try { mDownloadThread.join(); } catch (InterruptedException e) { // Don't care. } } private void onDownloadSucceeded() { Log.i(LOG_TAG, "Download succeeded"); PreconditionActivityHelper.startOriginalActivityAndFinish(this); } private void onDownloadFailed(String reason) { Log.e(LOG_TAG, "Download stopped: " + reason); String shortReason; int index = reason.indexOf('\n'); if (index >= 0) { shortReason = reason.substring(0, index); } else { shortReason = reason; } AlertDialog alert = new Builder(this).create(); alert.setTitle(R.string.download_activity_download_stopped); if (!mSuppressErrorMessages) { alert.setMessage(shortReason); } alert.setButton(getString(R.string.download_activity_retry), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { startDownloadThread(); } }); alert.setButton2(getString(R.string.download_activity_quit), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); try { alert.show(); } catch (WindowManager.BadTokenException e) { // Happens when the Back button is used to exit the activity. // ignore. } } private void onReportProgress(int progress) { mProgress.setText(mPercentFormat.format(progress / 10000.0)); long now = SystemClock.elapsedRealtime(); if (mStartTime == 0) { mStartTime = now; } long delta = now - mStartTime; String timeRemaining = getString(R.string.download_activity_time_remaining_unknown); if ((delta > 3 * MS_PER_SECOND) && (progress > 100)) { long totalTime = 10000 * delta / progress; long timeLeft = Math.max(0L, totalTime - delta); if (timeLeft > MS_PER_DAY) { timeRemaining = Long.toString( (timeLeft + MS_PER_DAY - 1) / MS_PER_DAY) + " " + getString(R.string.download_activity_time_remaining_days); } else if (timeLeft > MS_PER_HOUR) { timeRemaining = Long.toString( (timeLeft + MS_PER_HOUR - 1) / MS_PER_HOUR) + " " + getString(R.string.download_activity_time_remaining_hours); } else if (timeLeft > MS_PER_MINUTE) { timeRemaining = Long.toString( (timeLeft + MS_PER_MINUTE - 1) / MS_PER_MINUTE) + " " + getString(R.string.download_activity_time_remaining_minutes); } else { timeRemaining = Long.toString( (timeLeft + MS_PER_SECOND - 1) / MS_PER_SECOND) + " " + getString(R.string.download_activity_time_remaining_seconds); } } mTimeRemaining.setText(timeRemaining); } private void onReportVerifying() { mProgress.setText(getString(R.string.download_activity_verifying)); mTimeRemaining.setText(""); } private static void quietClose(InputStream is) { try { if (is != null) { is.close(); } } catch (IOException e) { // Don't care. } } private static void quietClose(OutputStream os) { try { if (os != null) { os.close(); } } catch (IOException e) { // Don't care. } } private static class Config { long getSize() { long result = 0; for(File file : mFiles) { result += file.getSize(); } return result; } static class File { public File(String src, String dest, String md5, long size) { if (src != null) { this.mParts.add(new Part(src, md5, size)); } this.dest = dest; } static class Part { Part(String src, String md5, long size) { this.src = src; this.md5 = md5; this.size = size; } String src; String md5; long size; } ArrayList<Part> mParts = new ArrayList<Part>(); String dest; long getSize() { long result = 0; for(Part part : mParts) { if (part.size > 0) { result += part.size; } } return result; } } String version; ArrayList<File> mFiles = new ArrayList<File>(); } /** * <config version=""> * <file src="http:..." dest ="b.x" /> * <file dest="b.x"> * <part src="http:..." /> * ... * ... * </config> * */ private static class ConfigHandler extends DefaultHandler { public static Config parse(InputStream is) throws SAXException, UnsupportedEncodingException, IOException { ConfigHandler handler = new ConfigHandler(); Xml.parse(is, Xml.findEncodingByName("UTF-8"), handler); return handler.mConfig; } private ConfigHandler() { mConfig = new Config(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (localName.equals("config")) { mConfig.version = getRequiredString(attributes, "version"); } else if (localName.equals("file")) { String src = attributes.getValue("", "src"); String dest = getRequiredString(attributes, "dest"); String md5 = attributes.getValue("", "md5"); long size = getLong(attributes, "size", -1); mConfig.mFiles.add(new Config.File(src, dest, md5, size)); } else if (localName.equals("part")) { String src = getRequiredString(attributes, "src"); String md5 = attributes.getValue("", "md5"); long size = getLong(attributes, "size", -1); int length = mConfig.mFiles.size(); if (length > 0) { mConfig.mFiles.get(length-1).mParts.add( new Config.File.Part(src, md5, size)); } } } private static String getRequiredString(Attributes attributes, String localName) throws SAXException { String result = attributes.getValue("", localName); if (result == null) { throw new SAXException("Expected attribute " + localName); } return result; } private static long getLong(Attributes attributes, String localName, long defaultValue) { String value = attributes.getValue("", localName); if (value == null) { return defaultValue; } else { return Long.parseLong(value); } } public Config mConfig; } private class DownloaderException extends Exception { public DownloaderException(String reason) { super(reason); } } private class Downloader implements Runnable { public void run() { Intent intent = getIntent(); mFileConfigUrl = intent.getStringExtra(EXTRA_FILE_CONFIG_URL); mConfigVersion = intent.getStringExtra(EXTRA_CONFIG_VERSION); mDataPath = intent.getStringExtra(EXTRA_DATA_PATH); mUserAgent = intent.getStringExtra(EXTRA_USER_AGENT); mDataDir = new File(mDataPath); try { // Download files. mHttpClient = new DefaultHttpClient(); Config config = getConfig(); filter(config); persistantDownload(config); verify(config); cleanup(); reportSuccess(); } catch (Exception e) { reportFailure(e.toString() + "\n" + Log.getStackTraceString(e)); } } private void persistantDownload(Config config) throws ClientProtocolException, DownloaderException, IOException { while(true) { try { download(config); break; } catch(java.net.SocketException e) { if (mSuppressErrorMessages) { throw e; } } catch(java.net.SocketTimeoutException e) { if (mSuppressErrorMessages) { throw e; } } Log.i(LOG_TAG, "Network connectivity issue, retrying."); } } private void filter(Config config) throws IOException, DownloaderException { File filteredFile = new File(mDataDir, LOCAL_FILTERED_FILE); if (filteredFile.exists()) { return; } File localConfigFile = new File(mDataDir, LOCAL_CONFIG_FILE_TEMP); HashSet<String> keepSet = new HashSet<String>(); keepSet.add(localConfigFile.getCanonicalPath()); HashMap<String, Config.File> fileMap = new HashMap<String, Config.File>(); for(Config.File file : config.mFiles) { String canonicalPath = new File(mDataDir, file.dest).getCanonicalPath(); fileMap.put(canonicalPath, file); } recursiveFilter(mDataDir, fileMap, keepSet, false); touch(filteredFile); } private void touch(File file) throws FileNotFoundException { FileOutputStream os = new FileOutputStream(file); quietClose(os); } private boolean recursiveFilter(File base, HashMap<String, Config.File> fileMap, HashSet<String> keepSet, boolean filterBase) throws IOException, DownloaderException { boolean result = true; if (base.isDirectory()) { for (File child : base.listFiles()) { result &= recursiveFilter(child, fileMap, keepSet, true); } } if (filterBase) { if (base.isDirectory()) { if (base.listFiles().length == 0) { result &= base.delete(); } } else { if (!shouldKeepFile(base, fileMap, keepSet)) { result &= base.delete(); } } } return result; } private boolean shouldKeepFile(File file, HashMap<String, Config.File> fileMap, HashSet<String> keepSet) throws IOException, DownloaderException { String canonicalPath = file.getCanonicalPath(); if (keepSet.contains(canonicalPath)) { return true; } Config.File configFile = fileMap.get(canonicalPath); if (configFile == null) { return false; } return verifyFile(configFile, false); } private void reportSuccess() { mHandler.sendMessage( Message.obtain(mHandler, MSG_DOWNLOAD_SUCCEEDED)); } private void reportFailure(String reason) { mHandler.sendMessage( Message.obtain(mHandler, MSG_DOWNLOAD_FAILED, reason)); } private void reportProgress(int progress) { mHandler.sendMessage( Message.obtain(mHandler, MSG_REPORT_PROGRESS, progress, 0)); } private void reportVerifying() { mHandler.sendMessage( Message.obtain(mHandler, MSG_REPORT_VERIFYING)); } private Config getConfig() throws DownloaderException, ClientProtocolException, IOException, SAXException { Config config = null; if (mDataDir.exists()) { config = getLocalConfig(mDataDir, LOCAL_CONFIG_FILE_TEMP); if ((config == null) || !mConfigVersion.equals(config.version)) { if (config == null) { Log.i(LOG_TAG, "Couldn't find local config."); } else { Log.i(LOG_TAG, "Local version out of sync. Wanted " + mConfigVersion + " but have " + config.version); } config = null; } } else { Log.i(LOG_TAG, "Creating directory " + mDataPath); mDataDir.mkdirs(); mDataDir.mkdir(); if (!mDataDir.exists()) { throw new DownloaderException( "Could not create the directory " + mDataPath); } } if (config == null) { File localConfig = download(mFileConfigUrl, LOCAL_CONFIG_FILE_TEMP); InputStream is = new FileInputStream(localConfig); try { config = ConfigHandler.parse(is); } finally { quietClose(is); } if (! config.version.equals(mConfigVersion)) { throw new DownloaderException( "Configuration file version mismatch. Expected " + mConfigVersion + " received " + config.version); } } return config; } private void noisyDelete(File file) throws IOException { if (! file.delete() ) { throw new IOException("could not delete " + file); } } private void download(Config config) throws DownloaderException, ClientProtocolException, IOException { mDownloadedSize = 0; getSizes(config); Log.i(LOG_TAG, "Total bytes to download: " + mTotalExpectedSize); for(Config.File file : config.mFiles) { downloadFile(file); } } private void downloadFile(Config.File file) throws DownloaderException, FileNotFoundException, IOException, ClientProtocolException { boolean append = false; File dest = new File(mDataDir, file.dest); long bytesToSkip = 0; if (dest.exists() && dest.isFile()) { append = true; bytesToSkip = dest.length(); mDownloadedSize += bytesToSkip; } FileOutputStream os = null; long offsetOfCurrentPart = 0; try { for(Config.File.Part part : file.mParts) { // The part.size==0 check below allows us to download // zero-length files. if ((part.size > bytesToSkip) || (part.size == 0)) { MessageDigest digest = null; if (part.md5 != null) { digest = createDigest(); if (bytesToSkip > 0) { FileInputStream is = openInput(file.dest); try { is.skip(offsetOfCurrentPart); readIntoDigest(is, bytesToSkip, digest); } finally { quietClose(is); } } } if (os == null) { os = openOutput(file.dest, append); } downloadPart(part.src, os, bytesToSkip, part.size, digest); if (digest != null) { String hash = getHash(digest); if (!hash.equalsIgnoreCase(part.md5)) { Log.e(LOG_TAG, "web MD5 checksums don't match. " + part.src + "\nExpected " + part.md5 + "\n got " + hash); quietClose(os); dest.delete(); throw new DownloaderException( "Received bad data from web server"); } else { Log.i(LOG_TAG, "web MD5 checksum matches."); } } } bytesToSkip -= Math.min(bytesToSkip, part.size); offsetOfCurrentPart += part.size; } } finally { quietClose(os); } } private void cleanup() throws IOException { File filtered = new File(mDataDir, LOCAL_FILTERED_FILE); noisyDelete(filtered); File tempConfig = new File(mDataDir, LOCAL_CONFIG_FILE_TEMP); File realConfig = new File(mDataDir, LOCAL_CONFIG_FILE); tempConfig.renameTo(realConfig); } private void verify(Config config) throws DownloaderException, ClientProtocolException, IOException { Log.i(LOG_TAG, "Verifying..."); String failFiles = null; for(Config.File file : config.mFiles) { if (! verifyFile(file, true) ) { if (failFiles == null) { failFiles = file.dest; } else { failFiles += " " + file.dest; } } } if (failFiles != null) { throw new DownloaderException( "Possible bad SD-Card. MD5 sum incorrect for file(s) " + failFiles); } } private boolean verifyFile(Config.File file, boolean deleteInvalid) throws FileNotFoundException, DownloaderException, IOException { Log.i(LOG_TAG, "verifying " + file.dest); reportVerifying(); File dest = new File(mDataDir, file.dest); if (! dest.exists()) { Log.e(LOG_TAG, "File does not exist: " + dest.toString()); return false; } long fileSize = file.getSize(); long destLength = dest.length(); if (fileSize != destLength) { Log.e(LOG_TAG, "Length doesn't match. Expected " + fileSize + " got " + destLength); if (deleteInvalid) { dest.delete(); return false; } } FileInputStream is = new FileInputStream(dest); try { for(Config.File.Part part : file.mParts) { if (part.md5 == null) { continue; } MessageDigest digest = createDigest(); readIntoDigest(is, part.size, digest); String hash = getHash(digest); if (!hash.equalsIgnoreCase(part.md5)) { Log.e(LOG_TAG, "MD5 checksums don't match. " + part.src + " Expected " + part.md5 + " got " + hash); if (deleteInvalid) { quietClose(is); dest.delete(); } return false; } } } finally { quietClose(is); } return true; } private void readIntoDigest(FileInputStream is, long bytesToRead, MessageDigest digest) throws IOException { while(bytesToRead > 0) { int chunkSize = (int) Math.min(mFileIOBuffer.length, bytesToRead); int bytesRead = is.read(mFileIOBuffer, 0, chunkSize); if (bytesRead < 0) { break; } updateDigest(digest, bytesRead); bytesToRead -= bytesRead; } } private MessageDigest createDigest() throws DownloaderException { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new DownloaderException("Couldn't create MD5 digest"); } return digest; } private void updateDigest(MessageDigest digest, int bytesRead) { if (bytesRead == mFileIOBuffer.length) { digest.update(mFileIOBuffer); } else { // Work around an awkward API: Create a // new buffer with just the valid bytes byte[] temp = new byte[bytesRead]; System.arraycopy(mFileIOBuffer, 0, temp, 0, bytesRead); digest.update(temp); } } private String getHash(MessageDigest digest) { StringBuilder builder = new StringBuilder(); for(byte b : digest.digest()) { builder.append(Integer.toHexString((b >> 4) & 0xf)); builder.append(Integer.toHexString(b & 0xf)); } return builder.toString(); } /** * Ensure we have sizes for all the items. * @param config * @throws ClientProtocolException * @throws IOException * @throws DownloaderException */ private void getSizes(Config config) throws ClientProtocolException, IOException, DownloaderException { for (Config.File file : config.mFiles) { for(Config.File.Part part : file.mParts) { if (part.size < 0) { part.size = getSize(part.src); } } } mTotalExpectedSize = config.getSize(); } private long getSize(String url) throws ClientProtocolException, IOException { url = normalizeUrl(url); Log.i(LOG_TAG, "Head " + url); HttpHead httpGet = new HttpHead(url); HttpResponse response = mHttpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new IOException("Unexpected Http status code " + response.getStatusLine().getStatusCode()); } Header[] clHeaders = response.getHeaders("Content-Length"); if (clHeaders.length > 0) { Header header = clHeaders[0]; return Long.parseLong(header.getValue()); } return -1; } private String normalizeUrl(String url) throws MalformedURLException { return (new URL(new URL(mFileConfigUrl), url)).toString(); } private InputStream get(String url, long startOffset, long expectedLength) throws ClientProtocolException, IOException { url = normalizeUrl(url); Log.i(LOG_TAG, "Get " + url); mHttpGet = new HttpGet(url); int expectedStatusCode = HttpStatus.SC_OK; if (startOffset > 0) { String range = "bytes=" + startOffset + "-"; if (expectedLength >= 0) { range += expectedLength-1; } Log.i(LOG_TAG, "requesting byte range " + range); mHttpGet.addHeader("Range", range); expectedStatusCode = HttpStatus.SC_PARTIAL_CONTENT; } HttpResponse response = mHttpClient.execute(mHttpGet); long bytesToSkip = 0; int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != expectedStatusCode) { if ((statusCode == HttpStatus.SC_OK) && (expectedStatusCode == HttpStatus.SC_PARTIAL_CONTENT)) { Log.i(LOG_TAG, "Byte range request ignored"); bytesToSkip = startOffset; } else { throw new IOException("Unexpected Http status code " + statusCode + " expected " + expectedStatusCode); } } HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); if (bytesToSkip > 0) { is.skip(bytesToSkip); } return is; } private File download(String src, String dest) throws DownloaderException, ClientProtocolException, IOException { File destFile = new File(mDataDir, dest); FileOutputStream os = openOutput(dest, false); try { downloadPart(src, os, 0, -1, null); } finally { os.close(); } return destFile; } private void downloadPart(String src, FileOutputStream os, long startOffset, long expectedLength, MessageDigest digest) throws ClientProtocolException, IOException, DownloaderException { boolean lengthIsKnown = expectedLength >= 0; if (startOffset < 0) { throw new IllegalArgumentException("Negative startOffset:" + startOffset); } if (lengthIsKnown && (startOffset > expectedLength)) { throw new IllegalArgumentException( "startOffset > expectedLength" + startOffset + " " + expectedLength); } InputStream is = get(src, startOffset, expectedLength); try { long bytesRead = downloadStream(is, os, digest); if (lengthIsKnown) { long expectedBytesRead = expectedLength - startOffset; if (expectedBytesRead != bytesRead) { Log.e(LOG_TAG, "Bad file transfer from server: " + src + " Expected " + expectedBytesRead + " Received " + bytesRead); throw new DownloaderException( "Incorrect number of bytes received from server"); } } } finally { is.close(); mHttpGet = null; } } private FileOutputStream openOutput(String dest, boolean append) throws FileNotFoundException, DownloaderException { File destFile = new File(mDataDir, dest); File parent = destFile.getParentFile(); if (! parent.exists()) { parent.mkdirs(); } if (! parent.exists()) { throw new DownloaderException("Could not create directory " + parent.toString()); } FileOutputStream os = new FileOutputStream(destFile, append); return os; } private FileInputStream openInput(String src) throws FileNotFoundException, DownloaderException { File srcFile = new File(mDataDir, src); File parent = srcFile.getParentFile(); if (! parent.exists()) { parent.mkdirs(); } if (! parent.exists()) { throw new DownloaderException("Could not create directory " + parent.toString()); } return new FileInputStream(srcFile); } private long downloadStream(InputStream is, FileOutputStream os, MessageDigest digest) throws DownloaderException, IOException { long totalBytesRead = 0; while(true){ if (Thread.interrupted()) { Log.i(LOG_TAG, "downloader thread interrupted."); mHttpGet.abort(); throw new DownloaderException("Thread interrupted"); } int bytesRead = is.read(mFileIOBuffer); if (bytesRead < 0) { break; } if (digest != null) { updateDigest(digest, bytesRead); } totalBytesRead += bytesRead; os.write(mFileIOBuffer, 0, bytesRead); mDownloadedSize += bytesRead; int progress = (int) (Math.min(mTotalExpectedSize, mDownloadedSize * 10000 / Math.max(1, mTotalExpectedSize))); if (progress != mReportedProgress) { mReportedProgress = progress; reportProgress(progress); } } return totalBytesRead; } private DefaultHttpClient mHttpClient; private HttpGet mHttpGet; private String mFileConfigUrl; private String mConfigVersion; private String mDataPath; private File mDataDir; private String mUserAgent; private long mTotalExpectedSize; private long mDownloadedSize; private int mReportedProgress; private final static int CHUNK_SIZE = 32 * 1024; byte[] mFileIOBuffer = new byte[CHUNK_SIZE]; } private final static String LOG_TAG = "Downloader"; private TextView mProgress; private TextView mTimeRemaining; private final DecimalFormat mPercentFormat = new DecimalFormat("0.00 %"); private long mStartTime; private Thread mDownloadThread; private boolean mSuppressErrorMessages; private final static long MS_PER_SECOND = 1000; private final static long MS_PER_MINUTE = 60 * 1000; private final static long MS_PER_HOUR = 60 * 60 * 1000; private final static long MS_PER_DAY = 24 * 60 * 60 * 1000; private final static String LOCAL_CONFIG_FILE = ".downloadConfig"; private final static String LOCAL_CONFIG_FILE_TEMP = ".downloadConfig_temp"; private final static String LOCAL_FILTERED_FILE = ".downloadConfig_filtered"; private final static String EXTRA_CUSTOM_TEXT = "DownloaderActivity_custom_text"; private final static String EXTRA_FILE_CONFIG_URL = "DownloaderActivity_config_url"; private final static String EXTRA_CONFIG_VERSION = "DownloaderActivity_config_version"; private final static String EXTRA_DATA_PATH = "DownloaderActivity_data_path"; private final static String EXTRA_USER_AGENT = "DownloaderActivity_user_agent"; private final static int MSG_DOWNLOAD_SUCCEEDED = 0; private final static int MSG_DOWNLOAD_FAILED = 1; private final static int MSG_REPORT_PROGRESS = 2; private final static int MSG_REPORT_VERIFYING = 3; private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_DOWNLOAD_SUCCEEDED: onDownloadSucceeded(); break; case MSG_DOWNLOAD_FAILED: onDownloadFailed((String) msg.obj); break; case MSG_REPORT_PROGRESS: onReportProgress(msg.arg1); break; case MSG_REPORT_VERIFYING: onReportVerifying(); break; default: throw new IllegalArgumentException("Unknown message id " + msg.what); } } }; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.downloader; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class DownloaderTest extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (! DownloaderActivity.ensureDownloaded(this, getString(R.string.app_name), FILE_CONFIG_URL, CONFIG_VERSION, DATA_PATH, USER_AGENT)) { return; } setContentView(R.layout.main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { boolean handled = true; int id = item.getItemId(); if (id == R.id.menu_main_download_again) { downloadAgain(); } else { handled = false; } if (!handled) { handled = super.onOptionsItemSelected(item); } return handled; } private void downloadAgain() { DownloaderActivity.deleteData(DATA_PATH); startActivity(getIntent()); finish(); } /** * Fill this in with your own web server. */ private final static String FILE_CONFIG_URL = "http://example.com/download.config"; private final static String CONFIG_VERSION = "1.0"; private final static String DATA_PATH = "/sdcard/data/downloadTest"; private final static String USER_AGENT = "MyApp Downloader"; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.downloader; import android.app.Activity; import android.content.Intent; /** * Usage: * * Intent intent = PreconditionActivityHelper.createPreconditionIntent( * activity, WaitActivity.class); * // Optionally add extras to pass arguments to the intent * intent.putExtra(Utils.EXTRA_ACCOUNT, account); * PreconditionActivityHelper.startPreconditionActivityAndFinish(this, intent); * * // And in the wait activity: * PreconditionActivityHelper.startOriginalActivityAndFinish(this); * */ public class PreconditionActivityHelper { /** * Create a precondition activity intent. * @param activity the original activity * @param preconditionActivityClazz the precondition activity's class * @return an intent which will launch the precondition activity. */ public static Intent createPreconditionIntent(Activity activity, Class preconditionActivityClazz) { Intent newIntent = new Intent(); newIntent.setClass(activity, preconditionActivityClazz); newIntent.putExtra(EXTRA_WRAPPED_INTENT, activity.getIntent()); return newIntent; } /** * Start the precondition activity using a given intent, which should * have been created by calling createPreconditionIntent. * @param activity * @param intent */ public static void startPreconditionActivityAndFinish(Activity activity, Intent intent) { activity.startActivity(intent); activity.finish(); } /** * Start the original activity, and finish the precondition activity. * @param preconditionActivity */ public static void startOriginalActivityAndFinish( Activity preconditionActivity) { preconditionActivity.startActivity( (Intent) preconditionActivity.getIntent() .getParcelableExtra(EXTRA_WRAPPED_INTENT)); preconditionActivity.finish(); } static private final String EXTRA_WRAPPED_INTENT = "PreconditionActivityHelper_wrappedIntent"; }
Java
package com.google.android.webviewdemo; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; /** * Demonstrates how to embed a WebView in your activity. Also demonstrates how * to have javascript in the WebView call into the activity, and how the activity * can invoke javascript. * <p> * In this example, clicking on the android in the WebView will result in a call into * the activities code in {@link DemoJavaScriptInterface#clickOnAndroid()}. This code * will turn around and invoke javascript using the {@link WebView#loadUrl(String)} * method. * <p> * Obviously all of this could have been accomplished without calling into the activity * and then back into javascript, but this code is intended to show how to set up the * code paths for this sort of communication. * */ public class WebViewDemo extends Activity { private static final String LOG_TAG = "WebViewDemo"; private WebView mWebView; private Handler mHandler = new Handler(); @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mWebView = (WebView) findViewById(R.id.webview); WebSettings webSettings = mWebView.getSettings(); webSettings.setSavePassword(false); webSettings.setSaveFormData(false); webSettings.setJavaScriptEnabled(true); webSettings.setSupportZoom(false); mWebView.setWebChromeClient(new MyWebChromeClient()); mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo"); mWebView.loadUrl("file:///android_asset/demo.html"); } final class DemoJavaScriptInterface { DemoJavaScriptInterface() { } /** * This is not called on the UI thread. Post a runnable to invoke * loadUrl on the UI thread. */ public void clickOnAndroid() { mHandler.post(new Runnable() { public void run() { mWebView.loadUrl("javascript:wave()"); } }); } } /** * Provides a hook for calling "alert" from javascript. Useful for * debugging your javascript. */ final class MyWebChromeClient extends WebChromeClient { @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { Log.d(LOG_TAG, message); result.confirm(); return true; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import javax.microedition.khronos.opengles.GL10; import android.graphics.Paint; public class NumericSprite { public NumericSprite() { mText = ""; mLabelMaker = null; } public void initialize(GL10 gl, Paint paint) { int height = roundUpPower2((int) paint.getFontSpacing()); final float interDigitGaps = 9 * 1.0f; int width = roundUpPower2((int) (interDigitGaps + paint.measureText(sStrike))); mLabelMaker = new LabelMaker(true, width, height); mLabelMaker.initialize(gl); mLabelMaker.beginAdding(gl); for (int i = 0; i < 10; i++) { String digit = sStrike.substring(i, i+1); mLabelId[i] = mLabelMaker.add(gl, digit, paint); mWidth[i] = (int) Math.ceil(mLabelMaker.getWidth(i)); } mLabelMaker.endAdding(gl); } public void shutdown(GL10 gl) { mLabelMaker.shutdown(gl); mLabelMaker = null; } /** * Find the smallest power of two >= the input value. * (Doesn't work for negative numbers.) */ private int roundUpPower2(int x) { x = x - 1; x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >>16); return x + 1; } public void setValue(int value) { mText = format(value); } public void draw(GL10 gl, float x, float y, float viewWidth, float viewHeight) { int length = mText.length(); mLabelMaker.beginDrawing(gl, viewWidth, viewHeight); for(int i = 0; i < length; i++) { char c = mText.charAt(i); int digit = c - '0'; mLabelMaker.draw(gl, x, y, mLabelId[digit]); x += mWidth[digit]; } mLabelMaker.endDrawing(gl); } public float width() { float width = 0.0f; int length = mText.length(); for(int i = 0; i < length; i++) { char c = mText.charAt(i); width += mWidth[c - '0']; } return width; } private String format(int value) { return Integer.toString(value); } private LabelMaker mLabelMaker; private String mText; private int[] mWidth = new int[10]; private int[] mLabelId = new int[10]; private final static String sStrike = "0123456789"; }
Java
/* * Copyright (C) 2007 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.opengles.spritetext; import android.opengl.Matrix; import java.nio.FloatBuffer; import java.nio.IntBuffer; /** * A matrix stack, similar to OpenGL ES's internal matrix stack. */ public class MatrixStack { public MatrixStack() { commonInit(DEFAULT_MAX_DEPTH); } public MatrixStack(int maxDepth) { commonInit(maxDepth); } private void commonInit(int maxDepth) { mMatrix = new float[maxDepth * MATRIX_SIZE]; mTemp = new float[MATRIX_SIZE * 2]; glLoadIdentity(); } public void glFrustumf(float left, float right, float bottom, float top, float near, float far) { Matrix.frustumM(mMatrix, mTop, left, right, bottom, top, near, far); } public void glFrustumx(int left, int right, int bottom, int top, int near, int far) { glFrustumf(fixedToFloat(left),fixedToFloat(right), fixedToFloat(bottom), fixedToFloat(top), fixedToFloat(near), fixedToFloat(far)); } public void glLoadIdentity() { Matrix.setIdentityM(mMatrix, mTop); } public void glLoadMatrixf(float[] m, int offset) { System.arraycopy(m, offset, mMatrix, mTop, MATRIX_SIZE); } public void glLoadMatrixf(FloatBuffer m) { m.get(mMatrix, mTop, MATRIX_SIZE); } public void glLoadMatrixx(int[] m, int offset) { for(int i = 0; i < MATRIX_SIZE; i++) { mMatrix[mTop + i] = fixedToFloat(m[offset + i]); } } public void glLoadMatrixx(IntBuffer m) { for(int i = 0; i < MATRIX_SIZE; i++) { mMatrix[mTop + i] = fixedToFloat(m.get()); } } public void glMultMatrixf(float[] m, int offset) { System.arraycopy(mMatrix, mTop, mTemp, 0, MATRIX_SIZE); Matrix.multiplyMM(mMatrix, mTop, mTemp, 0, m, offset); } public void glMultMatrixf(FloatBuffer m) { m.get(mTemp, MATRIX_SIZE, MATRIX_SIZE); glMultMatrixf(mTemp, MATRIX_SIZE); } public void glMultMatrixx(int[] m, int offset) { for(int i = 0; i < MATRIX_SIZE; i++) { mTemp[MATRIX_SIZE + i] = fixedToFloat(m[offset + i]); } glMultMatrixf(mTemp, MATRIX_SIZE); } public void glMultMatrixx(IntBuffer m) { for(int i = 0; i < MATRIX_SIZE; i++) { mTemp[MATRIX_SIZE + i] = fixedToFloat(m.get()); } glMultMatrixf(mTemp, MATRIX_SIZE); } public void glOrthof(float left, float right, float bottom, float top, float near, float far) { Matrix.orthoM(mMatrix, mTop, left, right, bottom, top, near, far); } public void glOrthox(int left, int right, int bottom, int top, int near, int far) { glOrthof(fixedToFloat(left), fixedToFloat(right), fixedToFloat(bottom), fixedToFloat(top), fixedToFloat(near), fixedToFloat(far)); } public void glPopMatrix() { preflight_adjust(-1); adjust(-1); } public void glPushMatrix() { preflight_adjust(1); System.arraycopy(mMatrix, mTop, mMatrix, mTop + MATRIX_SIZE, MATRIX_SIZE); adjust(1); } public void glRotatef(float angle, float x, float y, float z) { Matrix.setRotateM(mTemp, 0, angle, x, y, z); System.arraycopy(mMatrix, mTop, mTemp, MATRIX_SIZE, MATRIX_SIZE); Matrix.multiplyMM(mMatrix, mTop, mTemp, MATRIX_SIZE, mTemp, 0); } public void glRotatex(int angle, int x, int y, int z) { glRotatef(angle, fixedToFloat(x), fixedToFloat(y), fixedToFloat(z)); } public void glScalef(float x, float y, float z) { Matrix.scaleM(mMatrix, mTop, x, y, z); } public void glScalex(int x, int y, int z) { glScalef(fixedToFloat(x), fixedToFloat(y), fixedToFloat(z)); } public void glTranslatef(float x, float y, float z) { Matrix.translateM(mMatrix, mTop, x, y, z); } public void glTranslatex(int x, int y, int z) { glTranslatef(fixedToFloat(x), fixedToFloat(y), fixedToFloat(z)); } public void getMatrix(float[] dest, int offset) { System.arraycopy(mMatrix, mTop, dest, offset, MATRIX_SIZE); } private float fixedToFloat(int x) { return x * (1.0f / 65536.0f); } private void preflight_adjust(int dir) { int newTop = mTop + dir * MATRIX_SIZE; if (newTop < 0) { throw new IllegalArgumentException("stack underflow"); } if (newTop + MATRIX_SIZE > mMatrix.length) { throw new IllegalArgumentException("stack overflow"); } } private void adjust(int dir) { mTop += dir * MATRIX_SIZE; } private final static int DEFAULT_MAX_DEPTH = 32; private final static int MATRIX_SIZE = 16; private float[] mMatrix; private int mTop; private float[] mTemp; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Paint; import android.opengl.GLU; import android.opengl.GLUtils; import android.os.SystemClock; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.opengles.GL10; public class SpriteTextRenderer implements GLView.Renderer{ public SpriteTextRenderer(Context context) { mContext = context; mTriangle = new Triangle(); mProjector = new Projector(); mLabelPaint = new Paint(); mLabelPaint.setTextSize(32); mLabelPaint.setAntiAlias(true); mLabelPaint.setARGB(0xff, 0x00, 0x00, 0x00); } public int[] getConfigSpec() { // We don't need a depth buffer, and don't care about our // color depth. int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_NONE }; return configSpec; } public void surfaceCreated(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); /* * Some one-time OpenGL initialization can be made here * probably based on features of this particular context */ gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); gl.glClearColor(.5f, .5f, .5f, 1); gl.glShadeModel(GL10.GL_SMOOTH); gl.glEnable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_TEXTURE_2D); /* * Create our texture. This has to be done each time the * surface is created. */ int[] textures = new int[1]; gl.glGenTextures(1, textures, 0); mTextureID = textures[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); InputStream is = mContext.getResources() .openRawResource(R.drawable.tex); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is); } finally { try { is.close(); } catch(IOException e) { // Ignore. } } GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); if (mLabels != null) { mLabels.shutdown(gl); } else { mLabels = new LabelMaker(true, 256, 64); } mLabels.initialize(gl); mLabels.beginAdding(gl); mLabelA = mLabels.add(gl, "A", mLabelPaint); mLabelB = mLabels.add(gl, "B", mLabelPaint); mLabelC = mLabels.add(gl, "C", mLabelPaint); mLabelMsPF = mLabels.add(gl, "ms/f", mLabelPaint); mLabels.endAdding(gl); if (mNumericSprite != null) { mNumericSprite.shutdown(gl); } else { mNumericSprite = new NumericSprite(); } mNumericSprite.initialize(gl, mLabelPaint); } public void drawFrame(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE); /* * Usually, the first thing one might want to do is to clear * the screen. The most efficient way of doing this is to use * glClear(). */ gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); /* * Now we're ready to draw some 3D objects */ gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); GLU.gluLookAt(gl, 0.0f, 0.0f, -2.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glActiveTexture(GL10.GL_TEXTURE0); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); long time = SystemClock.uptimeMillis() % 4000L; float angle = 0.090f * ((int) time); gl.glRotatef(angle, 0, 0, 1.0f); gl.glScalef(2.0f, 2.0f, 2.0f); mTriangle.draw(gl); mProjector.getCurrentModelView(gl); mLabels.beginDrawing(gl, mWidth, mHeight); drawLabel(gl, 0, mLabelA); drawLabel(gl, 1, mLabelB); drawLabel(gl, 2, mLabelC); float msPFX = mWidth - mLabels.getWidth(mLabelMsPF) - 1; mLabels.draw(gl, msPFX, 0, mLabelMsPF); mLabels.endDrawing(gl); drawMsPF(gl, msPFX); } private void drawMsPF(GL10 gl, float rightMargin) { long time = SystemClock.uptimeMillis(); if (mStartTime == 0) { mStartTime = time; } if (mFrames++ == SAMPLE_PERIOD_FRAMES) { mFrames = 0; long delta = time - mStartTime; mStartTime = time; mMsPerFrame = (int) (delta * SAMPLE_FACTOR); } if (mMsPerFrame > 0) { mNumericSprite.setValue(mMsPerFrame); float numWidth = mNumericSprite.width(); float x = rightMargin - numWidth; mNumericSprite.draw(gl, x, 0, mWidth, mHeight); } } private void drawLabel(GL10 gl, int triangleVertex, int labelId) { float x = mTriangle.getX(triangleVertex); float y = mTriangle.getY(triangleVertex); mScratch[0] = x; mScratch[1] = y; mScratch[2] = 0.0f; mScratch[3] = 1.0f; mProjector.project(mScratch, 0, mScratch, 4); float sx = mScratch[4]; float sy = mScratch[5]; float height = mLabels.getHeight(labelId); float width = mLabels.getWidth(labelId); float tx = sx - width * 0.5f; float ty = sy - height * 0.5f; mLabels.draw(gl, tx, ty, labelId); } public void sizeChanged(GL10 gl, int w, int h) { mWidth = w; mHeight = h; gl.glViewport(0, 0, w, h); mProjector.setCurrentView(0, 0, w, h); /* * Set our projection matrix. This doesn't have to be done * each time we draw, but usually a new projection needs to * be set when the viewport is resized. */ float ratio = (float) w / h; gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10); mProjector.getCurrentProjection(gl); } private int mWidth; private int mHeight; private Context mContext; private Triangle mTriangle; private int mTextureID; private int mFrames; private int mMsPerFrame; private final static int SAMPLE_PERIOD_FRAMES = 12; private final static float SAMPLE_FACTOR = 1.0f / SAMPLE_PERIOD_FRAMES; private long mStartTime; private LabelMaker mLabels; private Paint mLabelPaint; private int mLabelA; private int mLabelB; private int mLabelC; private int mLabelMsPF; private Projector mProjector; private NumericSprite mNumericSprite; private float[] mScratch = new float[8]; } class Triangle { public Triangle() { // Buffers to be passed to gl*Pointer() functions // must be direct, i.e., they must be placed on the // native heap where the garbage collector cannot // move them. // // Buffers with multi-byte datatypes (e.g., short, int, float) // must have their byte order set to native order ByteBuffer vbb = ByteBuffer.allocateDirect(VERTS * 3 * 4); vbb.order(ByteOrder.nativeOrder()); mFVertexBuffer = vbb.asFloatBuffer(); ByteBuffer tbb = ByteBuffer.allocateDirect(VERTS * 2 * 4); tbb.order(ByteOrder.nativeOrder()); mTexBuffer = tbb.asFloatBuffer(); ByteBuffer ibb = ByteBuffer.allocateDirect(VERTS * 2); ibb.order(ByteOrder.nativeOrder()); mIndexBuffer = ibb.asShortBuffer(); for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 3; j++) { mFVertexBuffer.put(sCoords[i*3+j]); } } for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 2; j++) { mTexBuffer.put(sCoords[i*3+j] * 2.0f + 0.5f); } } for(int i = 0; i < VERTS; i++) { mIndexBuffer.put((short) i); } mFVertexBuffer.position(0); mTexBuffer.position(0); mIndexBuffer.position(0); } public void draw(GL10 gl) { gl.glFrontFace(GL10.GL_CCW); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFVertexBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer); gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, VERTS, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); } public float getX(int vertex) { return sCoords[3*vertex]; } public float getY(int vertex) { return sCoords[3*vertex+1]; } private final static int VERTS = 3; private FloatBuffer mFVertexBuffer; private FloatBuffer mTexBuffer; private ShortBuffer mIndexBuffer; // A unit-sided equalateral triangle centered on the origin. private final static float[] sCoords = { // X, Y, Z -0.5f, -0.25f, 0, 0.5f, -0.25f, 0, 0.0f, 0.559016994f, 0 }; }
Java
/* * Copyright (C) 2007 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.opengles.spritetext; import javax.microedition.khronos.opengles.GL10; class MatrixGrabber { public MatrixGrabber() { mModelView = new float[16]; mProjection = new float[16]; } /** * Record the current modelView and projection matrix state. * Has the side effect of setting the current matrix state to GL_MODELVIEW * @param gl */ public void getCurrentState(GL10 gl) { getCurrentProjection(gl); getCurrentModelView(gl); } /** * Record the current modelView matrix state. Has the side effect of * setting the current matrix state to GL_MODELVIEW * @param gl */ public void getCurrentModelView(GL10 gl) { getMatrix(gl, GL10.GL_MODELVIEW, mModelView); } /** * Record the current projection matrix state. Has the side effect of * setting the current matrix state to GL_PROJECTION * @param gl */ public void getCurrentProjection(GL10 gl) { getMatrix(gl, GL10.GL_PROJECTION, mProjection); } private void getMatrix(GL10 gl, int mode, float[] mat) { MatrixTrackingGL gl2 = (MatrixTrackingGL) gl; gl2.glMatrixMode(mode); gl2.getMatrix(mat, 0); } public float[] mModelView; public float[] mProjection; }
Java
/* * Copyright (C) 2007 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.opengles.spritetext; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Paint.Style; import android.graphics.drawable.Drawable; import android.opengl.GLUtils; import java.util.ArrayList; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import javax.microedition.khronos.opengles.GL11Ext; /** * An OpenGL text label maker. * * * OpenGL labels are implemented by creating a Bitmap, drawing all the labels * into the Bitmap, converting the Bitmap into an Alpha texture, and creating a * mesh for each label * * The benefits of this approach are that the labels are drawn using the high * quality anti-aliased font rasterizer, full character set support, and all the * text labels are stored on a single texture, which makes it faster to use. * * The drawbacks are that you can only have as many labels as will fit onto one * texture, and you have to recreate the whole texture if any label text * changes. * */ public class LabelMaker { /** * Create a label maker * or maximum compatibility with various OpenGL ES implementations, * the strike width and height must be powers of two, * We want the strike width to be at least as wide as the widest window. * * @param fullColor true if we want a full color backing store (4444), * otherwise we generate a grey L8 backing store. * @param strikeWidth width of strike * @param strikeHeight height of strike */ public LabelMaker(boolean fullColor, int strikeWidth, int strikeHeight) { mFullColor = fullColor; mStrikeWidth = strikeWidth; mStrikeHeight = strikeHeight; mTexelWidth = (float) (1.0 / mStrikeWidth); mTexelHeight = (float) (1.0 / mStrikeHeight); mClearPaint = new Paint(); mClearPaint.setARGB(0, 0, 0, 0); mClearPaint.setStyle(Style.FILL); mState = STATE_NEW; } /** * Call to initialize the class. * Call whenever the surface has been created. * * @param gl */ public void initialize(GL10 gl) { mState = STATE_INITIALIZED; int[] textures = new int[1]; gl.glGenTextures(1, textures, 0); mTextureID = textures[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); // Use Nearest for performance. gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); } /** * Call when the surface has been destroyed */ public void shutdown(GL10 gl) { if ( gl != null) { if (mState > STATE_NEW) { int[] textures = new int[1]; textures[0] = mTextureID; gl.glDeleteTextures(1, textures, 0); mState = STATE_NEW; } } } /** * Call before adding labels. Clears out any existing labels. * * @param gl */ public void beginAdding(GL10 gl) { checkState(STATE_INITIALIZED, STATE_ADDING); mLabels.clear(); mU = 0; mV = 0; mLineHeight = 0; Bitmap.Config config = mFullColor ? Bitmap.Config.ARGB_4444 : Bitmap.Config.ALPHA_8; mBitmap = Bitmap.createBitmap(mStrikeWidth, mStrikeHeight, config); mCanvas = new Canvas(mBitmap); mBitmap.eraseColor(0); } /** * Call to add a label * * @param gl * @param text the text of the label * @param textPaint the paint of the label * @return the id of the label, used to measure and draw the label */ public int add(GL10 gl, String text, Paint textPaint) { return add(gl, null, text, textPaint); } /** * Call to add a label * * @param gl * @param text the text of the label * @param textPaint the paint of the label * @return the id of the label, used to measure and draw the label */ public int add(GL10 gl, Drawable background, String text, Paint textPaint) { return add(gl, background, text, textPaint, 0, 0); } /** * Call to add a label * @return the id of the label, used to measure and draw the label */ public int add(GL10 gl, Drawable drawable, int minWidth, int minHeight) { return add(gl, drawable, null, null, minWidth, minHeight); } /** * Call to add a label * * @param gl * @param text the text of the label * @param textPaint the paint of the label * @return the id of the label, used to measure and draw the label */ public int add(GL10 gl, Drawable background, String text, Paint textPaint, int minWidth, int minHeight) { checkState(STATE_ADDING, STATE_ADDING); boolean drawBackground = background != null; boolean drawText = (text != null) && (textPaint != null); Rect padding = new Rect(); if (drawBackground) { background.getPadding(padding); minWidth = Math.max(minWidth, background.getMinimumWidth()); minHeight = Math.max(minHeight, background.getMinimumHeight()); } int ascent = 0; int descent = 0; int measuredTextWidth = 0; if (drawText) { // Paint.ascent is negative, so negate it. ascent = (int) Math.ceil(-textPaint.ascent()); descent = (int) Math.ceil(textPaint.descent()); measuredTextWidth = (int) Math.ceil(textPaint.measureText(text)); } int textHeight = ascent + descent; int textWidth = Math.min(mStrikeWidth,measuredTextWidth); int padHeight = padding.top + padding.bottom; int padWidth = padding.left + padding.right; int height = Math.max(minHeight, textHeight + padHeight); int width = Math.max(minWidth, textWidth + padWidth); int effectiveTextHeight = height - padHeight; int effectiveTextWidth = width - padWidth; int centerOffsetHeight = (effectiveTextHeight - textHeight) / 2; int centerOffsetWidth = (effectiveTextWidth - textWidth) / 2; // Make changes to the local variables, only commit them // to the member variables after we've decided not to throw // any exceptions. int u = mU; int v = mV; int lineHeight = mLineHeight; if (width > mStrikeWidth) { width = mStrikeWidth; } // Is there room for this string on the current line? if (u + width > mStrikeWidth) { // No room, go to the next line: u = 0; v += lineHeight; lineHeight = 0; } lineHeight = Math.max(lineHeight, height); if (v + lineHeight > mStrikeHeight) { throw new IllegalArgumentException("Out of texture space."); } int u2 = u + width; int vBase = v + ascent; int v2 = v + height; if (drawBackground) { background.setBounds(u, v, u + width, v + height); background.draw(mCanvas); } if (drawText) { mCanvas.drawText(text, u + padding.left + centerOffsetWidth, vBase + padding.top + centerOffsetHeight, textPaint); } Grid grid = new Grid(2, 2); // Grid.set arguments: i, j, x, y, z, u, v float texU = u * mTexelWidth; float texU2 = u2 * mTexelWidth; float texV = 1.0f - v * mTexelHeight; float texV2 = 1.0f - v2 * mTexelHeight; grid.set(0, 0, 0.0f, 0.0f, 0.0f, texU , texV2); grid.set(1, 0, width, 0.0f, 0.0f, texU2, texV2); grid.set(0, 1, 0.0f, height, 0.0f, texU , texV ); grid.set(1, 1, width, height, 0.0f, texU2, texV ); // We know there's enough space, so update the member variables mU = u + width; mV = v; mLineHeight = lineHeight; mLabels.add(new Label(grid, width, height, ascent, u, v + height, width, -height)); return mLabels.size() - 1; } /** * Call to end adding labels. Must be called before drawing starts. * * @param gl */ public void endAdding(GL10 gl) { checkState(STATE_ADDING, STATE_INITIALIZED); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, mBitmap, 0); // Reclaim storage used by bitmap and canvas. mBitmap.recycle(); mBitmap = null; mCanvas = null; } /** * Get the width in pixels of a given label. * * @param labelID * @return the width in pixels */ public float getWidth(int labelID) { return mLabels.get(labelID).width; } /** * Get the height in pixels of a given label. * * @param labelID * @return the height in pixels */ public float getHeight(int labelID) { return mLabels.get(labelID).height; } /** * Get the baseline of a given label. That's how many pixels from the top of * the label to the text baseline. (This is equivalent to the negative of * the label's paint's ascent.) * * @param labelID * @return the baseline in pixels. */ public float getBaseline(int labelID) { return mLabels.get(labelID).baseline; } /** * Begin drawing labels. Sets the OpenGL state for rapid drawing. * * @param gl * @param viewWidth * @param viewHeight */ public void beginDrawing(GL10 gl, float viewWidth, float viewHeight) { checkState(STATE_INITIALIZED, STATE_DRAWING); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glShadeModel(GL10.GL_FLAT); gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000); gl.glMatrixMode(GL10.GL_PROJECTION); gl.glPushMatrix(); gl.glLoadIdentity(); gl.glOrthof(0.0f, viewWidth, 0.0f, viewHeight, 0.0f, 1.0f); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glPushMatrix(); gl.glLoadIdentity(); // Magic offsets to promote consistent rasterization. gl.glTranslatef(0.375f, 0.375f, 0.0f); } /** * Draw a given label at a given x,y position, expressed in pixels, with the * lower-left-hand-corner of the view being (0,0). * * @param gl * @param x * @param y * @param labelID */ public void draw(GL10 gl, float x, float y, int labelID) { checkState(STATE_DRAWING, STATE_DRAWING); gl.glPushMatrix(); float snappedX = (float) Math.floor(x); float snappedY = (float) Math.floor(y); gl.glTranslatef(snappedX, snappedY, 0.0f); Label label = mLabels.get(labelID); gl.glEnable(GL10.GL_TEXTURE_2D); ((GL11)gl).glTexParameteriv(GL10.GL_TEXTURE_2D, GL11Ext.GL_TEXTURE_CROP_RECT_OES, label.mCrop, 0); ((GL11Ext)gl).glDrawTexiOES((int) snappedX, (int) snappedY, 0, (int) label.width, (int) label.height); gl.glPopMatrix(); } /** * Ends the drawing and restores the OpenGL state. * * @param gl */ public void endDrawing(GL10 gl) { checkState(STATE_DRAWING, STATE_INITIALIZED); gl.glDisable(GL10.GL_BLEND); gl.glMatrixMode(GL10.GL_PROJECTION); gl.glPopMatrix(); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glPopMatrix(); } private void checkState(int oldState, int newState) { if (mState != oldState) { throw new IllegalArgumentException("Can't call this method now."); } mState = newState; } private static class Label { public Label(Grid grid, float width, float height, float baseLine, int cropU, int cropV, int cropW, int cropH) { this.grid = grid; this.width = width; this.height = height; this.baseline = baseLine; int[] crop = new int[4]; crop[0] = cropU; crop[1] = cropV; crop[2] = cropW; crop[3] = cropH; mCrop = crop; } public Grid grid; public float width; public float height; public float baseline; public int[] mCrop; } private int mStrikeWidth; private int mStrikeHeight; private boolean mFullColor; private Bitmap mBitmap; private Canvas mCanvas; private Paint mClearPaint; private int mTextureID; private float mTexelWidth; // Convert texel to U private float mTexelHeight; // Convert texel to V private int mU; private int mV; private int mLineHeight; private ArrayList<Label> mLabels = new ArrayList<Label>(); private static final int STATE_NEW = 0; private static final int STATE_INITIALIZED = 1; private static final int STATE_ADDING = 2; private static final int STATE_DRAWING = 3; private int mState; }
Java
/* * Copyright (C) 2007 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.opengles.spritetext; import android.opengl.Matrix; import javax.microedition.khronos.opengles.GL10; /** * A utility that projects * */ class Projector { public Projector() { mMVP = new float[16]; mV = new float[4]; mGrabber = new MatrixGrabber(); } public void setCurrentView(int x, int y, int width, int height) { mX = x; mY = y; mViewWidth = width; mViewHeight = height; } public void project(float[] obj, int objOffset, float[] win, int winOffset) { if (!mMVPComputed) { Matrix.multiplyMM(mMVP, 0, mGrabber.mProjection, 0, mGrabber.mModelView, 0); mMVPComputed = true; } Matrix.multiplyMV(mV, 0, mMVP, 0, obj, objOffset); float rw = 1.0f / mV[3]; win[winOffset] = mX + mViewWidth * (mV[0] * rw + 1.0f) * 0.5f; win[winOffset + 1] = mY + mViewHeight * (mV[1] * rw + 1.0f) * 0.5f; win[winOffset + 2] = (mV[2] * rw + 1.0f) * 0.5f; } /** * Get the current projection matrix. Has the side-effect of * setting current matrix mode to GL_PROJECTION * @param gl */ public void getCurrentProjection(GL10 gl) { mGrabber.getCurrentProjection(gl); mMVPComputed = false; } /** * Get the current model view matrix. Has the side-effect of * setting current matrix mode to GL_MODELVIEW * @param gl */ public void getCurrentModelView(GL10 gl) { mGrabber.getCurrentModelView(gl); mMVPComputed = false; } private MatrixGrabber mGrabber; private boolean mMVPComputed; private float[] mMVP; private float[] mV; private int mX; private int mY; private int mViewWidth; private int mViewHeight; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import android.content.Context; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.util.ArrayList; import java.util.concurrent.Semaphore; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; /** * An implementation of SurfaceView that uses the dedicated surface for * displaying an OpenGL animation. This allows the animation to run in a * separate thread, without requiring that it be driven by the update mechanism * of the view hierarchy. * * The application-specific rendering code is delegated to a GLView.Renderer * instance. */ class GLView extends SurfaceView implements SurfaceHolder.Callback { GLView(Context context) { super(context); init(); } public GLView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU); } public void setGLWrapper(GLWrapper glWrapper) { mGLWrapper = glWrapper; } public void setRenderer(Renderer renderer) { mGLThread = new GLThread(renderer); mGLThread.start(); } public void surfaceCreated(SurfaceHolder holder) { mGLThread.surfaceCreated(); } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return mGLThread.surfaceDestroyed(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Surface size or format has changed. This should not happen in this // example. mGLThread.onWindowResize(w, h); } /** * Inform the view that the activity is paused. */ public void onPause() { mGLThread.onPause(); } /** * Inform the view that the activity is resumed. */ public void onResume() { mGLThread.onResume(); } /** * Inform the view that the window focus has changed. */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mGLThread.onWindowFocusChanged(hasFocus); } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { mGLThread.queueEvent(r); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mGLThread.requestExitAndWait(); } // ---------------------------------------------------------------------- public interface GLWrapper { GL wrap(GL gl); } // ---------------------------------------------------------------------- /** * A generic renderer interface. */ public interface Renderer { /** * @return the EGL configuration specification desired by the renderer. */ int[] getConfigSpec(); /** * Surface created. * Called when the surface is created. Called when the application * starts, and whenever the GPU is reinitialized. This will * typically happen when the device awakes after going to sleep. * Set your textures here. */ void surfaceCreated(GL10 gl); /** * Surface changed size. * Called after the surface is created and whenever * the OpenGL ES surface size changes. Set your viewport here. * @param gl * @param width * @param height */ void sizeChanged(GL10 gl, int width, int height); /** * Draw the current frame. * @param gl */ void drawFrame(GL10 gl); } /** * An EGL helper class. */ private class EglHelper { public EglHelper() { } /** * Initialize EGL for a given configuration spec. * @param configSpec */ public void start(int[] configSpec){ /* * Get an EGL instance */ mEgl = (EGL10) EGLContext.getEGL(); /* * Get to the default display. */ mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); /* * We can now initialize EGL for that display */ int[] version = new int[2]; mEgl.eglInitialize(mEglDisplay, version); EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1, num_config); mEglConfig = configs[0]; /* * Create an OpenGL ES context. This must be done only once, an * OpenGL context is a somewhat heavy object. */ mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig, EGL10.EGL_NO_CONTEXT, null); mEglSurface = null; } /* * Create and return an OpenGL surface */ public GL createSurface(SurfaceHolder holder) { /* * The window size has changed, so we need to create a new * surface. */ if (mEglSurface != null) { /* * Unbind and destroy the old EGL surface, if * there is one. */ mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); } /* * Create an EGL surface we can render into. */ mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, holder, null); /* * Before we can issue GL commands, we need to make sure * the context is current and bound to a surface. */ mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext); GL gl = mEglContext.getGL(); if (mGLWrapper != null) { gl = mGLWrapper.wrap(gl); } return gl; } /** * Display the current render surface. * @return false if the context has been lost. */ public boolean swap() { mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); /* * Always check for EGL_CONTEXT_LOST, which means the context * and all associated data were lost (For instance because * the device went to sleep). We need to sleep until we * get a new surface. */ return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; } public void finish() { if (mEglSurface != null) { mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); mEglSurface = null; } if (mEglContext != null) { mEgl.eglDestroyContext(mEglDisplay, mEglContext); mEglContext = null; } if (mEglDisplay != null) { mEgl.eglTerminate(mEglDisplay); mEglDisplay = null; } } EGL10 mEgl; EGLDisplay mEglDisplay; EGLSurface mEglSurface; EGLConfig mEglConfig; EGLContext mEglContext; } /** * A generic GL Thread. Takes care of initializing EGL and GL. Delegates * to a Renderer instance to do the actual drawing. * */ class GLThread extends Thread { GLThread(Renderer renderer) { super(); mDone = false; mWidth = 0; mHeight = 0; mRenderer = renderer; setName("GLThread"); } @Override public void run() { /* * When the android framework launches a second instance of * an activity, the new instance's onCreate() method may be * called before the first instance returns from onDestroy(). * * This semaphore ensures that only one instance at a time * accesses EGL. */ try { try { sEglSemaphore.acquire(); } catch (InterruptedException e) { return; } guardedRun(); } catch (InterruptedException e) { // fall thru and exit normally } finally { sEglSemaphore.release(); } } private void guardedRun() throws InterruptedException { mEglHelper = new EglHelper(); /* * Specify a configuration for our opengl session * and grab the first configuration that matches is */ int[] configSpec = mRenderer.getConfigSpec(); mEglHelper.start(configSpec); GL10 gl = null; boolean tellRendererSurfaceCreated = true; boolean tellRendererSurfaceChanged = true; /* * This is our main activity thread's loop, we go until * asked to quit. */ while (!mDone) { /* * Update the asynchronous state (window size) */ int w, h; boolean changed; boolean needStart = false; synchronized (this) { Runnable r; while ((r = getEvent()) != null) { r.run(); } if (mPaused) { mEglHelper.finish(); needStart = true; } if(needToWait()) { while (needToWait()) { wait(); } } if (mDone) { break; } changed = mSizeChanged; w = mWidth; h = mHeight; mSizeChanged = false; } if (needStart) { mEglHelper.start(configSpec); tellRendererSurfaceCreated = true; changed = true; } if (changed) { gl = (GL10) mEglHelper.createSurface(mHolder); tellRendererSurfaceChanged = true; } if (tellRendererSurfaceCreated) { mRenderer.surfaceCreated(gl); tellRendererSurfaceCreated = false; } if (tellRendererSurfaceChanged) { mRenderer.sizeChanged(gl, w, h); tellRendererSurfaceChanged = false; } if ((w > 0) && (h > 0)) { /* draw a frame here */ mRenderer.drawFrame(gl); /* * Once we're done with GL, we need to call swapBuffers() * to instruct the system to display the rendered frame */ mEglHelper.swap(); } } /* * clean-up everything... */ mEglHelper.finish(); } private boolean needToWait() { return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost) && (! mDone); } public void surfaceCreated() { synchronized(this) { mHasSurface = true; mContextLost = false; notify(); } } public void surfaceDestroyed() { synchronized(this) { mHasSurface = false; notify(); } } public void onPause() { synchronized (this) { mPaused = true; } } public void onResume() { synchronized (this) { mPaused = false; notify(); } } public void onWindowFocusChanged(boolean hasFocus) { synchronized (this) { mHasFocus = hasFocus; if (mHasFocus == true) { notify(); } } } public void onWindowResize(int w, int h) { synchronized (this) { mWidth = w; mHeight = h; mSizeChanged = true; } } public void requestExitAndWait() { // don't call this from GLThread thread or it is a guaranteed // deadlock! synchronized(this) { mDone = true; notify(); } try { join(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { synchronized(this) { mEventQueue.add(r); } } private Runnable getEvent() { synchronized(this) { if (mEventQueue.size() > 0) { return mEventQueue.remove(0); } } return null; } private boolean mDone; private boolean mPaused; private boolean mHasFocus; private boolean mHasSurface; private boolean mContextLost; private int mWidth; private int mHeight; private Renderer mRenderer; private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>(); private EglHelper mEglHelper; } private static final Semaphore sEglSemaphore = new Semaphore(1); private boolean mSizeChanged = true; private SurfaceHolder mHolder; private GLThread mGLThread; private GLWrapper mGLWrapper; }
Java
/* * Copyright (C) 2007 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.opengles.spritetext; import android.util.Log; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL10Ext; import javax.microedition.khronos.opengles.GL11; import javax.microedition.khronos.opengles.GL11Ext; /** * Allows retrieving the current matrix even if the current OpenGL ES * driver does not support retrieving the current matrix. * * Note: the actual matrix may differ from the retrieved matrix, due * to differences in the way the math is implemented by GLMatrixWrapper * as compared to the way the math is implemented by the OpenGL ES * driver. */ class MatrixTrackingGL implements GL, GL10, GL10Ext, GL11, GL11Ext { private GL10 mgl; private GL10Ext mgl10Ext; private GL11 mgl11; private GL11Ext mgl11Ext; private int mMatrixMode; private MatrixStack mCurrent; private MatrixStack mModelView; private MatrixStack mTexture; private MatrixStack mProjection; private final static boolean _check = false; ByteBuffer mByteBuffer; FloatBuffer mFloatBuffer; float[] mCheckA; float[] mCheckB; public MatrixTrackingGL(GL gl) { mgl = (GL10) gl; if (gl instanceof GL10Ext) { mgl10Ext = (GL10Ext) gl; } if (gl instanceof GL11) { mgl11 = (GL11) gl; } if (gl instanceof GL11Ext) { mgl11Ext = (GL11Ext) gl; } mModelView = new MatrixStack(); mProjection = new MatrixStack(); mTexture = new MatrixStack(); mCurrent = mModelView; mMatrixMode = GL10.GL_MODELVIEW; } // --------------------------------------------------------------------- // GL10 methods: public void glActiveTexture(int texture) { mgl.glActiveTexture(texture); } public void glAlphaFunc(int func, float ref) { mgl.glAlphaFunc(func, ref); } public void glAlphaFuncx(int func, int ref) { mgl.glAlphaFuncx(func, ref); } public void glBindTexture(int target, int texture) { mgl.glBindTexture(target, texture); } public void glBlendFunc(int sfactor, int dfactor) { mgl.glBlendFunc(sfactor, dfactor); } public void glClear(int mask) { mgl.glClear(mask); } public void glClearColor(float red, float green, float blue, float alpha) { mgl.glClearColor(red, green, blue, alpha); } public void glClearColorx(int red, int green, int blue, int alpha) { mgl.glClearColorx(red, green, blue, alpha); } public void glClearDepthf(float depth) { mgl.glClearDepthf(depth); } public void glClearDepthx(int depth) { mgl.glClearDepthx(depth); } public void glClearStencil(int s) { mgl.glClearStencil(s); } public void glClientActiveTexture(int texture) { mgl.glClientActiveTexture(texture); } public void glColor4f(float red, float green, float blue, float alpha) { mgl.glColor4f(red, green, blue, alpha); } public void glColor4x(int red, int green, int blue, int alpha) { mgl.glColor4x(red, green, blue, alpha); } public void glColorMask(boolean red, boolean green, boolean blue, boolean alpha) { mgl.glColorMask(red, green, blue, alpha); } public void glColorPointer(int size, int type, int stride, Buffer pointer) { mgl.glColorPointer(size, type, stride, pointer); } public void glCompressedTexImage2D(int target, int level, int internalformat, int width, int height, int border, int imageSize, Buffer data) { mgl.glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); } public void glCompressedTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int imageSize, Buffer data) { mgl.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); } public void glCopyTexImage2D(int target, int level, int internalformat, int x, int y, int width, int height, int border) { mgl.glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); } public void glCopyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) { mgl.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); } public void glCullFace(int mode) { mgl.glCullFace(mode); } public void glDeleteTextures(int n, int[] textures, int offset) { mgl.glDeleteTextures(n, textures, offset); } public void glDeleteTextures(int n, IntBuffer textures) { mgl.glDeleteTextures(n, textures); } public void glDepthFunc(int func) { mgl.glDepthFunc(func); } public void glDepthMask(boolean flag) { mgl.glDepthMask(flag); } public void glDepthRangef(float near, float far) { mgl.glDepthRangef(near, far); } public void glDepthRangex(int near, int far) { mgl.glDepthRangex(near, far); } public void glDisable(int cap) { mgl.glDisable(cap); } public void glDisableClientState(int array) { mgl.glDisableClientState(array); } public void glDrawArrays(int mode, int first, int count) { mgl.glDrawArrays(mode, first, count); } public void glDrawElements(int mode, int count, int type, Buffer indices) { mgl.glDrawElements(mode, count, type, indices); } public void glEnable(int cap) { mgl.glEnable(cap); } public void glEnableClientState(int array) { mgl.glEnableClientState(array); } public void glFinish() { mgl.glFinish(); } public void glFlush() { mgl.glFlush(); } public void glFogf(int pname, float param) { mgl.glFogf(pname, param); } public void glFogfv(int pname, float[] params, int offset) { mgl.glFogfv(pname, params, offset); } public void glFogfv(int pname, FloatBuffer params) { mgl.glFogfv(pname, params); } public void glFogx(int pname, int param) { mgl.glFogx(pname, param); } public void glFogxv(int pname, int[] params, int offset) { mgl.glFogxv(pname, params, offset); } public void glFogxv(int pname, IntBuffer params) { mgl.glFogxv(pname, params); } public void glFrontFace(int mode) { mgl.glFrontFace(mode); } public void glFrustumf(float left, float right, float bottom, float top, float near, float far) { mCurrent.glFrustumf(left, right, bottom, top, near, far); mgl.glFrustumf(left, right, bottom, top, near, far); if ( _check) check(); } public void glFrustumx(int left, int right, int bottom, int top, int near, int far) { mCurrent.glFrustumx(left, right, bottom, top, near, far); mgl.glFrustumx(left, right, bottom, top, near, far); if ( _check) check(); } public void glGenTextures(int n, int[] textures, int offset) { mgl.glGenTextures(n, textures, offset); } public void glGenTextures(int n, IntBuffer textures) { mgl.glGenTextures(n, textures); } public int glGetError() { int result = mgl.glGetError(); return result; } public void glGetIntegerv(int pname, int[] params, int offset) { mgl.glGetIntegerv(pname, params, offset); } public void glGetIntegerv(int pname, IntBuffer params) { mgl.glGetIntegerv(pname, params); } public String glGetString(int name) { String result = mgl.glGetString(name); return result; } public void glHint(int target, int mode) { mgl.glHint(target, mode); } public void glLightModelf(int pname, float param) { mgl.glLightModelf(pname, param); } public void glLightModelfv(int pname, float[] params, int offset) { mgl.glLightModelfv(pname, params, offset); } public void glLightModelfv(int pname, FloatBuffer params) { mgl.glLightModelfv(pname, params); } public void glLightModelx(int pname, int param) { mgl.glLightModelx(pname, param); } public void glLightModelxv(int pname, int[] params, int offset) { mgl.glLightModelxv(pname, params, offset); } public void glLightModelxv(int pname, IntBuffer params) { mgl.glLightModelxv(pname, params); } public void glLightf(int light, int pname, float param) { mgl.glLightf(light, pname, param); } public void glLightfv(int light, int pname, float[] params, int offset) { mgl.glLightfv(light, pname, params, offset); } public void glLightfv(int light, int pname, FloatBuffer params) { mgl.glLightfv(light, pname, params); } public void glLightx(int light, int pname, int param) { mgl.glLightx(light, pname, param); } public void glLightxv(int light, int pname, int[] params, int offset) { mgl.glLightxv(light, pname, params, offset); } public void glLightxv(int light, int pname, IntBuffer params) { mgl.glLightxv(light, pname, params); } public void glLineWidth(float width) { mgl.glLineWidth(width); } public void glLineWidthx(int width) { mgl.glLineWidthx(width); } public void glLoadIdentity() { mCurrent.glLoadIdentity(); mgl.glLoadIdentity(); if ( _check) check(); } public void glLoadMatrixf(float[] m, int offset) { mCurrent.glLoadMatrixf(m, offset); mgl.glLoadMatrixf(m, offset); if ( _check) check(); } public void glLoadMatrixf(FloatBuffer m) { int position = m.position(); mCurrent.glLoadMatrixf(m); m.position(position); mgl.glLoadMatrixf(m); if ( _check) check(); } public void glLoadMatrixx(int[] m, int offset) { mCurrent.glLoadMatrixx(m, offset); mgl.glLoadMatrixx(m, offset); if ( _check) check(); } public void glLoadMatrixx(IntBuffer m) { int position = m.position(); mCurrent.glLoadMatrixx(m); m.position(position); mgl.glLoadMatrixx(m); if ( _check) check(); } public void glLogicOp(int opcode) { mgl.glLogicOp(opcode); } public void glMaterialf(int face, int pname, float param) { mgl.glMaterialf(face, pname, param); } public void glMaterialfv(int face, int pname, float[] params, int offset) { mgl.glMaterialfv(face, pname, params, offset); } public void glMaterialfv(int face, int pname, FloatBuffer params) { mgl.glMaterialfv(face, pname, params); } public void glMaterialx(int face, int pname, int param) { mgl.glMaterialx(face, pname, param); } public void glMaterialxv(int face, int pname, int[] params, int offset) { mgl.glMaterialxv(face, pname, params, offset); } public void glMaterialxv(int face, int pname, IntBuffer params) { mgl.glMaterialxv(face, pname, params); } public void glMatrixMode(int mode) { switch (mode) { case GL10.GL_MODELVIEW: mCurrent = mModelView; break; case GL10.GL_TEXTURE: mCurrent = mTexture; break; case GL10.GL_PROJECTION: mCurrent = mProjection; break; default: throw new IllegalArgumentException("Unknown matrix mode: " + mode); } mgl.glMatrixMode(mode); mMatrixMode = mode; if ( _check) check(); } public void glMultMatrixf(float[] m, int offset) { mCurrent.glMultMatrixf(m, offset); mgl.glMultMatrixf(m, offset); if ( _check) check(); } public void glMultMatrixf(FloatBuffer m) { int position = m.position(); mCurrent.glMultMatrixf(m); m.position(position); mgl.glMultMatrixf(m); if ( _check) check(); } public void glMultMatrixx(int[] m, int offset) { mCurrent.glMultMatrixx(m, offset); mgl.glMultMatrixx(m, offset); if ( _check) check(); } public void glMultMatrixx(IntBuffer m) { int position = m.position(); mCurrent.glMultMatrixx(m); m.position(position); mgl.glMultMatrixx(m); if ( _check) check(); } public void glMultiTexCoord4f(int target, float s, float t, float r, float q) { mgl.glMultiTexCoord4f(target, s, t, r, q); } public void glMultiTexCoord4x(int target, int s, int t, int r, int q) { mgl.glMultiTexCoord4x(target, s, t, r, q); } public void glNormal3f(float nx, float ny, float nz) { mgl.glNormal3f(nx, ny, nz); } public void glNormal3x(int nx, int ny, int nz) { mgl.glNormal3x(nx, ny, nz); } public void glNormalPointer(int type, int stride, Buffer pointer) { mgl.glNormalPointer(type, stride, pointer); } public void glOrthof(float left, float right, float bottom, float top, float near, float far) { mCurrent.glOrthof(left, right, bottom, top, near, far); mgl.glOrthof(left, right, bottom, top, near, far); if ( _check) check(); } public void glOrthox(int left, int right, int bottom, int top, int near, int far) { mCurrent.glOrthox(left, right, bottom, top, near, far); mgl.glOrthox(left, right, bottom, top, near, far); if ( _check) check(); } public void glPixelStorei(int pname, int param) { mgl.glPixelStorei(pname, param); } public void glPointSize(float size) { mgl.glPointSize(size); } public void glPointSizex(int size) { mgl.glPointSizex(size); } public void glPolygonOffset(float factor, float units) { mgl.glPolygonOffset(factor, units); } public void glPolygonOffsetx(int factor, int units) { mgl.glPolygonOffsetx(factor, units); } public void glPopMatrix() { mCurrent.glPopMatrix(); mgl.glPopMatrix(); if ( _check) check(); } public void glPushMatrix() { mCurrent.glPushMatrix(); mgl.glPushMatrix(); if ( _check) check(); } public void glReadPixels(int x, int y, int width, int height, int format, int type, Buffer pixels) { mgl.glReadPixels(x, y, width, height, format, type, pixels); } public void glRotatef(float angle, float x, float y, float z) { mCurrent.glRotatef(angle, x, y, z); mgl.glRotatef(angle, x, y, z); if ( _check) check(); } public void glRotatex(int angle, int x, int y, int z) { mCurrent.glRotatex(angle, x, y, z); mgl.glRotatex(angle, x, y, z); if ( _check) check(); } public void glSampleCoverage(float value, boolean invert) { mgl.glSampleCoverage(value, invert); } public void glSampleCoveragex(int value, boolean invert) { mgl.glSampleCoveragex(value, invert); } public void glScalef(float x, float y, float z) { mCurrent.glScalef(x, y, z); mgl.glScalef(x, y, z); if ( _check) check(); } public void glScalex(int x, int y, int z) { mCurrent.glScalex(x, y, z); mgl.glScalex(x, y, z); if ( _check) check(); } public void glScissor(int x, int y, int width, int height) { mgl.glScissor(x, y, width, height); } public void glShadeModel(int mode) { mgl.glShadeModel(mode); } public void glStencilFunc(int func, int ref, int mask) { mgl.glStencilFunc(func, ref, mask); } public void glStencilMask(int mask) { mgl.glStencilMask(mask); } public void glStencilOp(int fail, int zfail, int zpass) { mgl.glStencilOp(fail, zfail, zpass); } public void glTexCoordPointer(int size, int type, int stride, Buffer pointer) { mgl.glTexCoordPointer(size, type, stride, pointer); } public void glTexEnvf(int target, int pname, float param) { mgl.glTexEnvf(target, pname, param); } public void glTexEnvfv(int target, int pname, float[] params, int offset) { mgl.glTexEnvfv(target, pname, params, offset); } public void glTexEnvfv(int target, int pname, FloatBuffer params) { mgl.glTexEnvfv(target, pname, params); } public void glTexEnvx(int target, int pname, int param) { mgl.glTexEnvx(target, pname, param); } public void glTexEnvxv(int target, int pname, int[] params, int offset) { mgl.glTexEnvxv(target, pname, params, offset); } public void glTexEnvxv(int target, int pname, IntBuffer params) { mgl.glTexEnvxv(target, pname, params); } public void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, Buffer pixels) { mgl.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); } public void glTexParameterf(int target, int pname, float param) { mgl.glTexParameterf(target, pname, param); } public void glTexParameterx(int target, int pname, int param) { mgl.glTexParameterx(target, pname, param); } public void glTexParameteriv(int target, int pname, int[] params, int offset) { mgl11.glTexParameteriv(target, pname, params, offset); } public void glTexParameteriv(int target, int pname, IntBuffer params) { mgl11.glTexParameteriv(target, pname, params); } public void glTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, Buffer pixels) { mgl.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); } public void glTranslatef(float x, float y, float z) { mCurrent.glTranslatef(x, y, z); mgl.glTranslatef(x, y, z); if ( _check) check(); } public void glTranslatex(int x, int y, int z) { mCurrent.glTranslatex(x, y, z); mgl.glTranslatex(x, y, z); if ( _check) check(); } public void glVertexPointer(int size, int type, int stride, Buffer pointer) { mgl.glVertexPointer(size, type, stride, pointer); } public void glViewport(int x, int y, int width, int height) { mgl.glViewport(x, y, width, height); } public void glClipPlanef(int plane, float[] equation, int offset) { mgl11.glClipPlanef(plane, equation, offset); } public void glClipPlanef(int plane, FloatBuffer equation) { mgl11.glClipPlanef(plane, equation); } public void glClipPlanex(int plane, int[] equation, int offset) { mgl11.glClipPlanex(plane, equation, offset); } public void glClipPlanex(int plane, IntBuffer equation) { mgl11.glClipPlanex(plane, equation); } // Draw Texture Extension public void glDrawTexfOES(float x, float y, float z, float width, float height) { mgl11Ext.glDrawTexfOES(x, y, z, width, height); } public void glDrawTexfvOES(float[] coords, int offset) { mgl11Ext.glDrawTexfvOES(coords, offset); } public void glDrawTexfvOES(FloatBuffer coords) { mgl11Ext.glDrawTexfvOES(coords); } public void glDrawTexiOES(int x, int y, int z, int width, int height) { mgl11Ext.glDrawTexiOES(x, y, z, width, height); } public void glDrawTexivOES(int[] coords, int offset) { mgl11Ext.glDrawTexivOES(coords, offset); } public void glDrawTexivOES(IntBuffer coords) { mgl11Ext.glDrawTexivOES(coords); } public void glDrawTexsOES(short x, short y, short z, short width, short height) { mgl11Ext.glDrawTexsOES(x, y, z, width, height); } public void glDrawTexsvOES(short[] coords, int offset) { mgl11Ext.glDrawTexsvOES(coords, offset); } public void glDrawTexsvOES(ShortBuffer coords) { mgl11Ext.glDrawTexsvOES(coords); } public void glDrawTexxOES(int x, int y, int z, int width, int height) { mgl11Ext.glDrawTexxOES(x, y, z, width, height); } public void glDrawTexxvOES(int[] coords, int offset) { mgl11Ext.glDrawTexxvOES(coords, offset); } public void glDrawTexxvOES(IntBuffer coords) { mgl11Ext.glDrawTexxvOES(coords); } public int glQueryMatrixxOES(int[] mantissa, int mantissaOffset, int[] exponent, int exponentOffset) { return mgl10Ext.glQueryMatrixxOES(mantissa, mantissaOffset, exponent, exponentOffset); } public int glQueryMatrixxOES(IntBuffer mantissa, IntBuffer exponent) { return mgl10Ext.glQueryMatrixxOES(mantissa, exponent); } // Unsupported GL11 methods public void glBindBuffer(int target, int buffer) { throw new UnsupportedOperationException(); } public void glBufferData(int target, int size, Buffer data, int usage) { throw new UnsupportedOperationException(); } public void glBufferSubData(int target, int offset, int size, Buffer data) { throw new UnsupportedOperationException(); } public void glColor4ub(byte red, byte green, byte blue, byte alpha) { throw new UnsupportedOperationException(); } public void glDeleteBuffers(int n, int[] buffers, int offset) { throw new UnsupportedOperationException(); } public void glDeleteBuffers(int n, IntBuffer buffers) { throw new UnsupportedOperationException(); } public void glGenBuffers(int n, int[] buffers, int offset) { throw new UnsupportedOperationException(); } public void glGenBuffers(int n, IntBuffer buffers) { throw new UnsupportedOperationException(); } public void glGetBooleanv(int pname, boolean[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetBooleanv(int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetBufferParameteriv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetBufferParameteriv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetClipPlanef(int pname, float[] eqn, int offset) { throw new UnsupportedOperationException(); } public void glGetClipPlanef(int pname, FloatBuffer eqn) { throw new UnsupportedOperationException(); } public void glGetClipPlanex(int pname, int[] eqn, int offset) { throw new UnsupportedOperationException(); } public void glGetClipPlanex(int pname, IntBuffer eqn) { throw new UnsupportedOperationException(); } public void glGetFixedv(int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetFixedv(int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetFloatv(int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetFloatv(int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetLightfv(int light, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetLightfv(int light, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetLightxv(int light, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetLightxv(int light, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetMaterialfv(int face, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetMaterialfv(int face, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetMaterialxv(int face, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetMaterialxv(int face, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexEnviv(int env, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexEnviv(int env, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexEnvxv(int env, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexEnvxv(int env, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexParameterfv(int target, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexParameterfv(int target, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexParameteriv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexParameteriv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexParameterxv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexParameterxv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public boolean glIsBuffer(int buffer) { throw new UnsupportedOperationException(); } public boolean glIsEnabled(int cap) { throw new UnsupportedOperationException(); } public boolean glIsTexture(int texture) { throw new UnsupportedOperationException(); } public void glPointParameterf(int pname, float param) { throw new UnsupportedOperationException(); } public void glPointParameterfv(int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glPointParameterfv(int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glPointParameterx(int pname, int param) { throw new UnsupportedOperationException(); } public void glPointParameterxv(int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glPointParameterxv(int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glPointSizePointerOES(int type, int stride, Buffer pointer) { throw new UnsupportedOperationException(); } public void glTexEnvi(int target, int pname, int param) { throw new UnsupportedOperationException(); } public void glTexEnviv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glTexEnviv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glTexParameterfv(int target, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glTexParameterfv(int target, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glTexParameteri(int target, int pname, int param) { throw new UnsupportedOperationException(); } public void glTexParameterxv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glTexParameterxv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glColorPointer(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glDrawElements(int mode, int count, int type, int offset) { throw new UnsupportedOperationException(); } public void glGetPointerv(int pname, Buffer[] params) { throw new UnsupportedOperationException(); } public void glNormalPointer(int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glTexCoordPointer(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glVertexPointer(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glCurrentPaletteMatrixOES(int matrixpaletteindex) { throw new UnsupportedOperationException(); } public void glLoadPaletteFromModelViewMatrixOES() { throw new UnsupportedOperationException(); } public void glMatrixIndexPointerOES(int size, int type, int stride, Buffer pointer) { throw new UnsupportedOperationException(); } public void glMatrixIndexPointerOES(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glWeightPointerOES(int size, int type, int stride, Buffer pointer) { throw new UnsupportedOperationException(); } public void glWeightPointerOES(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } /** * Get the current matrix */ public void getMatrix(float[] m, int offset) { mCurrent.getMatrix(m, offset); } /** * Get the current matrix mode */ public int getMatrixMode() { return mMatrixMode; } private void check() { int oesMode; switch (mMatrixMode) { case GL_MODELVIEW: oesMode = GL11.GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES; break; case GL_PROJECTION: oesMode = GL11.GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES; break; case GL_TEXTURE: oesMode = GL11.GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES; break; default: throw new IllegalArgumentException("Unknown matrix mode"); } if ( mByteBuffer == null) { mCheckA = new float[16]; mCheckB = new float[16]; mByteBuffer = ByteBuffer.allocateDirect(64); mByteBuffer.order(ByteOrder.nativeOrder()); mFloatBuffer = mByteBuffer.asFloatBuffer(); } mgl.glGetIntegerv(oesMode, mByteBuffer.asIntBuffer()); for(int i = 0; i < 16; i++) { mCheckB[i] = mFloatBuffer.get(i); } mCurrent.getMatrix(mCheckA, 0); boolean fail = false; for(int i = 0; i < 16; i++) { if (mCheckA[i] != mCheckB[i]) { Log.d("GLMatWrap", "i:" + i + " a:" + mCheckA[i] + " a:" + mCheckB[i]); fail = true; } } if (fail) { throw new IllegalArgumentException("Matrix math difference."); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import javax.microedition.khronos.opengles.GL; import android.app.Activity; import android.os.Bundle; public class SpriteTextActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mGLView = (GLView) findViewById(R.id.glview); mGLView.setGLWrapper(new GLView.GLWrapper() { public GL wrap(GL gl) { return new MatrixTrackingGL(gl); }}); mGLView.setRenderer(new SpriteTextRenderer(this)); mGLView.requestFocus(); } @Override protected void onPause() { super.onPause(); mGLView.onPause(); } @Override protected void onResume() { super.onResume(); mGLView.onResume(); } private GLView mGLView; }
Java
/* * Copyright (C) 2007 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.opengles.spritetext; import java.nio.CharBuffer; import java.nio.FloatBuffer; import javax.microedition.khronos.opengles.GL10; /** * A 2D rectangular mesh. Can be drawn textured or untextured. * */ class Grid { public Grid(int w, int h) { if (w < 0 || w >= 65536) { throw new IllegalArgumentException("w"); } if (h < 0 || h >= 65536) { throw new IllegalArgumentException("h"); } if (w * h >= 65536) { throw new IllegalArgumentException("w * h >= 65536"); } mW = w; mH = h; int size = w * h; mVertexArray = new float[size * 3]; mVertexBuffer = FloatBuffer.wrap(mVertexArray); mTexCoordArray = new float[size * 2]; mTexCoordBuffer = FloatBuffer.wrap(mTexCoordArray); int quadW = mW - 1; int quadH = mH - 1; int quadCount = quadW * quadH; int indexCount = quadCount * 6; mIndexCount = indexCount; char[] indexArray = new char[indexCount]; /* * Initialize triangle list mesh. * * [0]-----[ 1] ... * | / | * | / | * | / | * [w]-----[w+1] ... * | | * */ { int i = 0; for (int y = 0; y < quadH; y++) { for (int x = 0; x < quadW; x++) { char a = (char) (y * mW + x); char b = (char) (y * mW + x + 1); char c = (char) ((y + 1) * mW + x); char d = (char) ((y + 1) * mW + x + 1); indexArray[i++] = a; indexArray[i++] = b; indexArray[i++] = c; indexArray[i++] = b; indexArray[i++] = c; indexArray[i++] = d; } } } mIndexBuffer = CharBuffer.wrap(indexArray); } void set(int i, int j, float x, float y, float z, float u, float v) { if (i < 0 || i >= mW) { throw new IllegalArgumentException("i"); } if (j < 0 || j >= mH) { throw new IllegalArgumentException("j"); } int index = mW * j + i; int posIndex = index * 3; mVertexArray[posIndex] = x; mVertexArray[posIndex + 1] = y; mVertexArray[posIndex + 2] = z; int texIndex = index * 2; mTexCoordArray[texIndex] = u; mTexCoordArray[texIndex + 1] = v; } public void draw(GL10 gl, boolean useTexture) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer); if (useTexture) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexCoordBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); } else { gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glDisable(GL10.GL_TEXTURE_2D); } gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } private FloatBuffer mVertexBuffer; private float[] mVertexArray; private FloatBuffer mTexCoordBuffer; private float[] mTexCoordArray; private CharBuffer mIndexBuffer; private int mW; private int mH; private int mIndexCount; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.triangle; import javax.microedition.khronos.opengles.GL; import android.app.Activity; import android.opengl.GLDebugHelper; import android.os.Bundle; public class TriangleActivity extends Activity { /** Set to true to enable checking of the OpenGL error code after every OpenGL call. Set to * false for faster code. * */ private final static boolean DEBUG_CHECK_GL_ERROR = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mGLView = (GLView) findViewById(R.id.glview); if (DEBUG_CHECK_GL_ERROR) { mGLView.setGLWrapper(new GLView.GLWrapper() { public GL wrap(GL gl) { return GLDebugHelper.wrap(gl, GLDebugHelper.CONFIG_CHECK_GL_ERROR, null); }}); } mGLView.setRenderer(new TriangleRenderer(this)); mGLView.requestFocus(); } @Override protected void onPause() { super.onPause(); mGLView.onPause(); } @Override protected void onResume() { super.onResume(); mGLView.onResume(); } private GLView mGLView; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.triangle; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLU; import android.opengl.GLUtils; import android.os.SystemClock; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.opengles.GL10; public class TriangleRenderer implements GLView.Renderer{ public TriangleRenderer(Context context) { mContext = context; mTriangle = new Triangle(); } public int[] getConfigSpec() { // We don't need a depth buffer, and don't care about our // color depth. int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_NONE }; return configSpec; } public void surfaceCreated(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); /* * Some one-time OpenGL initialization can be made here * probably based on features of this particular context */ gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); gl.glClearColor(.5f, .5f, .5f, 1); gl.glShadeModel(GL10.GL_SMOOTH); gl.glEnable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_TEXTURE_2D); /* * Create our texture. This has to be done each time the * surface is created. */ int[] textures = new int[1]; gl.glGenTextures(1, textures, 0); mTextureID = textures[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); InputStream is = mContext.getResources() .openRawResource(R.drawable.tex); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is); } finally { try { is.close(); } catch(IOException e) { // Ignore. } } GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); } public void drawFrame(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE); /* * Usually, the first thing one might want to do is to clear * the screen. The most efficient way of doing this is to use * glClear(). */ gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); /* * Now we're ready to draw some 3D objects */ gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glActiveTexture(GL10.GL_TEXTURE0); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); long time = SystemClock.uptimeMillis() % 4000L; float angle = 0.090f * ((int) time); gl.glRotatef(angle, 0, 0, 1.0f); mTriangle.draw(gl); } public void sizeChanged(GL10 gl, int w, int h) { gl.glViewport(0, 0, w, h); /* * Set our projection matrix. This doesn't have to be done * each time we draw, but usually a new projection needs to * be set when the viewport is resized. */ float ratio = (float) w / h; gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7); } private Context mContext; private Triangle mTriangle; private int mTextureID; } class Triangle { public Triangle() { // Buffers to be passed to gl*Pointer() functions // must be direct, i.e., they must be placed on the // native heap where the garbage collector cannot // move them. // // Buffers with multi-byte datatypes (e.g., short, int, float) // must have their byte order set to native order ByteBuffer vbb = ByteBuffer.allocateDirect(VERTS * 3 * 4); vbb.order(ByteOrder.nativeOrder()); mFVertexBuffer = vbb.asFloatBuffer(); ByteBuffer tbb = ByteBuffer.allocateDirect(VERTS * 2 * 4); tbb.order(ByteOrder.nativeOrder()); mTexBuffer = tbb.asFloatBuffer(); ByteBuffer ibb = ByteBuffer.allocateDirect(VERTS * 2); ibb.order(ByteOrder.nativeOrder()); mIndexBuffer = ibb.asShortBuffer(); // A unit-sided equalateral triangle centered on the origin. float[] coords = { // X, Y, Z -0.5f, -0.25f, 0, 0.5f, -0.25f, 0, 0.0f, 0.559016994f, 0 }; for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 3; j++) { mFVertexBuffer.put(coords[i*3+j] * 2.0f); } } for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 2; j++) { mTexBuffer.put(coords[i*3+j] * 2.0f + 0.5f); } } for(int i = 0; i < VERTS; i++) { mIndexBuffer.put((short) i); } mFVertexBuffer.position(0); mTexBuffer.position(0); mIndexBuffer.position(0); } public void draw(GL10 gl) { gl.glFrontFace(GL10.GL_CCW); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFVertexBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer); gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, VERTS, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); } private final static int VERTS = 3; private FloatBuffer mFVertexBuffer; private FloatBuffer mTexBuffer; private ShortBuffer mIndexBuffer; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.triangle; import android.content.Context; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.util.ArrayList; import java.util.concurrent.Semaphore; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; /** * An implementation of SurfaceView that uses the dedicated surface for * displaying an OpenGL animation. This allows the animation to run in a * separate thread, without requiring that it be driven by the update mechanism * of the view hierarchy. * * The application-specific rendering code is delegated to a GLView.Renderer * instance. */ class GLView extends SurfaceView implements SurfaceHolder.Callback { GLView(Context context) { super(context); init(); } public GLView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU); } public void setGLWrapper(GLWrapper glWrapper) { mGLWrapper = glWrapper; } public void setRenderer(Renderer renderer) { mGLThread = new GLThread(renderer); mGLThread.start(); } public void surfaceCreated(SurfaceHolder holder) { mGLThread.surfaceCreated(); } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return mGLThread.surfaceDestroyed(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Surface size or format has changed. This should not happen in this // example. mGLThread.onWindowResize(w, h); } /** * Inform the view that the activity is paused. */ public void onPause() { mGLThread.onPause(); } /** * Inform the view that the activity is resumed. */ public void onResume() { mGLThread.onResume(); } /** * Inform the view that the window focus has changed. */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mGLThread.onWindowFocusChanged(hasFocus); } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { mGLThread.queueEvent(r); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mGLThread.requestExitAndWait(); } // ---------------------------------------------------------------------- public interface GLWrapper { GL wrap(GL gl); } // ---------------------------------------------------------------------- /** * A generic renderer interface. */ public interface Renderer { /** * @return the EGL configuration specification desired by the renderer. */ int[] getConfigSpec(); /** * Surface created. * Called when the surface is created. Called when the application * starts, and whenever the GPU is reinitialized. This will * typically happen when the device awakes after going to sleep. * Set your textures here. */ void surfaceCreated(GL10 gl); /** * Surface changed size. * Called after the surface is created and whenever * the OpenGL ES surface size changes. Set your viewport here. * @param gl * @param width * @param height */ void sizeChanged(GL10 gl, int width, int height); /** * Draw the current frame. * @param gl */ void drawFrame(GL10 gl); } /** * An EGL helper class. */ private class EglHelper { public EglHelper() { } /** * Initialize EGL for a given configuration spec. * @param configSpec */ public void start(int[] configSpec){ /* * Get an EGL instance */ mEgl = (EGL10) EGLContext.getEGL(); /* * Get to the default display. */ mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); /* * We can now initialize EGL for that display */ int[] version = new int[2]; mEgl.eglInitialize(mEglDisplay, version); EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1, num_config); mEglConfig = configs[0]; /* * Create an OpenGL ES context. This must be done only once, an * OpenGL context is a somewhat heavy object. */ mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig, EGL10.EGL_NO_CONTEXT, null); mEglSurface = null; } /* * Create and return an OpenGL surface */ public GL createSurface(SurfaceHolder holder) { /* * The window size has changed, so we need to create a new * surface. */ if (mEglSurface != null) { /* * Unbind and destroy the old EGL surface, if * there is one. */ mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); } /* * Create an EGL surface we can render into. */ mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, holder, null); /* * Before we can issue GL commands, we need to make sure * the context is current and bound to a surface. */ mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext); GL gl = mEglContext.getGL(); if (mGLWrapper != null) { gl = mGLWrapper.wrap(gl); } return gl; } /** * Display the current render surface. * @return false if the context has been lost. */ public boolean swap() { mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); /* * Always check for EGL_CONTEXT_LOST, which means the context * and all associated data were lost (For instance because * the device went to sleep). We need to sleep until we * get a new surface. */ return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; } public void finish() { if (mEglSurface != null) { mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); mEglSurface = null; } if (mEglContext != null) { mEgl.eglDestroyContext(mEglDisplay, mEglContext); mEglContext = null; } if (mEglDisplay != null) { mEgl.eglTerminate(mEglDisplay); mEglDisplay = null; } } EGL10 mEgl; EGLDisplay mEglDisplay; EGLSurface mEglSurface; EGLConfig mEglConfig; EGLContext mEglContext; } /** * A generic GL Thread. Takes care of initializing EGL and GL. Delegates * to a Renderer instance to do the actual drawing. * */ class GLThread extends Thread { GLThread(Renderer renderer) { super(); mDone = false; mWidth = 0; mHeight = 0; mRenderer = renderer; setName("GLThread"); } @Override public void run() { /* * When the android framework launches a second instance of * an activity, the new instance's onCreate() method may be * called before the first instance returns from onDestroy(). * * This semaphore ensures that only one instance at a time * accesses EGL. */ try { try { sEglSemaphore.acquire(); } catch (InterruptedException e) { return; } guardedRun(); } catch (InterruptedException e) { // fall thru and exit normally } finally { sEglSemaphore.release(); } } private void guardedRun() throws InterruptedException { mEglHelper = new EglHelper(); /* * Specify a configuration for our opengl session * and grab the first configuration that matches is */ int[] configSpec = mRenderer.getConfigSpec(); mEglHelper.start(configSpec); GL10 gl = null; boolean tellRendererSurfaceCreated = true; boolean tellRendererSurfaceChanged = true; /* * This is our main activity thread's loop, we go until * asked to quit. */ while (!mDone) { /* * Update the asynchronous state (window size) */ int w, h; boolean changed; boolean needStart = false; synchronized (this) { Runnable r; while ((r = getEvent()) != null) { r.run(); } if (mPaused) { mEglHelper.finish(); needStart = true; } if(needToWait()) { while (needToWait()) { wait(); } } if (mDone) { break; } changed = mSizeChanged; w = mWidth; h = mHeight; mSizeChanged = false; } if (needStart) { mEglHelper.start(configSpec); tellRendererSurfaceCreated = true; changed = true; } if (changed) { gl = (GL10) mEglHelper.createSurface(mHolder); tellRendererSurfaceChanged = true; } if (tellRendererSurfaceCreated) { mRenderer.surfaceCreated(gl); tellRendererSurfaceCreated = false; } if (tellRendererSurfaceChanged) { mRenderer.sizeChanged(gl, w, h); tellRendererSurfaceChanged = false; } if ((w > 0) && (h > 0)) { /* draw a frame here */ mRenderer.drawFrame(gl); /* * Once we're done with GL, we need to call swapBuffers() * to instruct the system to display the rendered frame */ mEglHelper.swap(); } } /* * clean-up everything... */ mEglHelper.finish(); } private boolean needToWait() { return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost) && (! mDone); } public void surfaceCreated() { synchronized(this) { mHasSurface = true; mContextLost = false; notify(); } } public void surfaceDestroyed() { synchronized(this) { mHasSurface = false; notify(); } } public void onPause() { synchronized (this) { mPaused = true; } } public void onResume() { synchronized (this) { mPaused = false; notify(); } } public void onWindowFocusChanged(boolean hasFocus) { synchronized (this) { mHasFocus = hasFocus; if (mHasFocus == true) { notify(); } } } public void onWindowResize(int w, int h) { synchronized (this) { mWidth = w; mHeight = h; mSizeChanged = true; } } public void requestExitAndWait() { // don't call this from GLThread thread or it is a guaranteed // deadlock! synchronized(this) { mDone = true; notify(); } try { join(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { synchronized(this) { mEventQueue.add(r); } } private Runnable getEvent() { synchronized(this) { if (mEventQueue.size() > 0) { return mEventQueue.remove(0); } } return null; } private boolean mDone; private boolean mPaused; private boolean mHasFocus; private boolean mHasSurface; private boolean mContextLost; private int mWidth; private int mHeight; private Renderer mRenderer; private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>(); private EglHelper mEglHelper; } private static final Semaphore sEglSemaphore = new Semaphore(1); private boolean mSizeChanged = true; private SurfaceHolder mHolder; private GLThread mGLThread; private GLWrapper mGLWrapper; }
Java
package com.google.clickin2dabeat; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; /** * Checks for updates to the game. */ public class UpdateChecker { public String marketId; @SuppressWarnings("finally") public int getLatestVersionCode() { int version = 0; try { URLConnection cn; URL url = new URL( "http://apps-for-android.googlecode.com/svn/trunk/CLiCkin2DaBeaT/AndroidManifest.xml"); cn = url.openConnection(); cn.connect(); InputStream stream = cn.getInputStream(); DocumentBuilder docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document manifestDoc = docBuild.parse(stream); NodeList manifestNodeList = manifestDoc.getElementsByTagName("manifest"); String versionStr = manifestNodeList.item(0).getAttributes().getNamedItem("android:versionCode") .getNodeValue(); version = Integer.parseInt(versionStr); NodeList clcNodeList = manifestDoc.getElementsByTagName("clc"); marketId = clcNodeList.item(0).getAttributes().getNamedItem("marketId").getNodeValue(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { return version; } } public void checkForNewerVersion(int currentVersion) { int latestVersion = getLatestVersionCode(); if (latestVersion > currentVersion) { } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import android.graphics.Color; /** * Contains information about the when the beat should be displayed, where it * should be displayed, and what color it should be. */ public class Target { public double time; public int x; public int y; public int color; public Target(double timeToHit, int xpos, int ypos, String hexColor) { time = timeToHit; x = xpos; y = ypos; if (hexColor.length() == 6) { int r = Integer.parseInt(hexColor.substring(0, 2), 16); int g = Integer.parseInt(hexColor.substring(2, 4), 16); int b = Integer.parseInt(hexColor.substring(4, 6), 16); color = Color.rgb(r, g, b); } else { int colorChoice = ((int) (Math.random() * 100)) % 4; if (colorChoice == 0) { color = Color.RED; } else if (colorChoice == 1) { color = Color.GREEN; } else if (colorChoice == 2) { color = Color.BLUE; } else { color = Color.YELLOW; } } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; public class DownloadC2BFile extends Activity { String dataSource; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); dataSource = this.getIntent().getData().toString(); (new Thread(new loader())).start(); } public void runMem() { startApp("com.google.clickin2dabeat", "C2B"); finish(); } private void startApp(String packageName, String className) { try { int flags = Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY; Context myContext = createPackageContext(packageName, flags); Class<?> appClass = myContext.getClassLoader().loadClass(packageName + "." + className); Intent intent = new Intent(myContext, appClass); startActivity(intent); } catch (NameNotFoundException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public class loader implements Runnable { public void run() { Unzipper.unzip(dataSource); runMem(); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.File; import java.io.FileWriter; import java.io.IOException; /** * Creates a skeleton C2B file when an appropriate media object is opened. */ public class CreateC2BFile extends Activity { private String dataSource; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); dataSource = this.getIntent().getData().toString(); setContentView(R.layout.c2b_creator_form); Button create = ((Button) findViewById(R.id.CreateButton)); create.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { String title = ((EditText) findViewById(R.id.TitleEditText)).getText().toString(); String author = ((EditText) findViewById(R.id.AuthorEditText)).getText().toString(); if (!title.equals("") && !author.equals("")) { createC2BSkeleton(title, author, dataSource); finish(); } } }); Button cancel = ((Button) findViewById(R.id.CancelButton)); cancel.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { finish(); } }); } private void createC2BSkeleton(String title, String author, String media) { String c2bDirStr = "/sdcard/c2b/"; String sanitizedTitle = title.replaceAll("'", " "); String sanitizedAuthor = author.replaceAll("'", " "); String filename = sanitizedTitle.replaceAll("[^a-zA-Z0-9,\\s]", ""); filename = c2bDirStr + filename + ".c2b"; String contents = "<c2b title='" + title + "' level='1' author='" + author + "' media='" + media + "'></c2b>"; File c2bDir = new File(c2bDirStr); boolean directoryExists = c2bDir.isDirectory(); if (!directoryExists) { c2bDir.mkdir(); } try { FileWriter writer = new FileWriter(filename); writer.write(contents); writer.close(); Toast.makeText(CreateC2BFile.this, getString(R.string.STAGE_CREATED), 5000).show(); } catch (IOException e) { Toast.makeText(CreateC2BFile.this, getString(R.string.NEED_SD_CARD), 30000).show(); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import java.util.ArrayList; /** * Adjusts the times for the beat targets using a linear least-squares fit. */ public class BeatTimingsAdjuster { private double[] adjustedBeatTimes; public void setRawBeatTimes(ArrayList<Integer> rawBeatTimes) { double[] beatTimes = new double[rawBeatTimes.size()]; for (int i = 0; i < beatTimes.length; i++) { beatTimes[i] = rawBeatTimes.get(i); } adjustedBeatTimes = new double[beatTimes.length]; double[] beatNumbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; double n = beatNumbers.length; // Some things can be computed once and never computed again double[] beatNumbersXNumbers = multiplyArrays(beatNumbers, beatNumbers); double sumOfBeatNumbersXNumbers = sum(beatNumbersXNumbers); double sumOfBeatNumbers = sum(beatNumbers); // The divisor is: // (n * sum(beatNumbersXNumbers) - (sum(beatNumbers) * sum(beatNumbers))) // Since these are all constants, they can be computed first for better // efficiency. double divisor = (n * sum(beatNumbersXNumbers) - (sum(beatNumbers) * sum(beatNumbers))); // Not enough data to adjust for the first 5 beats for (int i = 0; (i < beatTimes.length) && (i < 5); i++) { adjustedBeatTimes[i] = beatTimes[i]; } // Adjust time for beat i by using timings for beats i-5 through i+5 double[] beatWindow = new double[beatNumbers.length]; for (int i = 0; i < beatTimes.length - 10; i++) { System.arraycopy(beatTimes, i, beatWindow, 0, beatNumbers.length); double[] beatNumbersXTimes = multiplyArrays(beatNumbers, beatWindow); double a = (sum(beatTimes) * sumOfBeatNumbersXNumbers - sumOfBeatNumbers * sum(beatNumbersXTimes)) / divisor; double b = (n * sum(beatNumbersXTimes) - sumOfBeatNumbers * sum(beatTimes)) / divisor; adjustedBeatTimes[i + 5] = a + b * beatNumbers[5]; } if (beatTimes.length - 10 < 0) { return; } // Not enough data to adjust for the last 5 beats for (int i = beatTimes.length - 10; i < beatTimes.length; i++) { adjustedBeatTimes[i] = beatTimes[i]; } } public ArrayList<Target> adjustBeatTargets(ArrayList<Target> rawTargets) { ArrayList<Target> adjustedTargets = new ArrayList<Target>(); int j = 0; double threshold = 200; for (int i = 0; i < rawTargets.size(); i++) { Target t = rawTargets.get(i); while ((j < adjustedBeatTimes.length) && (adjustedBeatTimes[j] < t.time)) { j++; } double prevTime = 0; if (j > 0) { prevTime = adjustedBeatTimes[j - 1]; } double postTime = -1; if (j < adjustedBeatTimes.length) { postTime = adjustedBeatTimes[j]; } if ((Math.abs(t.time - prevTime) < Math.abs(t.time - postTime)) && Math.abs(t.time - prevTime) < threshold) { t.time = prevTime; } else if ((Math.abs(t.time - prevTime) > Math.abs(t.time - postTime)) && Math.abs(t.time - postTime) < threshold) { t.time = postTime; } adjustedTargets.add(t); } return adjustedTargets; } private double sum(double[] numbers) { double sum = 0; for (int i = 0; i < numbers.length; i++) { sum = sum + numbers[i]; } return sum; } private double[] multiplyArrays(double[] numberSetA, double[] numberSetB) { double[] sqArray = new double[numberSetA.length]; for (int i = 0; i < numberSetA.length; i++) { sqArray[i] = numberSetA[i] * numberSetB[i]; } return sqArray; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import android.app.Activity; import android.app.AlertDialog.Builder; import android.content.ComponentName; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnErrorListener; import android.media.MediaPlayer.OnPreparedListener; import android.net.Uri; import android.os.Bundle; import android.widget.FrameLayout; import android.widget.Toast; import android.widget.VideoView; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; /** * A rhythm/music game for Android that can use any video as the background. */ public class C2B extends Activity { public static final int GAME_MODE = 0; public static final int TWOPASS_MODE = 1; public static final int ONEPASS_MODE = 2; public int mode; public boolean wasEditMode; private boolean forceEditMode; private VideoView background; private GameView foreground; private FrameLayout layout; private String c2bFileName; private String[] filenames; private String marketId; // These are parsed in from the C2B file private String title; private String author; private String level; private String media; private Uri videoUri; public ArrayList<Target> targets; public ArrayList<Integer> beatTimes; private BeatTimingsAdjuster timingAdjuster; private boolean busyProcessing; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); UpdateChecker checker = new UpdateChecker(); int latestVersion = checker.getLatestVersionCode(); String packageName = C2B.class.getPackage().getName(); int currentVersion = 0; try { currentVersion = getPackageManager().getPackageInfo(packageName, 0).versionCode; } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (latestVersion > currentVersion){ marketId = checker.marketId; displayUpdateMessage(); } else { resetGame(); } } private void resetGame() { targets = new ArrayList<Target>(); mode = GAME_MODE; forceEditMode = false; wasEditMode = false; busyProcessing = false; c2bFileName = ""; title = ""; author = ""; level = ""; media = ""; background = null; foreground = null; layout = null; background = new VideoView(this); foreground = new GameView(this); layout = new FrameLayout(this); layout.addView(background); layout.setPadding(30, 0, 0, 0); // Is there a better way to do layout? beatTimes = null; timingAdjuster = null; background.setOnPreparedListener(new OnPreparedListener() { public void onPrepared(MediaPlayer mp) { background.start(); } }); background.setOnErrorListener(new OnErrorListener() { public boolean onError(MediaPlayer arg0, int arg1, int arg2) { background.setVideoURI(videoUri); return true; } }); background.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { if (mode == ONEPASS_MODE) { Toast waitMessage = Toast.makeText(C2B.this, getString(R.string.PROCESSING), 5000); waitMessage.show(); (new Thread(new BeatsWriter())).start(); } else if (mode == TWOPASS_MODE) { mode = ONEPASS_MODE; (new Thread(new BeatsTimingAdjuster())).start(); displayCreateLevelInfo(); return; } displayStats(); } }); layout.addView(foreground); setContentView(layout); setVolumeControlStream(AudioManager.STREAM_MUSIC); displayStartupMessage(); } private void writeC2BFile(String filename) { String contents = "<c2b title='" + title + "' level='" + level + "' author='" + author + "' media='" + media + "'>"; ArrayList<Target> targets = foreground.recordedTargets; if (timingAdjuster != null) { targets = timingAdjuster.adjustBeatTargets(foreground.recordedTargets); } for (int i = 0; i < targets.size(); i++) { Target t = targets.get(i); contents = contents + "<beat time='" + Double.toString(t.time) + "' "; contents = contents + "x='" + Integer.toString(t.x) + "' "; contents = contents + "y='" + Integer.toString(t.y) + "' "; contents = contents + "color='" + Integer.toHexString(t.color) + "'/>"; } contents = contents + "</c2b>"; try { FileWriter writer = new FileWriter(filename); writer.write(contents); writer.close(); } catch (IOException e) { // TODO(clchen): Do better error handling here e.printStackTrace(); } } private void loadC2B(String fileUriString) { try { FileInputStream fis = new FileInputStream(fileUriString); DocumentBuilder docBuild; docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document c2b = docBuild.parse(fis); runC2B(c2b); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void runC2B(Document c2b) { Node root = c2b.getElementsByTagName("c2b").item(0); title = root.getAttributes().getNamedItem("title").getNodeValue(); author = root.getAttributes().getNamedItem("author").getNodeValue(); level = root.getAttributes().getNamedItem("level").getNodeValue(); media = root.getAttributes().getNamedItem("media").getNodeValue(); NodeList beats = c2b.getElementsByTagName("beat"); targets = new ArrayList<Target>(); for (int i = 0; i < beats.getLength(); i++) { NamedNodeMap attribs = beats.item(i).getAttributes(); double time = Double.parseDouble(attribs.getNamedItem("time").getNodeValue()); int x = Integer.parseInt(attribs.getNamedItem("x").getNodeValue()); int y = Integer.parseInt(attribs.getNamedItem("y").getNodeValue()); String colorStr = attribs.getNamedItem("color").getNodeValue(); targets.add(new Target(time, x, y, colorStr)); } if ((beats.getLength() == 0) || forceEditMode) { displayCreateLevelAlert(); } else { videoUri = Uri.parse(media); background.setVideoURI(videoUri); } } private void displayCreateLevelAlert() { mode = ONEPASS_MODE; Builder createLevelAlert = new Builder(this); String titleText = getString(R.string.NO_BEATS) + " \"" + title + "\""; createLevelAlert.setTitle(titleText); String[] choices = new String[2]; choices[0] = getString(R.string.ONE_PASS); choices[1] = getString(R.string.TWO_PASS); createLevelAlert.setSingleChoiceItems(choices, 0, new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (which == 0) { mode = ONEPASS_MODE; } else { mode = TWOPASS_MODE; } } }); createLevelAlert.setPositiveButton("Ok", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (busyProcessing) { Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show(); displayCreateLevelAlert(); return; } wasEditMode = true; if (mode == TWOPASS_MODE) { beatTimes = new ArrayList<Integer>(); timingAdjuster = new BeatTimingsAdjuster(); } displayCreateLevelInfo(); } }); createLevelAlert.setNegativeButton("Cancel", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (busyProcessing) { Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show(); displayCreateLevelAlert(); return; } displayC2BFiles(); } }); createLevelAlert.setCancelable(false); createLevelAlert.show(); } private void displayC2BFiles() { Builder c2bFilesAlert = new Builder(this); String titleText = getString(R.string.CHOOSE_STAGE); c2bFilesAlert.setTitle(titleText); File c2bDir = new File("/sdcard/c2b/"); filenames = c2bDir.list(new FilenameFilter() { public boolean accept(File dir, String filename) { return filename.endsWith(".c2b"); } }); if (filenames == null) { displayNoFilesMessage(); return; } if (filenames.length == 0) { displayNoFilesMessage(); return; } c2bFilesAlert.setSingleChoiceItems(filenames, -1, new OnClickListener() { public void onClick(DialogInterface dialog, int which) { c2bFileName = "/sdcard/c2b/" + filenames[which]; } }); c2bFilesAlert.setPositiveButton("Go!", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { loadC2B(c2bFileName); dialog.dismiss(); } }); /* c2bFilesAlert.setNeutralButton("Set new beats", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); displaySetNewBeatsConfirmation(); } }); */ final Activity self = this; c2bFilesAlert.setNeutralButton(getString(R.string.MOAR_STAGES), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(); ComponentName comp = new ComponentName("com.android.browser", "com.android.browser.BrowserActivity"); i.setComponent(comp); i.setAction("android.intent.action.VIEW"); i.addCategory("android.intent.category.BROWSABLE"); Uri uri = Uri.parse("http://groups.google.com/group/clickin-2-da-beat/files"); i.setData(uri); self.startActivity(i); finish(); } }); c2bFilesAlert.setNegativeButton(getString(R.string.QUIT), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); c2bFilesAlert.setCancelable(false); c2bFilesAlert.show(); } /* private void displaySetNewBeatsConfirmation() { Builder setNewBeatsConfirmation = new Builder(this); String titleText = getString(R.string.EDIT_CONFIRMATION); setNewBeatsConfirmation.setTitle(titleText); String message = getString(R.string.EDIT_WARNING); setNewBeatsConfirmation.setMessage(message); setNewBeatsConfirmation.setPositiveButton("Continue", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { forceEditMode = true; loadC2B(c2bFileName); dialog.dismiss(); } }); setNewBeatsConfirmation.setNegativeButton("Cancel", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { displayC2BFiles(); dialog.dismiss(); } }); setNewBeatsConfirmation.setCancelable(false); setNewBeatsConfirmation.show(); } */ private void displayCreateLevelInfo() { Builder createLevelInfoAlert = new Builder(this); String titleText = getString(R.string.BEAT_SETTING_INFO); createLevelInfoAlert.setTitle(titleText); String message = ""; if (mode == TWOPASS_MODE) { message = getString(R.string.TWO_PASS_INFO); } else { message = getString(R.string.ONE_PASS_INFO); } createLevelInfoAlert.setMessage(message); createLevelInfoAlert.setPositiveButton("Start", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); videoUri = Uri.parse(media); background.setVideoURI(videoUri); } }); createLevelInfoAlert.setCancelable(false); createLevelInfoAlert.show(); } private void displayStats() { Builder statsAlert = new Builder(this); String titleText = ""; if (!wasEditMode) { titleText = "Game Over"; } else { titleText = "Stage created!"; } statsAlert.setTitle(titleText); int longestCombo = foreground.longestCombo; if (foreground.comboCount > longestCombo) { longestCombo = foreground.comboCount; } String message = ""; if (!wasEditMode) { message = "Longest combo: " + Integer.toString(longestCombo); } else { message = "Beats recorded!"; } statsAlert.setMessage(message); statsAlert.setPositiveButton("Play", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (busyProcessing) { Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show(); displayStats(); return; } resetGame(); } }); statsAlert.setNegativeButton("Quit", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (busyProcessing) { Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show(); displayStats(); return; } finish(); } }); statsAlert.setCancelable(false); statsAlert.show(); } private void displayNoFilesMessage() { Builder noFilesMessage = new Builder(this); String titleText = getString(R.string.NO_STAGES_FOUND); noFilesMessage.setTitle(titleText); String message = getString(R.string.NO_STAGES_INFO); noFilesMessage.setMessage(message); noFilesMessage.setPositiveButton(getString(R.string.SHUT_UP), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { loadHardCodedRickroll(); } }); final Activity self = this; noFilesMessage.setNeutralButton(getString(R.string.ILL_GET_STAGES), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(); ComponentName comp = new ComponentName("com.android.browser", "com.android.browser.BrowserActivity"); i.setComponent(comp); i.setAction("android.intent.action.VIEW"); i.addCategory("android.intent.category.BROWSABLE"); Uri uri = Uri.parse("http://groups.google.com/group/clickin-2-da-beat/files"); i.setData(uri); self.startActivity(i); finish(); } }); noFilesMessage.setNegativeButton(getString(R.string.QUIT), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); noFilesMessage.setCancelable(false); noFilesMessage.show(); } private void loadHardCodedRickroll() { try { Resources res = getResources(); InputStream fis = res.openRawResource(R.raw.rickroll); DocumentBuilder docBuild; docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document c2b = docBuild.parse(fis); runC2B(c2b); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void displayStartupMessage() { Builder startupMessage = new Builder(this); String titleText = getString(R.string.WELCOME); startupMessage.setTitle(titleText); String message = getString(R.string.BETA_MESSAGE); startupMessage.setMessage(message); startupMessage.setPositiveButton(getString(R.string.START_GAME), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { displayC2BFiles(); } }); final Activity self = this; startupMessage.setNeutralButton(getString(R.string.VISIT_WEBSITE), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(); ComponentName comp = new ComponentName("com.android.browser", "com.android.browser.BrowserActivity"); i.setComponent(comp); i.setAction("android.intent.action.VIEW"); i.addCategory("android.intent.category.BROWSABLE"); Uri uri = Uri.parse("http://groups.google.com/group/clickin-2-da-beat"); i.setData(uri); self.startActivity(i); finish(); } }); startupMessage.setNegativeButton(getString(R.string.QUIT), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); startupMessage.setCancelable(false); startupMessage.show(); } private void displayUpdateMessage() { Builder updateMessage = new Builder(this); String titleText = getString(R.string.UPDATE_AVAILABLE); updateMessage.setTitle(titleText); String message = getString(R.string.UPDATE_MESSAGE); updateMessage.setMessage(message); updateMessage.setPositiveButton("Yes", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Uri marketUri = Uri.parse("market://details?id=" + marketId); Intent marketIntent = new Intent(Intent.ACTION_VIEW, marketUri); startActivity(marketIntent); finish(); } }); final Activity self = this; updateMessage.setNegativeButton("No", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { resetGame(); } }); updateMessage.setCancelable(false); updateMessage.show(); } public int getCurrentTime() { try { return background.getCurrentPosition(); } catch (IllegalStateException e) { // This will be thrown if the player is exiting mid-game and the video // view is going away at the same time as the foreground is trying to get // the position. This error can be safely ignored without doing anything. e.printStackTrace(); return 0; } } // Do beats processing in another thread to avoid hogging the UI thread and // generating a "not responding" error public class BeatsWriter implements Runnable { public void run() { writeC2BFile(c2bFileName); busyProcessing = false; } } public class BeatsTimingAdjuster implements Runnable { public void run() { timingAdjuster.setRawBeatTimes(beatTimes); busyProcessing = false; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.media.AudioManager; import android.media.SoundPool; import android.os.Vibrator; import android.view.MotionEvent; import android.view.View; import java.util.ArrayList; /** * Draws the beat targets and takes user input. * This view is used as the foreground; the background is the video * being played. */ public class GameView extends View { private static final long[] VIBE_PATTERN = {0, 1, 40, 41}; private static final int INTERVAL = 10; // in ms private static final int PRE_THRESHOLD = 1000; // in ms private static final int POST_THRESHOLD = 500; // in ms private static final int TOLERANCE = 100; // in ms private static final int POINTS_FOR_PERFECT = 100; private static final double PENALTY_FACTOR = .25; private static final double COMBO_FACTOR = .1; private static final float TARGET_RADIUS = 50; public static final String LAST_RATING_OK = "(^_')"; public static final String LAST_RATING_PERFECT = "(^_^)/"; public static final String LAST_RATING_MISS = "(X_X)"; private C2B parent; private Vibrator vibe; private SoundPool snd; private int hitOkSfx; private int hitPerfectSfx; private int missSfx; public int comboCount; public int longestCombo; public String lastRating; Paint innerPaint; Paint borderPaint; Paint haloPaint; private ArrayList<Target> drawnTargets; private int lastTarget; public ArrayList<Target> recordedTargets; private int score; public GameView(Context context) { super(context); parent = (C2B) context; lastTarget = 0; score = 0; comboCount = 0; longestCombo = 0; lastRating = ""; drawnTargets = new ArrayList<Target>(); recordedTargets = new ArrayList<Target>(); vibe = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); snd = new SoundPool(10, AudioManager.STREAM_SYSTEM, 0); missSfx = snd.load(context, R.raw.miss, 0); hitOkSfx = snd.load(context, R.raw.ok, 0); hitPerfectSfx = snd.load(context, R.raw.perfect, 0); innerPaint = new Paint(); innerPaint.setColor(Color.argb(127, 0, 0, 0)); innerPaint.setStyle(Paint.Style.FILL); borderPaint = new Paint(); borderPaint.setStyle(Paint.Style.STROKE); borderPaint.setAntiAlias(true); borderPaint.setStrokeWidth(2); haloPaint = new Paint(); haloPaint.setStyle(Paint.Style.STROKE); haloPaint.setAntiAlias(true); haloPaint.setStrokeWidth(4); Thread monitorThread = (new Thread(new Monitor())); monitorThread.setPriority(Thread.MIN_PRIORITY); monitorThread.start(); } private void updateTargets() { int i = lastTarget; int currentTime = parent.getCurrentTime(); // Add any targets that are within the pre-threshold to the list of // drawnTargets boolean cont = true; while (cont && (i < parent.targets.size())) { if (parent.targets.get(i).time < currentTime + PRE_THRESHOLD) { drawnTargets.add(parent.targets.get(i)); i++; } else { cont = false; } } lastTarget = i; // Move any expired targets out of drawn targets for (int j = 0; j < drawnTargets.size(); j++) { Target t = drawnTargets.get(j); if (t == null) { // Do nothing - this is a concurrency issue where // the target is already gone, so just ignore it } else if (t.time + POST_THRESHOLD < currentTime) { try { drawnTargets.remove(j); } catch (IndexOutOfBoundsException e){ // Do nothing here, j is already gone } if (longestCombo < comboCount) { longestCombo = comboCount; } comboCount = 0; lastRating = LAST_RATING_MISS; } } } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { int currentTime = parent.getCurrentTime(); float x = event.getX(); float y = event.getY(); boolean hadHit = false; if (parent.mode == C2B.ONEPASS_MODE) { // Record this point as a target hadHit = true; snd.play(hitPerfectSfx, 1, 1, 0, 0, 1); Target targ = new Target(currentTime, (int) x, (int) y, ""); recordedTargets.add(targ); } else if (parent.mode == C2B.TWOPASS_MODE) { hadHit = true; parent.beatTimes.add(currentTime); } else { // Play the game normally for (int i = 0; i < drawnTargets.size(); i++) { if (hitTarget(x, y, drawnTargets.get(i))) { Target t = drawnTargets.get(i); int points; double timeDiff = Math.abs(currentTime - t.time); if (timeDiff < TOLERANCE) { points = POINTS_FOR_PERFECT; snd.play(hitPerfectSfx, 1, 1, 0, 0, 1); lastRating = LAST_RATING_PERFECT; } else { points = (int) (POINTS_FOR_PERFECT - (timeDiff * PENALTY_FACTOR)); points = points + (int) (points * (comboCount * COMBO_FACTOR)); snd.play(hitOkSfx, 1, 1, 0, 0, 1); lastRating = LAST_RATING_OK; } if (points > 0) { score = score + points; hadHit = true; } drawnTargets.remove(i); break; } } } if (hadHit) { comboCount++; } else { if (longestCombo < comboCount) { longestCombo = comboCount; } comboCount = 0; snd.play(missSfx, 1, 1, 0, 0, 1); lastRating = LAST_RATING_MISS; } vibe.vibrate(VIBE_PATTERN, -1); } return true; } private boolean hitTarget(float x, float y, Target t) { if (t == null) { return false; } // Use the pythagorean theorem to solve this. float xSquared = (t.x - x) * (t.x - x); float ySquared = (t.y - y) * (t.y - y); if ((xSquared + ySquared) < (TARGET_RADIUS * TARGET_RADIUS)) { return true; } return false; } @Override public void onDraw(Canvas canvas) { if (parent.mode != C2B.GAME_MODE) { return; } int currentTime = parent.getCurrentTime(); // Draw the circles for (int i = 0; i < drawnTargets.size(); i++) { Target t = drawnTargets.get(i); if (t == null) { break; } // Insides should be semi-transparent canvas.drawCircle(t.x, t.y, TARGET_RADIUS, innerPaint); // Set colors for the target borderPaint.setColor(t.color); haloPaint.setColor(t.color); // Perfect timing == hitting the halo inside the borders canvas.drawCircle(t.x, t.y, TARGET_RADIUS - 5, borderPaint); canvas.drawCircle(t.x, t.y, TARGET_RADIUS, borderPaint); // Draw timing halos - may need to change the formula here float percentageOff = ((float) (t.time - currentTime)) / PRE_THRESHOLD; int haloSize = (int) (TARGET_RADIUS + (percentageOff * TARGET_RADIUS)); canvas.drawCircle(t.x, t.y, haloSize, haloPaint); } // Score and Combo info String scoreText = "Score: " + Integer.toString(score); int x = getWidth() - 100; // Fudge factor for making it on the top right // corner int y = 30; Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.RED); paint.setTextAlign(Paint.Align.CENTER); paint.setTextSize(24); paint.setTypeface(Typeface.DEFAULT_BOLD); y -= paint.ascent() / 2; canvas.drawText(scoreText, x, y, paint); x = getWidth() / 2; canvas.drawText(lastRating, x, y, paint); String comboText = "Combo: " + Integer.toString(comboCount); x = 60; canvas.drawText(comboText, x, y, paint); } private class Monitor implements Runnable { public void run() { while (true) { try { Thread.sleep(INTERVAL); } catch (InterruptedException e) { // This should not be interrupted. If it is, just dump the stack // trace. e.printStackTrace(); } updateTargets(); postInvalidate(); } } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.zip.ZipFile; public class Unzipper { public static String download(String fileUrl) { URLConnection cn; try { fileUrl = (new URL(new URL(fileUrl), fileUrl)).toString(); URL url = new URL(fileUrl); cn = url.openConnection(); cn.connect(); InputStream stream = cn.getInputStream(); File outputDir = new File("/sdcard/c2b/"); outputDir.mkdirs(); String filename = fileUrl.substring(fileUrl.lastIndexOf("/") + 1); filename = filename.substring(0, filename.indexOf("c2b.zip") + 7); File outputFile = new File("/sdcard/c2b/", filename); outputFile.createNewFile(); FileOutputStream out = new FileOutputStream(outputFile); byte buf[] = new byte[16384]; do { int numread = stream.read(buf); if (numread <= 0) { break; } else { out.write(buf, 0, numread); } } while (true); stream.close(); out.close(); return "/sdcard/c2b/" + filename; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); return ""; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return ""; } } public static void unzip(String fileUrl) { try { String filename = download(fileUrl); ZipFile zip = new ZipFile(filename); Enumeration<? extends ZipEntry> zippedFiles = zip.entries(); while (zippedFiles.hasMoreElements()) { ZipEntry entry = zippedFiles.nextElement(); InputStream is = zip.getInputStream(entry); String name = entry.getName(); File outputFile = new File("/sdcard/c2b/" + name); String outputPath = outputFile.getCanonicalPath(); name = outputPath.substring(outputPath.lastIndexOf("/") + 1); outputPath = outputPath.substring(0, outputPath.lastIndexOf("/")); File outputDir = new File(outputPath); outputDir.mkdirs(); outputFile = new File(outputPath, name); outputFile.createNewFile(); FileOutputStream out = new FileOutputStream(outputFile); byte buf[] = new byte[16384]; do { int numread = is.read(buf); if (numread <= 0) { break; } else { out.write(buf, 0, numread); } } while (true); is.close(); out.close(); } File theZipFile = new File(filename); theZipFile.delete(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Java
/* * Copyright (C) 2007 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.android.globaltime; import javax.microedition.khronos.opengles.GL10; public class Sphere extends Shape { public Sphere(boolean emitTextureCoordinates, boolean emitNormals, boolean emitColors) { super(GL10.GL_TRIANGLES, GL10.GL_UNSIGNED_SHORT, emitTextureCoordinates, emitNormals, emitColors); } }
Java
/* * Copyright (C) 2007 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.android.globaltime; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.TimeZone; /** * A class representing a city, with an associated position, time zone name, * and raw offset from UTC. */ public class City implements Comparable<City> { private static Map<String,City> cities = new HashMap<String,City>(); private static City[] citiesByRawOffset; private String name; private String timeZoneID; private TimeZone timeZone = null; private int rawOffset; private float latitude, longitude; private float x, y, z; /** * Loads the city database. The cities must be stored in order by raw * offset from UTC. */ public static void loadCities(InputStream is) throws IOException { DataInputStream dis = new DataInputStream(is); int numCities = dis.readInt(); citiesByRawOffset = new City[numCities]; byte[] buf = new byte[24]; for (int i = 0; i < numCities; i++) { String name = dis.readUTF(); String tzid = dis.readUTF(); dis.read(buf); // The code below is a faster version of: // int rawOffset = dis.readInt(); // float latitude = dis.readFloat(); // float longitude = dis.readFloat(); // float cx = dis.readFloat(); // float cy = dis.readFloat(); // float cz = dis.readFloat(); int rawOffset = (buf[ 0] << 24) | ((buf[ 1] & 0xff) << 16) | ((buf[ 2] & 0xff) << 8) | (buf[ 3] & 0xff); int ilat = (buf[ 4] << 24) | ((buf[ 5] & 0xff) << 16) | ((buf[ 6] & 0xff) << 8) | (buf[ 7] & 0xff); int ilon = (buf[ 8] << 24) | ((buf[ 9] & 0xff) << 16) | ((buf[10] & 0xff) << 8) | (buf[11] & 0xff); int icx = (buf[12] << 24) | ((buf[13] & 0xff) << 16) | ((buf[14] & 0xff) << 8) | (buf[15] & 0xff); int icy = (buf[16] << 24) | ((buf[17] & 0xff) << 16) | ((buf[18] & 0xff) << 8) | (buf[19] & 0xff); int icz = (buf[20] << 24) | ((buf[21] & 0xff) << 16) | ((buf[22] & 0xff) << 8) | (buf[23] & 0xff); float latitude = Float.intBitsToFloat(ilat); float longitude = Float.intBitsToFloat(ilon); float cx = Float.intBitsToFloat(icx); float cy = Float.intBitsToFloat(icy); float cz = Float.intBitsToFloat(icz); City city = new City(name, tzid, rawOffset, latitude, longitude, cx, cy, cz); cities.put(name, city); citiesByRawOffset[i] = city; } } /** * Returns the cities, ordered by name. */ public static City[] getCitiesByName() { City[] ocities = cities.values().toArray(new City[0]); Arrays.sort(ocities); return ocities; } /** * Returns the cities, ordered by offset, accounting for summer/daylight * savings time. This requires reading the entire time zone database * behind the scenes. */ public static City[] getCitiesByOffset() { City[] ocities = cities.values().toArray(new City[0]); Arrays.sort(ocities, new Comparator<City>() { public int compare(City c1, City c2) { long now = System.currentTimeMillis(); TimeZone tz1 = c1.getTimeZone(); TimeZone tz2 = c2.getTimeZone(); int off1 = tz1.getOffset(now); int off2 = tz2.getOffset(now); if (off1 == off2) { float dlat = c2.getLatitude() - c1.getLatitude(); if (dlat < 0.0f) return -1; if (dlat > 0.0f) return 1; return 0; } return off1 - off2; } }); return ocities; } /** * Returns the cities, ordered by offset, accounting for summer/daylight * savings time. This does not require reading the time zone database * since the cities are pre-sorted. */ public static City[] getCitiesByRawOffset() { return citiesByRawOffset; } /** * Returns an Iterator over all cities, in raw offset order. */ public static Iterator<City> iterator() { return cities.values().iterator(); } /** * Returns the total number of cities. */ public static int numCities() { return cities.size(); } /** * Constructs a city with the given name, time zone name, raw offset, * latitude, longitude, and 3D (X, Y, Z) coordinate. */ public City(String name, String timeZoneID, int rawOffset, float latitude, float longitude, float x, float y, float z) { this.name = name; this.timeZoneID = timeZoneID; this.rawOffset = rawOffset; this.latitude = latitude; this.longitude = longitude; this.x = x; this.y = y; this.z = z; } public String getName() { return name; } public TimeZone getTimeZone() { if (timeZone == null) { timeZone = TimeZone.getTimeZone(timeZoneID); } return timeZone; } public float getLongitude() { return longitude; } public float getLatitude() { return latitude; } public float getX() { return x; } public float getY() { return y; } public float getZ() { return z; } public float getRawOffset() { return rawOffset / 3600000.0f; } public int getRawOffsetMillis() { return rawOffset; } /** * Returns this city's offset from UTC, taking summer/daylight savigns * time into account. */ public float getOffset() { long now = System.currentTimeMillis(); if (timeZone == null) { timeZone = TimeZone.getTimeZone(timeZoneID); } return timeZone.getOffset(now) / 3600000.0f; } /** * Compares this city to another by name. */ public int compareTo(City o) { return name.compareTo(o.name); } }
Java
/* * Copyright (C) 2007 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.android.globaltime; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import java.text.DateFormat; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.text.format.DateUtils; //import android.text.format.DateFormat; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.Interpolator; /** * A class that draws an analog clock face with information about the current * time in a given city. */ public class Clock { static final int MILLISECONDS_PER_MINUTE = 60 * 1000; static final int MILLISECONDS_PER_HOUR = 60 * 60 * 1000; private City mCity = null; private long mCitySwitchTime; private long mTime; private float mColorRed = 1.0f; private float mColorGreen = 1.0f; private float mColorBlue = 1.0f; private long mOldOffset; private Interpolator mClockHandInterpolator = new AccelerateDecelerateInterpolator(); public Clock() { // Empty constructor } /** * Adds a line to the given Path. The line extends from * radius r0 to radius r1 about the center point (cx, cy), * at an angle given by pos. * * @param path the Path to draw to * @param radius the radius of the outer rim of the clock * @param pos the angle, with 0 and 1 at 12:00 * @param cx the X coordinate of the clock center * @param cy the Y coordinate of the clock center * @param r0 the starting radius for the line * @param r1 the ending radius for the line */ private static void drawLine(Path path, float radius, float pos, float cx, float cy, float r0, float r1) { float theta = pos * Shape.TWO_PI - Shape.PI_OVER_TWO; float dx = (float) Math.cos(theta); float dy = (float) Math.sin(theta); float p0x = cx + dx * r0; float p0y = cy + dy * r0; float p1x = cx + dx * r1; float p1y = cy + dy * r1; float ox = (p1y - p0y); float oy = -(p1x - p0x); float norm = (radius / 2.0f) / (float) Math.sqrt(ox * ox + oy * oy); ox *= norm; oy *= norm; path.moveTo(p0x - ox, p0y - oy); path.lineTo(p1x - ox, p1y - oy); path.lineTo(p1x + ox, p1y + oy); path.lineTo(p0x + ox, p0y + oy); path.close(); } /** * Adds a vertical arrow to the given Path. * * @param path the Path to draw to */ private static void drawVArrow(Path path, float cx, float cy, float width, float height) { path.moveTo(cx - width / 2.0f, cy); path.lineTo(cx, cy + height); path.lineTo(cx + width / 2.0f, cy); path.close(); } /** * Adds a horizontal arrow to the given Path. * * @param path the Path to draw to */ private static void drawHArrow(Path path, float cx, float cy, float width, float height) { path.moveTo(cx, cy - height / 2.0f); path.lineTo(cx + width, cy); path.lineTo(cx, cy + height / 2.0f); path.close(); } /** * Returns an offset in milliseconds to be subtracted from the current time * in order to obtain an smooth interpolation between the previously * displayed time and the current time. */ private long getOffset(float lerp) { long doffset = (long) (mCity.getOffset() * (float) MILLISECONDS_PER_HOUR - mOldOffset); int sign; if (doffset < 0) { doffset = -doffset; sign = -1; } else { sign = 1; } while (doffset > 12L * MILLISECONDS_PER_HOUR) { doffset -= 12L * MILLISECONDS_PER_HOUR; } if (doffset > 6L * MILLISECONDS_PER_HOUR) { doffset = 12L * MILLISECONDS_PER_HOUR - doffset; sign = -sign; } // Interpolate doffset towards 0 doffset = (long)((1.0f - lerp)*doffset); // Keep the same seconds count long dh = doffset / (MILLISECONDS_PER_HOUR); doffset -= dh * MILLISECONDS_PER_HOUR; long dm = doffset / MILLISECONDS_PER_MINUTE; doffset = sign * (60 * dh + dm) * MILLISECONDS_PER_MINUTE; return doffset; } /** * Set the city to be displayed. setCity(null) resets things so the clock * hand animation won't occur next time. */ public void setCity(City city) { if (mCity != city) { if (mCity != null) { mOldOffset = (long) (mCity.getOffset() * (float) MILLISECONDS_PER_HOUR); } else if (city != null) { mOldOffset = (long) (city.getOffset() * (float) MILLISECONDS_PER_HOUR); } else { mOldOffset = 0L; // this will never be used } this.mCitySwitchTime = System.currentTimeMillis(); this.mCity = city; } } public void setTime(long time) { this.mTime = time; } /** * Draws the clock face. * * @param canvas the Canvas to draw to * @param cx the X coordinate of the clock center * @param cy the Y coordinate of the clock center * @param radius the radius of the clock face * @param alpha the translucency of the clock face * @param textAlpha the translucency of the text * @param showCityName if true, display the city name * @param showTime if true, display the time digitally * @param showUpArrow if true, display an up arrow * @param showDownArrow if true, display a down arrow * @param showLeftRightArrows if true, display left and right arrows * @param prefixChars number of characters of the city name to draw in bold */ public void drawClock(Canvas canvas, float cx, float cy, float radius, float alpha, float textAlpha, boolean showCityName, boolean showTime, boolean showUpArrow, boolean showDownArrow, boolean showLeftRightArrows, int prefixChars) { Paint paint = new Paint(); paint.setAntiAlias(true); int iradius = (int)radius; TimeZone tz = mCity.getTimeZone(); // Compute an interpolated time to animate between the previously // displayed time and the current time float lerp = Math.min(1.0f, (System.currentTimeMillis() - mCitySwitchTime) / 500.0f); lerp = mClockHandInterpolator.getInterpolation(lerp); long doffset = lerp < 1.0f ? getOffset(lerp) : 0L; // Determine the interpolated time for the given time zone Calendar cal = Calendar.getInstance(tz); cal.setTimeInMillis(mTime - doffset); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND); int milli = cal.get(Calendar.MILLISECOND); float offset = tz.getRawOffset() / (float) MILLISECONDS_PER_HOUR; float daylightOffset = tz.inDaylightTime(new Date(mTime)) ? tz.getDSTSavings() / (float) MILLISECONDS_PER_HOUR : 0.0f; float absOffset = offset < 0 ? -offset : offset; int offsetH = (int) absOffset; int offsetM = (int) (60.0f * (absOffset - offsetH)); hour %= 12; // Get the city name and digital time strings String cityName = mCity.getName(); cal.setTimeInMillis(mTime); //java.text.DateFormat mTimeFormat = android.text.format.DateFormat.getTimeFormat(this.getApplicationContext()); DateFormat mTimeFormat = DateFormat.getTimeInstance(); String time = mTimeFormat.format(cal.getTimeInMillis()) + " " + DateUtils.getDayOfWeekString(cal.get(Calendar.DAY_OF_WEEK), DateUtils.LENGTH_SHORT) + " " + " (UTC" + (offset >= 0 ? "+" : "-") + offsetH + (offsetM == 0 ? "" : ":" + offsetM) + (daylightOffset == 0 ? "" : "+" + daylightOffset) + ")"; float th = paint.getTextSize(); float tw; // Set the text color paint.setARGB((int) (textAlpha * 255.0f), (int) (mColorRed * 255.0f), (int) (mColorGreen * 255.0f), (int) (mColorBlue * 255.0f)); tw = paint.measureText(cityName); if (showCityName) { // Increment prefixChars to include any spaces for (int i = 0; i < prefixChars; i++) { if (cityName.charAt(i) == ' ') { ++prefixChars; } } // Draw the city name canvas.drawText(cityName, cx - tw / 2, cy - radius - th, paint); // Overstrike the first 'prefixChars' characters canvas.drawText(cityName.substring(0, prefixChars), cx - tw / 2 + 1, cy - radius - th, paint); } tw = paint.measureText(time); if (showTime) { canvas.drawText(time, cx - tw / 2, cy + radius + th + 5, paint); } paint.setARGB((int)(alpha * 255.0f), (int)(mColorRed * 255.0f), (int)(mColorGreen * 255.0f), (int)(mColorBlue * 255.0f)); paint.setStyle(Paint.Style.FILL); canvas.drawOval(new RectF(cx - 2, cy - 2, cx + 2, cy + 2), paint); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(radius * 0.12f); canvas.drawOval(new RectF(cx - iradius, cy - iradius, cx + iradius, cy + iradius), paint); float r0 = radius * 0.1f; float r1 = radius * 0.4f; float r2 = radius * 0.6f; float r3 = radius * 0.65f; float r4 = radius * 0.7f; float r5 = radius * 0.9f; Path path = new Path(); float ss = second + milli / 1000.0f; float mm = minute + ss / 60.0f; float hh = hour + mm / 60.0f; // Tics for the hours for (int i = 0; i < 12; i++) { drawLine(path, radius * 0.12f, i / 12.0f, cx, cy, r4, r5); } // Hour hand drawLine(path, radius * 0.12f, hh / 12.0f, cx, cy, r0, r1); // Minute hand drawLine(path, radius * 0.12f, mm / 60.0f, cx, cy, r0, r2); // Second hand drawLine(path, radius * 0.036f, ss / 60.0f, cx, cy, r0, r3); if (showUpArrow) { drawVArrow(path, cx + radius * 1.13f, cy - radius, radius * 0.15f, -radius * 0.1f); } if (showDownArrow) { drawVArrow(path, cx + radius * 1.13f, cy + radius, radius * 0.15f, radius * 0.1f); } if (showLeftRightArrows) { drawHArrow(path, cx - radius * 1.3f, cy, -radius * 0.1f, radius * 0.15f); drawHArrow(path, cx + radius * 1.3f, cy, radius * 0.1f, radius * 0.15f); } paint.setStyle(Paint.Style.FILL); canvas.drawPath(path, paint); } }
Java
/* * Copyright (C) 2007 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.android.globaltime; import javax.microedition.khronos.opengles.GL10; /** * A class representing a set of GL_POINT objects. GlobalTime uses this class * to draw city lights on the night side of the earth. */ public class PointCloud extends Shape { /** * Constructs a PointCloud with a point at each of the given vertex * (x, y, z) positions. * @param vertices an array of (x, y, z) positions given in fixed-point. */ public PointCloud(int[] vertices) { this(vertices, 0, vertices.length); } /** * Constructs a PointCloud with a point at each of the given vertex * (x, y, z) positions. * @param vertices an array of (x, y, z) positions given in fixed-point. * @param off the starting offset of the vertices array * @param len the number of elements of the vertices array to use */ public PointCloud(int[] vertices, int off, int len) { super(GL10.GL_POINTS, GL10.GL_UNSIGNED_SHORT, false, false, false); int numPoints = len / 3; short[] indices = new short[numPoints]; for (int i = 0; i < numPoints; i++) { indices[i] = (short)i; } allocateBuffers(vertices, null, null, null, indices); this.mNumIndices = mIndexBuffer.capacity(); } @Override public int getNumTriangles() { return mNumIndices * 2; } }
Java
/* * Copyright (C) 2007 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.android.globaltime; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.IntBuffer; import java.nio.ShortBuffer; import javax.microedition.khronos.opengles.GL10; /** * An abstract superclass for various three-dimensional objects to be drawn * using OpenGL ES. Each subclass is responsible for setting up NIO buffers * containing vertices, texture coordinates, colors, normals, and indices. * The {@link #draw(GL10)} method draws the object to the given OpenGL context. */ public abstract class Shape { public static final int INT_BYTES = 4; public static final int SHORT_BYTES = 2; public static final float DEGREES_TO_RADIANS = (float) Math.PI / 180.0f; public static final float PI = (float) Math.PI; public static final float TWO_PI = (float) (2.0 * Math.PI); public static final float PI_OVER_TWO = (float) (Math.PI / 2.0); protected int mPrimitive; protected int mIndexDatatype; protected boolean mEmitTextureCoordinates; protected boolean mEmitNormals; protected boolean mEmitColors; protected IntBuffer mVertexBuffer; protected IntBuffer mTexcoordBuffer; protected IntBuffer mColorBuffer; protected IntBuffer mNormalBuffer; protected Buffer mIndexBuffer; protected int mNumIndices = -1; /** * Constructs a Shape. * * @param primitive a GL primitive type understood by glDrawElements, * such as GL10.GL_TRIANGLES * @param indexDatatype the GL datatype for the index buffer, such as * GL10.GL_UNSIGNED_SHORT * @param emitTextureCoordinates true to enable use of the texture * coordinate buffer * @param emitNormals true to enable use of the normal buffer * @param emitColors true to enable use of the color buffer */ protected Shape(int primitive, int indexDatatype, boolean emitTextureCoordinates, boolean emitNormals, boolean emitColors) { mPrimitive = primitive; mIndexDatatype = indexDatatype; mEmitTextureCoordinates = emitTextureCoordinates; mEmitNormals = emitNormals; mEmitColors = emitColors; } /** * Converts the given floating-point value to fixed-point. */ public static int toFixed(float x) { return (int) (x * 65536.0); } /** * Converts the given fixed-point value to floating-point. */ public static float toFloat(int x) { return (float) (x / 65536.0); } /** * Computes the cross-product of two vectors p and q and places * the result in out. */ public static void cross(float[] p, float[] q, float[] out) { out[0] = p[1] * q[2] - p[2] * q[1]; out[1] = p[2] * q[0] - p[0] * q[2]; out[2] = p[0] * q[1] - p[1] * q[0]; } /** * Returns the length of a vector, given as three floats. */ public static float length(float vx, float vy, float vz) { return (float) Math.sqrt(vx * vx + vy * vy + vz * vz); } /** * Returns the length of a vector, given as an array of three floats. */ public static float length(float[] v) { return length(v[0], v[1], v[2]); } /** * Normalizes the given vector of three floats to have length == 1.0. * Vectors with length zero are unaffected. */ public static void normalize(float[] v) { float length = length(v); if (length != 0.0f) { float norm = 1.0f / length; v[0] *= norm; v[1] *= norm; v[2] *= norm; } } /** * Returns the number of triangles associated with this shape. */ public int getNumTriangles() { if (mPrimitive == GL10.GL_TRIANGLES) { return mIndexBuffer.capacity() / 3; } else if (mPrimitive == GL10.GL_TRIANGLE_STRIP) { return mIndexBuffer.capacity() - 2; } return 0; } /** * Copies the given data into the instance * variables mVertexBuffer, mTexcoordBuffer, mNormalBuffer, mColorBuffer, * and mIndexBuffer. * * @param vertices an array of fixed-point vertex coordinates * @param texcoords an array of fixed-point texture coordinates * @param normals an array of fixed-point normal vector coordinates * @param colors an array of fixed-point color channel values * @param indices an array of short indices */ public void allocateBuffers(int[] vertices, int[] texcoords, int[] normals, int[] colors, short[] indices) { allocate(vertices, texcoords, normals, colors); ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * SHORT_BYTES); ibb.order(ByteOrder.nativeOrder()); ShortBuffer shortIndexBuffer = ibb.asShortBuffer(); shortIndexBuffer.put(indices); shortIndexBuffer.position(0); this.mIndexBuffer = shortIndexBuffer; } /** * Copies the given data into the instance * variables mVertexBuffer, mTexcoordBuffer, mNormalBuffer, mColorBuffer, * and mIndexBuffer. * * @param vertices an array of fixed-point vertex coordinates * @param texcoords an array of fixed-point texture coordinates * @param normals an array of fixed-point normal vector coordinates * @param colors an array of fixed-point color channel values * @param indices an array of int indices */ public void allocateBuffers(int[] vertices, int[] texcoords, int[] normals, int[] colors, int[] indices) { allocate(vertices, texcoords, normals, colors); ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * INT_BYTES); ibb.order(ByteOrder.nativeOrder()); IntBuffer intIndexBuffer = ibb.asIntBuffer(); intIndexBuffer.put(indices); intIndexBuffer.position(0); this.mIndexBuffer = intIndexBuffer; } /** * Allocate the vertex, texture coordinate, normal, and color buffer. */ private void allocate(int[] vertices, int[] texcoords, int[] normals, int[] colors) { ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * INT_BYTES); vbb.order(ByteOrder.nativeOrder()); mVertexBuffer = vbb.asIntBuffer(); mVertexBuffer.put(vertices); mVertexBuffer.position(0); if ((texcoords != null) && mEmitTextureCoordinates) { ByteBuffer tbb = ByteBuffer.allocateDirect(texcoords.length * INT_BYTES); tbb.order(ByteOrder.nativeOrder()); mTexcoordBuffer = tbb.asIntBuffer(); mTexcoordBuffer.put(texcoords); mTexcoordBuffer.position(0); } if ((normals != null) && mEmitNormals) { ByteBuffer nbb = ByteBuffer.allocateDirect(normals.length * INT_BYTES); nbb.order(ByteOrder.nativeOrder()); mNormalBuffer = nbb.asIntBuffer(); mNormalBuffer.put(normals); mNormalBuffer.position(0); } if ((colors != null) && mEmitColors) { ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * INT_BYTES); cbb.order(ByteOrder.nativeOrder()); mColorBuffer = cbb.asIntBuffer(); mColorBuffer.put(colors); mColorBuffer.position(0); } } /** * Draws the shape to the given OpenGL ES 1.0 context. Texture coordinates, * normals, and colors are emitted according the the preferences set for * this shape. */ public void draw(GL10 gl) { gl.glVertexPointer(3, GL10.GL_FIXED, 0, mVertexBuffer); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); if (mEmitTextureCoordinates) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glTexCoordPointer(2, GL10.GL_FIXED, 0, mTexcoordBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); } else { gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glDisable(GL10.GL_TEXTURE_2D); } if (mEmitNormals) { gl.glEnableClientState(GL10.GL_NORMAL_ARRAY); gl.glNormalPointer(GL10.GL_FIXED, 0, mNormalBuffer); } else { gl.glDisableClientState(GL10.GL_NORMAL_ARRAY); } if (mEmitColors) { gl.glEnableClientState(GL10.GL_COLOR_ARRAY); gl.glColorPointer(4, GL10.GL_FIXED, 0, mColorBuffer); } else { gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } gl.glDrawElements(mPrimitive, mNumIndices > 0 ? mNumIndices : mIndexBuffer.capacity(), mIndexDatatype, mIndexBuffer); } }
Java
/* * Copyright (C) 2007 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.android.globaltime; import javax.microedition.khronos.opengles.GL10; /** * A class that draws a ring with a given center and inner and outer radii. * The inner and outer rings each have a color and the remaining pixels are * colored by interpolation. GlobalTime uses this class to simulate an * "atmosphere" around the earth. */ public class Annulus extends Shape { /** * Constructs an annulus. * * @param centerX the X coordinate of the center point * @param centerY the Y coordinate of the center point * @param Z the fixed Z for the entire ring * @param innerRadius the inner radius * @param outerRadius the outer radius * @param rInner the red channel of the color of the inner ring * @param gInner the green channel of the color of the inner ring * @param bInner the blue channel of the color of the inner ring * @param aInner the alpha channel of the color of the inner ring * @param rOuter the red channel of the color of the outer ring * @param gOuter the green channel of the color of the outer ring * @param bOuter the blue channel of the color of the outer ring * @param aOuter the alpha channel of the color of the outer ring * @param sectors the number of sectors used to approximate curvature */ public Annulus(float centerX, float centerY, float Z, float innerRadius, float outerRadius, float rInner, float gInner, float bInner, float aInner, float rOuter, float gOuter, float bOuter, float aOuter, int sectors) { super(GL10.GL_TRIANGLES, GL10.GL_UNSIGNED_SHORT, false, false, true); int radii = sectors + 1; int[] vertices = new int[2 * 3 * radii]; int[] colors = new int[2 * 4 * radii]; short[] indices = new short[2 * 3 * radii]; int vidx = 0; int cidx = 0; int iidx = 0; for (int i = 0; i < radii; i++) { float theta = (i * TWO_PI) / (radii - 1); float cosTheta = (float) Math.cos(theta); float sinTheta = (float) Math.sin(theta); vertices[vidx++] = toFixed(centerX + innerRadius * cosTheta); vertices[vidx++] = toFixed(centerY + innerRadius * sinTheta); vertices[vidx++] = toFixed(Z); vertices[vidx++] = toFixed(centerX + outerRadius * cosTheta); vertices[vidx++] = toFixed(centerY + outerRadius * sinTheta); vertices[vidx++] = toFixed(Z); colors[cidx++] = toFixed(rInner); colors[cidx++] = toFixed(gInner); colors[cidx++] = toFixed(bInner); colors[cidx++] = toFixed(aInner); colors[cidx++] = toFixed(rOuter); colors[cidx++] = toFixed(gOuter); colors[cidx++] = toFixed(bOuter); colors[cidx++] = toFixed(aOuter); } for (int i = 0; i < sectors; i++) { indices[iidx++] = (short) (2 * i); indices[iidx++] = (short) (2 * i + 1); indices[iidx++] = (short) (2 * i + 2); indices[iidx++] = (short) (2 * i + 1); indices[iidx++] = (short) (2 * i + 3); indices[iidx++] = (short) (2 * i + 2); } allocateBuffers(vertices, null, null, colors, indices); } }
Java
/* * Copyright (C) 2007 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.android.globaltime; import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Locale; import java.util.TimeZone; import javax.microedition.khronos.egl.*; import javax.microedition.khronos.opengles.*; import android.app.Activity; import android.content.Context; import android.content.res.AssetManager; import android.graphics.Canvas; import android.opengl.Object3D; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.MessageQueue; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; /** * The main View of the GlobalTime Activity. */ class GTView extends SurfaceView implements SurfaceHolder.Callback { /** * A TimeZone object used to compute the current UTC time. */ private static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("utc"); /** * The Sun's color is close to that of a 5780K blackbody. */ private static final float[] SUNLIGHT_COLOR = { 1.0f, 0.9375f, 0.91015625f, 1.0f }; /** * The inclination of the earth relative to the plane of the ecliptic * is 23.45 degrees. */ private static final float EARTH_INCLINATION = 23.45f * Shape.PI / 180.0f; /** Seconds in a day */ private static final int SECONDS_PER_DAY = 24 * 60 * 60; /** Flag for the depth test */ private static final boolean PERFORM_DEPTH_TEST= false; /** Use raw time zone offsets, disregarding "summer time." If false, * current offsets will be used, which requires a much longer startup time * in order to sort the city database. */ private static final boolean USE_RAW_OFFSETS = true; /** * The earth's atmosphere. */ private static final Annulus ATMOSPHERE = new Annulus(0.0f, 0.0f, 1.75f, 0.9f, 1.08f, 0.4f, 0.4f, 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 50); /** * The tesselation of the earth by latitude. */ private static final int SPHERE_LATITUDES = 25; /** * The tesselation of the earth by longitude. */ private static int SPHERE_LONGITUDES = 25; /** * A flattened version of the earth. The normals are computed identically * to those of the round earth, allowing the day/night lighting to be * applied to the flattened surface. */ private static Sphere worldFlat = new LatLongSphere(0.0f, 0.0f, 0.0f, 1.0f, SPHERE_LATITUDES, SPHERE_LONGITUDES, 0.0f, 360.0f, true, true, false, true); /** * The earth. */ private Object3D mWorld; /** * Geometry of the city lights */ private PointCloud mLights; /** * True if the activiy has been initialized. */ boolean mInitialized = false; /** * True if we're in alphabetic entry mode. */ private boolean mAlphaKeySet = false; private EGLContext mEGLContext; private EGLSurface mEGLSurface; private EGLDisplay mEGLDisplay; private EGLConfig mEGLConfig; GLView mGLView; // Rotation and tilt of the Earth private float mRotAngle = 0.0f; private float mTiltAngle = 0.0f; // Rotational velocity of the orbiting viewer private float mRotVelocity = 1.0f; // Rotation of the flat view private float mWrapX = 0.0f; private float mWrapVelocity = 0.0f; private float mWrapVelocityFactor = 0.01f; // Toggle switches private boolean mDisplayAtmosphere = true; private boolean mDisplayClock = false; private boolean mClockShowing = false; private boolean mDisplayLights = false; private boolean mDisplayWorld = true; private boolean mDisplayWorldFlat = false; private boolean mSmoothShading = true; // City search string private String mCityName = ""; // List of all cities private List<City> mClockCities; // List of cities matching a user-supplied prefix private List<City> mCityNameMatches = new ArrayList<City>(); private List<City> mCities; // Start time for clock fade animation private long mClockFadeTime; // Interpolator for clock fade animation private Interpolator mClockSizeInterpolator = new DecelerateInterpolator(1.0f); // Index of current clock private int mCityIndex; // Current clock private Clock mClock; // City-to-city flight animation parameters private boolean mFlyToCity = false; private long mCityFlyStartTime; private float mCityFlightTime; private float mRotAngleStart, mRotAngleDest; private float mTiltAngleStart, mTiltAngleDest; // Interpolator for flight motion animation private Interpolator mFlyToCityInterpolator = new AccelerateDecelerateInterpolator(); private static int sNumLights; private static int[] sLightCoords; // static Map<Float,int[]> cityCoords = new HashMap<Float,int[]>(); // Arrays for GL calls private float[] mClipPlaneEquation = new float[4]; private float[] mLightDir = new float[4]; // Calendar for computing the Sun's position Calendar mSunCal = Calendar.getInstance(UTC_TIME_ZONE); // Triangles drawn per frame private int mNumTriangles; private long startTime; private static final int MOTION_NONE = 0; private static final int MOTION_X = 1; private static final int MOTION_Y = 2; private static final int MIN_MANHATTAN_DISTANCE = 20; private static final float ROTATION_FACTOR = 1.0f / 30.0f; private static final float TILT_FACTOR = 0.35f; // Touchscreen support private float mMotionStartX; private float mMotionStartY; private float mMotionStartRotVelocity; private float mMotionStartTiltAngle; private int mMotionDirection; public void surfaceCreated(SurfaceHolder holder) { EGL10 egl = (EGL10)EGLContext.getEGL(); mEGLSurface = egl.eglCreateWindowSurface(mEGLDisplay, mEGLConfig, this, null); egl.eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext); } public void surfaceDestroyed(SurfaceHolder holder) { // nothing to do } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // nothing to do } /** * Set up the view. * * @param context the Context * @param am an AssetManager to retrieve the city database from */ public GTView(Context context) { super(context); getHolder().addCallback(this); getHolder().setType(SurfaceHolder.SURFACE_TYPE_GPU); AssetManager am = context.getAssets(); startTime = System.currentTimeMillis(); EGL10 egl = (EGL10)EGLContext.getEGL(); EGLDisplay dpy = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); int[] version = new int[2]; egl.eglInitialize(dpy, version); int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 16, EGL10.EGL_NONE }; EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; egl.eglChooseConfig(dpy, configSpec, configs, 1, num_config); mEGLConfig = configs[0]; mEGLContext = egl.eglCreateContext(dpy, mEGLConfig, EGL10.EGL_NO_CONTEXT, null); mEGLDisplay = dpy; mClock = new Clock(); setFocusable(true); setFocusableInTouchMode(true); requestFocus(); try { loadAssets(am); } catch (IOException ioe) { ioe.printStackTrace(); throw new RuntimeException(ioe); } catch (ArrayIndexOutOfBoundsException aioobe) { aioobe.printStackTrace(); throw new RuntimeException(aioobe); } } /** * Destroy the view. */ public void destroy() { EGL10 egl = (EGL10)EGLContext.getEGL(); egl.eglMakeCurrent(mEGLDisplay, egl.EGL_NO_SURFACE, egl.EGL_NO_SURFACE, egl.EGL_NO_CONTEXT); egl.eglDestroyContext(mEGLDisplay, mEGLContext); egl.eglDestroySurface(mEGLDisplay, mEGLSurface); egl.eglTerminate(mEGLDisplay); mEGLContext = null; } /** * Begin animation. */ public void startAnimating() { mHandler.sendEmptyMessage(INVALIDATE); } /** * Quit animation. */ public void stopAnimating() { mHandler.removeMessages(INVALIDATE); } /** * Read a two-byte integer from the input stream. */ private int readInt16(InputStream is) throws IOException { int lo = is.read(); int hi = is.read(); return (hi << 8) | lo; } /** * Returns the offset from UTC for the given city. If USE_RAW_OFFSETS * is true, summer/daylight savings is ignored. */ private static float getOffset(City c) { return USE_RAW_OFFSETS ? c.getRawOffset() : c.getOffset(); } private InputStream cache(InputStream is) throws IOException { int nbytes = is.available(); byte[] data = new byte[nbytes]; int nread = 0; while (nread < nbytes) { nread += is.read(data, nread, nbytes - nread); } return new ByteArrayInputStream(data); } /** * Load the city and lights databases. * * @param am the AssetManager to load from. */ private void loadAssets(final AssetManager am) throws IOException { Locale locale = Locale.getDefault(); String language = locale.getLanguage(); String country = locale.getCountry(); InputStream cis = null; try { // Look for (e.g.) cities_fr_FR.dat or cities_fr_CA.dat cis = am.open("cities_" + language + "_" + country + ".dat"); } catch (FileNotFoundException e1) { try { // Look for (e.g.) cities_fr.dat or cities_fr.dat cis = am.open("cities_" + language + ".dat"); } catch (FileNotFoundException e2) { try { // Use English city names by default cis = am.open("cities_en.dat"); } catch (FileNotFoundException e3) { throw e3; } } } cis = cache(cis); City.loadCities(cis); City[] cities; if (USE_RAW_OFFSETS) { cities = City.getCitiesByRawOffset(); } else { cities = City.getCitiesByOffset(); } mClockCities = new ArrayList<City>(cities.length); for (int i = 0; i < cities.length; i++) { mClockCities.add(cities[i]); } mCities = mClockCities; mCityIndex = 0; this.mWorld = new Object3D() { @Override public InputStream readFile(String filename) throws IOException { return cache(am.open(filename)); } }; mWorld.load("world.gles"); // lights.dat has the following format. All integers // are 16 bits, low byte first. // // width // height // N [# of lights] // light 0 X [in the range 0 to (width - 1)] // light 0 Y ]in the range 0 to (height - 1)] // light 1 X [in the range 0 to (width - 1)] // light 1 Y ]in the range 0 to (height - 1)] // ... // light (N - 1) X [in the range 0 to (width - 1)] // light (N - 1) Y ]in the range 0 to (height - 1)] // // For a larger number of lights, it could make more // sense to store the light positions in a bitmap // and extract them manually InputStream lis = am.open("lights.dat"); lis = cache(lis); int lightWidth = readInt16(lis); int lightHeight = readInt16(lis); sNumLights = readInt16(lis); sLightCoords = new int[3 * sNumLights]; int lidx = 0; float lightRadius = 1.009f; float lightScale = 65536.0f * lightRadius; float[] cosTheta = new float[lightWidth]; float[] sinTheta = new float[lightWidth]; float twoPi = (float) (2.0 * Math.PI); float scaleW = twoPi / lightWidth; for (int i = 0; i < lightWidth; i++) { float theta = twoPi - i * scaleW; cosTheta[i] = (float)Math.cos(theta); sinTheta[i] = (float)Math.sin(theta); } float[] cosPhi = new float[lightHeight]; float[] sinPhi = new float[lightHeight]; float scaleH = (float) (Math.PI / lightHeight); for (int j = 0; j < lightHeight; j++) { float phi = j * scaleH; cosPhi[j] = (float)Math.cos(phi); sinPhi[j] = (float)Math.sin(phi); } int nbytes = 4 * sNumLights; byte[] ilights = new byte[nbytes]; int nread = 0; while (nread < nbytes) { nread += lis.read(ilights, nread, nbytes - nread); } int idx = 0; for (int i = 0; i < sNumLights; i++) { int lx = (((ilights[idx + 1] & 0xff) << 8) | (ilights[idx ] & 0xff)); int ly = (((ilights[idx + 3] & 0xff) << 8) | (ilights[idx + 2] & 0xff)); idx += 4; float sin = sinPhi[ly]; float x = cosTheta[lx]*sin; float y = cosPhi[ly]; float z = sinTheta[lx]*sin; sLightCoords[lidx++] = (int) (x * lightScale); sLightCoords[lidx++] = (int) (y * lightScale); sLightCoords[lidx++] = (int) (z * lightScale); } mLights = new PointCloud(sLightCoords); } /** * Returns true if two time zone offsets are equal. We assume distinct * time zone offsets will differ by at least a few minutes. */ private boolean tzEqual(float o1, float o2) { return Math.abs(o1 - o2) < 0.001; } /** * Move to a different time zone. * * @param incr The increment between the current and future time zones. */ private void shiftTimeZone(int incr) { // If only 1 city in the current set, there's nowhere to go if (mCities.size() <= 1) { return; } float offset = getOffset(mCities.get(mCityIndex)); do { mCityIndex = (mCityIndex + mCities.size() + incr) % mCities.size(); } while (tzEqual(getOffset(mCities.get(mCityIndex)), offset)); offset = getOffset(mCities.get(mCityIndex)); locateCity(true, offset); goToCity(); } /** * Returns true if there is another city within the current time zone * that is the given increment away from the current city. * * @param incr the increment, +1 or -1 * @return */ private boolean atEndOfTimeZone(int incr) { if (mCities.size() <= 1) { return true; } float offset = getOffset(mCities.get(mCityIndex)); int nindex = (mCityIndex + mCities.size() + incr) % mCities.size(); if (tzEqual(getOffset(mCities.get(nindex)), offset)) { return false; } return true; } /** * Shifts cities within the current time zone. * * @param incr the increment, +1 or -1 */ private void shiftWithinTimeZone(int incr) { float offset = getOffset(mCities.get(mCityIndex)); int nindex = (mCityIndex + mCities.size() + incr) % mCities.size(); if (tzEqual(getOffset(mCities.get(nindex)), offset)) { mCityIndex = nindex; goToCity(); } } /** * Returns true if the city name matches the given prefix, ignoring spaces. */ private boolean nameMatches(City city, String prefix) { String cityName = city.getName().replaceAll("[ ]", ""); return prefix.regionMatches(true, 0, cityName, 0, prefix.length()); } /** * Returns true if there are cities matching the given name prefix. */ private boolean hasMatches(String prefix) { for (int i = 0; i < mClockCities.size(); i++) { City city = mClockCities.get(i); if (nameMatches(city, prefix)) { return true; } } return false; } /** * Shifts to the nearest city that matches the new prefix. */ private void shiftByName() { // Attempt to keep current city if it matches City finalCity = null; City currCity = mCities.get(mCityIndex); if (nameMatches(currCity, mCityName)) { finalCity = currCity; } mCityNameMatches.clear(); for (int i = 0; i < mClockCities.size(); i++) { City city = mClockCities.get(i); if (nameMatches(city, mCityName)) { mCityNameMatches.add(city); } } mCities = mCityNameMatches; if (finalCity != null) { for (int i = 0; i < mCityNameMatches.size(); i++) { if (mCityNameMatches.get(i) == finalCity) { mCityIndex = i; break; } } } else { // Find the closest matching city locateCity(false, 0.0f); } goToCity(); } /** * Increases or decreases the rotational speed of the earth. */ private void incrementRotationalVelocity(float incr) { if (mDisplayWorldFlat) { mWrapVelocity -= incr; } else { mRotVelocity -= incr; } } /** * Clears the current matching prefix, while keeping the focus on * the current city. */ private void clearCityMatches() { // Determine the global city index that matches the current city if (mCityNameMatches.size() > 0) { City city = mCityNameMatches.get(mCityIndex); for (int i = 0; i < mClockCities.size(); i++) { City ncity = mClockCities.get(i); if (city.equals(ncity)) { mCityIndex = i; break; } } } mCityName = ""; mCityNameMatches.clear(); mCities = mClockCities; goToCity(); } /** * Fade the clock in or out. */ private void enableClock(boolean enabled) { mClockFadeTime = System.currentTimeMillis(); mDisplayClock = enabled; mClockShowing = true; mAlphaKeySet = enabled; if (enabled) { // Find the closest matching city locateCity(false, 0.0f); } clearCityMatches(); } /** * Use the touchscreen to alter the rotational velocity or the * tilt of the earth. */ @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mMotionStartX = event.getX(); mMotionStartY = event.getY(); mMotionStartRotVelocity = mDisplayWorldFlat ? mWrapVelocity : mRotVelocity; mMotionStartTiltAngle = mTiltAngle; // Stop the rotation if (mDisplayWorldFlat) { mWrapVelocity = 0.0f; } else { mRotVelocity = 0.0f; } mMotionDirection = MOTION_NONE; break; case MotionEvent.ACTION_MOVE: // Disregard motion events when the clock is displayed float dx = event.getX() - mMotionStartX; float dy = event.getY() - mMotionStartY; float delx = Math.abs(dx); float dely = Math.abs(dy); // Determine the direction of motion (major axis) // Once if has been determined, it's locked in until // we receive ACTION_UP or ACTION_CANCEL if ((mMotionDirection == MOTION_NONE) && (delx + dely > MIN_MANHATTAN_DISTANCE)) { if (delx > dely) { mMotionDirection = MOTION_X; } else { mMotionDirection = MOTION_Y; } } // If the clock is displayed, don't actually rotate or tilt; // just use mMotionDirection to record whether motion occurred if (!mDisplayClock) { if (mMotionDirection == MOTION_X) { if (mDisplayWorldFlat) { mWrapVelocity = mMotionStartRotVelocity + dx * ROTATION_FACTOR; } else { mRotVelocity = mMotionStartRotVelocity + dx * ROTATION_FACTOR; } mClock.setCity(null); } else if (mMotionDirection == MOTION_Y && !mDisplayWorldFlat) { mTiltAngle = mMotionStartTiltAngle + dy * TILT_FACTOR; if (mTiltAngle < -90.0f) { mTiltAngle = -90.0f; } if (mTiltAngle > 90.0f) { mTiltAngle = 90.0f; } mClock.setCity(null); } } break; case MotionEvent.ACTION_UP: mMotionDirection = MOTION_NONE; break; case MotionEvent.ACTION_CANCEL: mTiltAngle = mMotionStartTiltAngle; if (mDisplayWorldFlat) { mWrapVelocity = mMotionStartRotVelocity; } else { mRotVelocity = mMotionStartRotVelocity; } mMotionDirection = MOTION_NONE; break; } return true; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (mInitialized && mGLView.processKey(keyCode)) { boolean drawing = (mClockShowing || mGLView.hasMessages()); this.setWillNotDraw(!drawing); return true; } boolean handled = false; // If we're not in alphabetical entry mode, convert letters // to their digit equivalents if (!mAlphaKeySet) { char numChar = event.getNumber(); if (numChar >= '0' && numChar <= '9') { keyCode = KeyEvent.KEYCODE_0 + (numChar - '0'); } } switch (keyCode) { // The 'space' key toggles the clock case KeyEvent.KEYCODE_SPACE: mAlphaKeySet = !mAlphaKeySet; enableClock(mAlphaKeySet); handled = true; break; // The 'left' and 'right' buttons shift time zones if the clock is // displayed, otherwise they alters the rotational speed of the earthh case KeyEvent.KEYCODE_DPAD_LEFT: if (mDisplayClock) { shiftTimeZone(-1); } else { mClock.setCity(null); incrementRotationalVelocity(1.0f); } handled = true; break; case KeyEvent.KEYCODE_DPAD_RIGHT: if (mDisplayClock) { shiftTimeZone(1); } else { mClock.setCity(null); incrementRotationalVelocity(-1.0f); } handled = true; break; // The 'up' and 'down' buttons shift cities within a time zone if the // clock is displayed, otherwise they tilt the earth case KeyEvent.KEYCODE_DPAD_UP: if (mDisplayClock) { shiftWithinTimeZone(-1); } else { mClock.setCity(null); if (!mDisplayWorldFlat) { mTiltAngle += 360.0f / 48.0f; } } handled = true; break; case KeyEvent.KEYCODE_DPAD_DOWN: if (mDisplayClock) { shiftWithinTimeZone(1); } else { mClock.setCity(null); if (!mDisplayWorldFlat) { mTiltAngle -= 360.0f / 48.0f; } } handled = true; break; // The center key stops the earth's rotation, then toggles between the // round and flat views of the earth case KeyEvent.KEYCODE_DPAD_CENTER: if ((!mDisplayWorldFlat && mRotVelocity == 0.0f) || (mDisplayWorldFlat && mWrapVelocity == 0.0f)) { mDisplayWorldFlat = !mDisplayWorldFlat; } else { if (mDisplayWorldFlat) { mWrapVelocity = 0.0f; } else { mRotVelocity = 0.0f; } } handled = true; break; // The 'L' key toggles the city lights case KeyEvent.KEYCODE_L: if (!mAlphaKeySet && !mDisplayWorldFlat) { mDisplayLights = !mDisplayLights; handled = true; } break; // The 'W' key toggles the earth (just for fun) case KeyEvent.KEYCODE_W: if (!mAlphaKeySet && !mDisplayWorldFlat) { mDisplayWorld = !mDisplayWorld; handled = true; } break; // The 'A' key toggles the atmosphere case KeyEvent.KEYCODE_A: if (!mAlphaKeySet && !mDisplayWorldFlat) { mDisplayAtmosphere = !mDisplayAtmosphere; handled = true; } break; // The '2' key zooms out case KeyEvent.KEYCODE_2: if (!mAlphaKeySet && !mDisplayWorldFlat) { mGLView.zoom(-2); handled = true; } break; // The '8' key zooms in case KeyEvent.KEYCODE_8: if (!mAlphaKeySet && !mDisplayWorldFlat) { mGLView.zoom(2); handled = true; } break; } // Handle letters in city names if (!handled && mAlphaKeySet) { switch (keyCode) { // Add a letter to the city name prefix case KeyEvent.KEYCODE_A: case KeyEvent.KEYCODE_B: case KeyEvent.KEYCODE_C: case KeyEvent.KEYCODE_D: case KeyEvent.KEYCODE_E: case KeyEvent.KEYCODE_F: case KeyEvent.KEYCODE_G: case KeyEvent.KEYCODE_H: case KeyEvent.KEYCODE_I: case KeyEvent.KEYCODE_J: case KeyEvent.KEYCODE_K: case KeyEvent.KEYCODE_L: case KeyEvent.KEYCODE_M: case KeyEvent.KEYCODE_N: case KeyEvent.KEYCODE_O: case KeyEvent.KEYCODE_P: case KeyEvent.KEYCODE_Q: case KeyEvent.KEYCODE_R: case KeyEvent.KEYCODE_S: case KeyEvent.KEYCODE_T: case KeyEvent.KEYCODE_U: case KeyEvent.KEYCODE_V: case KeyEvent.KEYCODE_W: case KeyEvent.KEYCODE_X: case KeyEvent.KEYCODE_Y: case KeyEvent.KEYCODE_Z: char c = (char)(keyCode - KeyEvent.KEYCODE_A + 'A'); if (hasMatches(mCityName + c)) { mCityName += c; shiftByName(); } handled = true; break; // Remove a letter from the city name prefix case KeyEvent.KEYCODE_DEL: if (mCityName.length() > 0) { mCityName = mCityName.substring(0, mCityName.length() - 1); shiftByName(); } else { clearCityMatches(); } handled = true; break; // Clear the city name prefix case KeyEvent.KEYCODE_ENTER: clearCityMatches(); handled = true; break; } } boolean drawing = (mClockShowing || ((mGLView != null) && (mGLView.hasMessages()))); this.setWillNotDraw(!drawing); // Let the system handle other keypresses if (!handled) { return super.onKeyDown(keyCode, event); } return true; } /** * Initialize OpenGL ES drawing. */ private synchronized void init(GL10 gl) { mGLView = new GLView(); mGLView.setNearFrustum(5.0f); mGLView.setFarFrustum(50.0f); mGLView.setLightModelAmbientIntensity(0.225f); mGLView.setAmbientIntensity(0.0f); mGLView.setDiffuseIntensity(1.5f); mGLView.setDiffuseColor(SUNLIGHT_COLOR); mGLView.setSpecularIntensity(0.0f); mGLView.setSpecularColor(SUNLIGHT_COLOR); if (PERFORM_DEPTH_TEST) { gl.glEnable(GL10.GL_DEPTH_TEST); } gl.glDisable(GL10.GL_SCISSOR_TEST); gl.glClearColor(0, 0, 0, 1); gl.glHint(GL10.GL_POINT_SMOOTH_HINT, GL10.GL_NICEST); mInitialized = true; } /** * Computes the vector from the center of the earth to the sun for a * particular moment in time. */ private void computeSunDirection() { mSunCal.setTimeInMillis(System.currentTimeMillis()); int day = mSunCal.get(Calendar.DAY_OF_YEAR); int seconds = 3600 * mSunCal.get(Calendar.HOUR_OF_DAY) + 60 * mSunCal.get(Calendar.MINUTE) + mSunCal.get(Calendar.SECOND); day += (float) seconds / SECONDS_PER_DAY; // Approximate declination of the sun, changes sinusoidally // during the year. The winter solstice occurs 10 days before // the start of the year. float decl = (float) (EARTH_INCLINATION * Math.cos(Shape.TWO_PI * (day + 10) / 365.0)); // Subsolar latitude, convert from (-PI/2, PI/2) -> (0, PI) form float phi = decl + Shape.PI_OVER_TWO; // Subsolar longitude float theta = Shape.TWO_PI * seconds / SECONDS_PER_DAY; float sinPhi = (float) Math.sin(phi); float cosPhi = (float) Math.cos(phi); float sinTheta = (float) Math.sin(theta); float cosTheta = (float) Math.cos(theta); // Convert from polar to rectangular coordinates float x = cosTheta * sinPhi; float y = cosPhi; float z = sinTheta * sinPhi; // Directional light -> w == 0 mLightDir[0] = x; mLightDir[1] = y; mLightDir[2] = z; mLightDir[3] = 0.0f; } /** * Computes the approximate spherical distance between two * (latitude, longitude) coordinates. */ private float distance(float lat1, float lon1, float lat2, float lon2) { lat1 *= Shape.DEGREES_TO_RADIANS; lat2 *= Shape.DEGREES_TO_RADIANS; lon1 *= Shape.DEGREES_TO_RADIANS; lon2 *= Shape.DEGREES_TO_RADIANS; float r = 6371.0f; // Earth's radius in km float dlat = lat2 - lat1; float dlon = lon2 - lon1; double sinlat2 = Math.sin(dlat / 2.0f); sinlat2 *= sinlat2; double sinlon2 = Math.sin(dlon / 2.0f); sinlon2 *= sinlon2; double a = sinlat2 + Math.cos(lat1) * Math.cos(lat2) * sinlon2; double c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return (float) (r * c); } /** * Locates the closest city to the currently displayed center point, * optionally restricting the search to cities within a given time zone. */ private void locateCity(boolean useOffset, float offset) { float mindist = Float.MAX_VALUE; int minidx = -1; for (int i = 0; i < mCities.size(); i++) { City city = mCities.get(i); if (useOffset && !tzEqual(getOffset(city), offset)) { continue; } float dist = distance(city.getLatitude(), city.getLongitude(), mTiltAngle, mRotAngle - 90.0f); if (dist < mindist) { mindist = dist; minidx = i; } } mCityIndex = minidx; } /** * Animates the earth to be centered at the current city. */ private void goToCity() { City city = mCities.get(mCityIndex); float dist = distance(city.getLatitude(), city.getLongitude(), mTiltAngle, mRotAngle - 90.0f); mFlyToCity = true; mCityFlyStartTime = System.currentTimeMillis(); mCityFlightTime = dist / 5.0f; // 5000 km/sec mRotAngleStart = mRotAngle; mRotAngleDest = city.getLongitude() + 90; if (mRotAngleDest - mRotAngleStart > 180.0f) { mRotAngleDest -= 360.0f; } else if (mRotAngleStart - mRotAngleDest > 180.0f) { mRotAngleDest += 360.0f; } mTiltAngleStart = mTiltAngle; mTiltAngleDest = city.getLatitude(); mRotVelocity = 0.0f; } /** * Returns a linearly interpolated value between two values. */ private float lerp(float a, float b, float lerp) { return a + (b - a)*lerp; } /** * Draws the city lights, using a clip plane to restrict the lights * to the night side of the earth. */ private void drawCityLights(GL10 gl, float brightness) { gl.glEnable(GL10.GL_POINT_SMOOTH); gl.glDisable(GL10.GL_DEPTH_TEST); gl.glDisable(GL10.GL_LIGHTING); gl.glDisable(GL10.GL_DITHER); gl.glShadeModel(GL10.GL_FLAT); gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); gl.glPointSize(1.0f); float ls = lerp(0.8f, 0.3f, brightness); gl.glColor4f(ls * 1.0f, ls * 1.0f, ls * 0.8f, 1.0f); if (mDisplayWorld) { mClipPlaneEquation[0] = -mLightDir[0]; mClipPlaneEquation[1] = -mLightDir[1]; mClipPlaneEquation[2] = -mLightDir[2]; mClipPlaneEquation[3] = 0.0f; // Assume we have glClipPlanef() from OpenGL ES 1.1 ((GL11) gl).glClipPlanef(GL11.GL_CLIP_PLANE0, mClipPlaneEquation, 0); gl.glEnable(GL11.GL_CLIP_PLANE0); } mLights.draw(gl); if (mDisplayWorld) { gl.glDisable(GL11.GL_CLIP_PLANE0); } mNumTriangles += mLights.getNumTriangles()*2; } /** * Draws the atmosphere. */ private void drawAtmosphere(GL10 gl) { gl.glDisable(GL10.GL_LIGHTING); gl.glDisable(GL10.GL_CULL_FACE); gl.glDisable(GL10.GL_DITHER); gl.glDisable(GL10.GL_DEPTH_TEST); gl.glShadeModel(mSmoothShading ? GL10.GL_SMOOTH : GL10.GL_FLAT); // Draw the atmospheric layer float tx = mGLView.getTranslateX(); float ty = mGLView.getTranslateY(); float tz = mGLView.getTranslateZ(); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); gl.glTranslatef(tx, ty, tz); // Blend in the atmosphere a bit gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); ATMOSPHERE.draw(gl); mNumTriangles += ATMOSPHERE.getNumTriangles(); } /** * Draws the world in a 2D map view. */ private void drawWorldFlat(GL10 gl) { gl.glDisable(GL10.GL_BLEND); gl.glEnable(GL10.GL_DITHER); gl.glShadeModel(mSmoothShading ? GL10.GL_SMOOTH : GL10.GL_FLAT); gl.glTranslatef(mWrapX - 2, 0.0f, 0.0f); worldFlat.draw(gl); gl.glTranslatef(2.0f, 0.0f, 0.0f); worldFlat.draw(gl); mNumTriangles += worldFlat.getNumTriangles() * 2; mWrapX += mWrapVelocity * mWrapVelocityFactor; while (mWrapX < 0.0f) { mWrapX += 2.0f; } while (mWrapX > 2.0f) { mWrapX -= 2.0f; } } /** * Draws the world in a 2D round view. */ private void drawWorldRound(GL10 gl) { gl.glDisable(GL10.GL_BLEND); gl.glEnable(GL10.GL_DITHER); gl.glShadeModel(mSmoothShading ? GL10.GL_SMOOTH : GL10.GL_FLAT); mWorld.draw(gl); mNumTriangles += mWorld.getNumTriangles(); } /** * Draws the clock. * * @param canvas the Canvas to draw to * @param now the current time * @param w the width of the screen * @param h the height of the screen * @param lerp controls the animation, between 0.0 and 1.0 */ private void drawClock(Canvas canvas, long now, int w, int h, float lerp) { float clockAlpha = lerp(0.0f, 0.8f, lerp); mClockShowing = clockAlpha > 0.0f; if (clockAlpha > 0.0f) { City city = mCities.get(mCityIndex); mClock.setCity(city); mClock.setTime(now); float cx = w / 2.0f; float cy = h / 2.0f; float smallRadius = 18.0f; float bigRadius = 0.75f * 0.5f * Math.min(w, h); float radius = lerp(smallRadius, bigRadius, lerp); // Only display left/right arrows if we are in a name search boolean scrollingByName = (mCityName.length() > 0) && (mCities.size() > 1); mClock.drawClock(canvas, cx, cy, radius, clockAlpha, 1.0f, lerp == 1.0f, lerp == 1.0f, !atEndOfTimeZone(-1), !atEndOfTimeZone(1), scrollingByName, mCityName.length()); } } /** * Draws the 2D layer. */ @Override protected void onDraw(Canvas canvas) { long now = System.currentTimeMillis(); if (startTime != -1) { startTime = -1; } int w = getWidth(); int h = getHeight(); // Interpolator for clock size, clock alpha, night lights intensity float lerp = Math.min((now - mClockFadeTime)/1000.0f, 1.0f); if (!mDisplayClock) { // Clock is receding lerp = 1.0f - lerp; } lerp = mClockSizeInterpolator.getInterpolation(lerp); // we don't need to make sure OpenGL rendering is done because // we're drawing in to a different surface drawClock(canvas, now, w, h, lerp); mGLView.showMessages(canvas); mGLView.showStatistics(canvas, w); } /** * Draws the 3D layer. */ protected void drawOpenGLScene() { long now = System.currentTimeMillis(); mNumTriangles = 0; EGL10 egl = (EGL10)EGLContext.getEGL(); GL10 gl = (GL10)mEGLContext.getGL(); if (!mInitialized) { init(gl); } int w = getWidth(); int h = getHeight(); gl.glViewport(0, 0, w, h); gl.glEnable(GL10.GL_LIGHTING); gl.glEnable(GL10.GL_LIGHT0); gl.glEnable(GL10.GL_CULL_FACE); gl.glFrontFace(GL10.GL_CCW); float ratio = (float) w / h; mGLView.setAspectRatio(ratio); mGLView.setTextureParameters(gl); if (PERFORM_DEPTH_TEST) { gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); } else { gl.glClear(GL10.GL_COLOR_BUFFER_BIT); } if (mDisplayWorldFlat) { gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glFrustumf(-1.0f, 1.0f, -1.0f / ratio, 1.0f / ratio, 1.0f, 2.0f); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); gl.glTranslatef(0.0f, 0.0f, -1.0f); } else { mGLView.setProjection(gl); mGLView.setView(gl); } if (!mDisplayWorldFlat) { if (mFlyToCity) { float lerp = (now - mCityFlyStartTime)/mCityFlightTime; if (lerp >= 1.0f) { mFlyToCity = false; } lerp = Math.min(lerp, 1.0f); lerp = mFlyToCityInterpolator.getInterpolation(lerp); mRotAngle = lerp(mRotAngleStart, mRotAngleDest, lerp); mTiltAngle = lerp(mTiltAngleStart, mTiltAngleDest, lerp); } // Rotate the viewpoint around the earth gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glRotatef(mTiltAngle, 1, 0, 0); gl.glRotatef(mRotAngle, 0, 1, 0); // Increment the rotation angle mRotAngle += mRotVelocity; if (mRotAngle < 0.0f) { mRotAngle += 360.0f; } if (mRotAngle > 360.0f) { mRotAngle -= 360.0f; } } // Draw the world with lighting gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, mLightDir, 0); mGLView.setLights(gl, GL10.GL_LIGHT0); if (mDisplayWorldFlat) { drawWorldFlat(gl); } else if (mDisplayWorld) { drawWorldRound(gl); } if (mDisplayLights && !mDisplayWorldFlat) { // Interpolator for clock size, clock alpha, night lights intensity float lerp = Math.min((now - mClockFadeTime)/1000.0f, 1.0f); if (!mDisplayClock) { // Clock is receding lerp = 1.0f - lerp; } lerp = mClockSizeInterpolator.getInterpolation(lerp); drawCityLights(gl, lerp); } if (mDisplayAtmosphere && !mDisplayWorldFlat) { drawAtmosphere(gl); } mGLView.setNumTriangles(mNumTriangles); egl.eglSwapBuffers(mEGLDisplay, mEGLSurface); if (egl.eglGetError() == EGL11.EGL_CONTEXT_LOST) { // we lost the gpu, quit immediately Context c = getContext(); if (c instanceof Activity) { ((Activity)c).finish(); } } } private static final int INVALIDATE = 1; private static final int ONE_MINUTE = 60000; /** * Controls the animation using the message queue. Every time we receive * an INVALIDATE message, we redraw and place another message in the queue. */ private final Handler mHandler = new Handler() { private long mLastSunPositionTime = 0; @Override public void handleMessage(Message msg) { if (msg.what == INVALIDATE) { // Use the message's time, it's good enough and // allows us to avoid a system call. if ((msg.getWhen() - mLastSunPositionTime) >= ONE_MINUTE) { // Recompute the sun's position once per minute // Place the light at the Sun's direction computeSunDirection(); mLastSunPositionTime = msg.getWhen(); } // Draw the GL scene drawOpenGLScene(); // Send an update for the 2D overlay if needed if (mInitialized && (mClockShowing || mGLView.hasMessages())) { invalidate(); } // Just send another message immediately. This works because // drawOpenGLScene() does the timing for us -- it will // block until the last frame has been processed. // The invalidate message we're posting here will be // interleaved properly with motion/key events which // guarantee a prompt reaction to the user input. sendEmptyMessage(INVALIDATE); } } }; } /** * The main activity class for GlobalTime. */ public class GlobalTime extends Activity { GTView gtView = null; private void setGTView() { if (gtView == null) { gtView = new GTView(this); setContentView(gtView); } } @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setGTView(); } @Override protected void onResume() { super.onResume(); setGTView(); Looper.myQueue().addIdleHandler(new Idler()); } @Override protected void onPause() { super.onPause(); gtView.stopAnimating(); } @Override protected void onStop() { super.onStop(); gtView.stopAnimating(); gtView.destroy(); gtView = null; } // Allow the activity to go idle before its animation starts class Idler implements MessageQueue.IdleHandler { public Idler() { super(); } public final boolean queueIdle() { if (gtView != null) { gtView.startAnimating(); } return false; } } }
Java
/* * Copyright (C) 2006-2007 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.android.globaltime; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.HashMap; import javax.microedition.khronos.opengles.GL10; import android.graphics.Canvas; import android.graphics.Paint; import android.view.KeyEvent; class Message { private String mText; private long mExpirationTime; public Message(String text, long expirationTime) { this.mText = text; this.mExpirationTime = expirationTime; } public String getText() { return mText; } public long getExpirationTime() { return mExpirationTime; } } /** * A helper class to simplify writing an Activity that renders using * OpenGL ES. * * <p> A GLView object stores common elements of GL state and allows * them to be modified interactively. This is particularly useful for * determining the proper settings of parameters such as the view * frustum and light intensities during application development. * * <p> A GLView is not an actual View; instead, it is meant to be * called from within a View to perform event processing on behalf of the * actual View. * * <p> By passing key events to the GLView object from the View, * the application can automatically allow certain parameters to * be user-controlled from the keyboard. Key events may be passed as * shown below: * * <pre> * GLView mGlView = new GLView(); * * public boolean onKeyDown(int keyCode, KeyEvent event) { * // Hand the key to the GLView object first * if (mGlView.processKey(keyCode)) { * return; * } * * switch (keyCode) { * case KeyEvent.KEY_CODE_X: * // perform app processing * break; * * default: * super.onKeyDown(keyCode, event); * break; * } * } * </pre> * * <p> During drawing of a frame, the GLView object should be given the * opportunity to manage GL parameters as shown below: * * OpenGLContext mGLContext; // initialization not shown * int mNumTrianglesDrawn = 0; * * protected void onDraw(Canvas canvas) { * int w = getWidth(); * int h = getHeight(); * * float ratio = (float) w / h; * mGLView.setAspectRatio(ratio); * * GL10 gl = (GL10) mGLContext.getGL(); * mGLContext.waitNative(canvas, this); * * // Enable a light for the GLView to manipulate * gl.glEnable(GL10.GL_LIGHTING); * gl.glEnable(GL10.GL_LIGHT0); * * // Allow the GLView to set GL parameters * mGLView.setTextureParameters(gl); * mGLView.setProjection(gl); * mGLView.setView(gl); * mGLView.setLights(gl, GL10.GL_LIGHT0); * * // Draw some stuff (not shown) * mNumTrianglesDrawn += <num triangles just drawn>; * * // Wait for GL drawing to complete * mGLContext.waitGL(); * * // Inform the GLView of what was drawn, and ask it to display statistics * mGLView.setNumTriangles(mNumTrianglesDrawn); * mGLView.showMessages(canvas); * mGLView.showStatistics(canvas, w); * } * </pre> * * <p> At the end of each frame, following the call to * GLContext.waitGL, the showStatistics and showMessages methods * will cause additional information to be displayed. * * <p> To enter the interactive command mode, the 'tab' key must be * pressed twice in succession. A subsequent press of the 'tab' key * exits the interactive command mode. Entering a multi-letter code * sets the parameter to be modified. The 'newline' key erases the * current code, and the 'del' key deletes the last letter of * the code. The parameter value may be modified by pressing the * keypad left or up to decrement the value and right or down to * increment the value. The current value will be displayed as an * overlay above the GL rendered content. * * <p> The supported keyboard commands are as follows: * * <ul> * <li> h - display a list of commands * <li> fn - near frustum * <li> ff - far frustum * <li> tx - translate x * <li> ty - translate y * <li> tz - translate z * <li> z - zoom (frustum size) * <li> la - ambient light (all RGB channels) * <li> lar - ambient light red channel * <li> lag - ambient light green channel * <li> lab - ambient light blue channel * <li> ld - diffuse light (all RGB channels) * <li> ldr - diffuse light red channel * <li> ldg - diffuse light green channel * <li> ldb - diffuse light blue channel * <li> ls - specular light (all RGB channels) * <li> lsr - specular light red channel * <li> lsg - specular light green channel * <li> lsb - specular light blue channel * <li> lma - light model ambient (all RGB channels) * <li> lmar - light model ambient light red channel * <li> lmag - light model ambient green channel * <li> lmab - light model ambient blue channel * <li> tmin - texture min filter * <li> tmag - texture mag filter * <li> tper - texture perspective correction * </ul> * * {@hide} */ public class GLView { private static final int DEFAULT_DURATION_MILLIS = 1000; private static final int STATE_KEY = KeyEvent.KEYCODE_TAB; private static final int HAVE_NONE = 0; private static final int HAVE_ONE = 1; private static final int HAVE_TWO = 2; private static final float MESSAGE_Y_SPACING = 12.0f; private int mState = HAVE_NONE; private static final int NEAR_FRUSTUM = 0; private static final int FAR_FRUSTUM = 1; private static final int TRANSLATE_X = 2; private static final int TRANSLATE_Y = 3; private static final int TRANSLATE_Z = 4; private static final int ZOOM_EXPONENT = 5; private static final int AMBIENT_INTENSITY = 6; private static final int AMBIENT_RED = 7; private static final int AMBIENT_GREEN = 8; private static final int AMBIENT_BLUE = 9; private static final int DIFFUSE_INTENSITY = 10; private static final int DIFFUSE_RED = 11; private static final int DIFFUSE_GREEN = 12; private static final int DIFFUSE_BLUE = 13; private static final int SPECULAR_INTENSITY = 14; private static final int SPECULAR_RED = 15; private static final int SPECULAR_GREEN = 16; private static final int SPECULAR_BLUE = 17; private static final int LIGHT_MODEL_AMBIENT_INTENSITY = 18; private static final int LIGHT_MODEL_AMBIENT_RED = 19; private static final int LIGHT_MODEL_AMBIENT_GREEN = 20; private static final int LIGHT_MODEL_AMBIENT_BLUE = 21; private static final int TEXTURE_MIN_FILTER = 22; private static final int TEXTURE_MAG_FILTER = 23; private static final int TEXTURE_PERSPECTIVE_CORRECTION = 24; private static final String[] commands = { "fn", "ff", "tx", "ty", "tz", "z", "la", "lar", "lag", "lab", "ld", "ldr", "ldg", "ldb", "ls", "lsr", "lsg", "lsb", "lma", "lmar", "lmag", "lmab", "tmin", "tmag", "tper" }; private static final String[] labels = { "Near Frustum", "Far Frustum", "Translate X", "Translate Y", "Translate Z", "Zoom", "Ambient Intensity", "Ambient Red", "Ambient Green", "Ambient Blue", "Diffuse Intensity", "Diffuse Red", "Diffuse Green", "Diffuse Blue", "Specular Intenstity", "Specular Red", "Specular Green", "Specular Blue", "Light Model Ambient Intensity", "Light Model Ambient Red", "Light Model Ambient Green", "Light Model Ambient Blue", "Texture Min Filter", "Texture Mag Filter", "Texture Perspective Correction", }; private static final float[] defaults = { 5.0f, 100.0f, 0.0f, 0.0f, -50.0f, 0, 0.125f, 1.0f, 1.0f, 1.0f, 0.125f, 1.0f, 1.0f, 1.0f, 0.125f, 1.0f, 1.0f, 1.0f, 0.125f, 1.0f, 1.0f, 1.0f, GL10.GL_NEAREST, GL10.GL_NEAREST, GL10.GL_FASTEST }; private static final float[] increments = { 0.01f, 0.5f, 0.125f, 0.125f, 0.125f, 1.0f, 0.03125f, 0.1f, 0.1f, 0.1f, 0.03125f, 0.1f, 0.1f, 0.1f, 0.03125f, 0.1f, 0.1f, 0.1f, 0.03125f, 0.1f, 0.1f, 0.1f, 0, 0, 0 }; private float[] params = new float[commands.length]; private static final float mZoomScale = 0.109f; private static final float mZoomBase = 1.01f; private int mParam = -1; private float mIncr = 0; private Paint mPaint = new Paint(); private float mAspectRatio = 1.0f; private float mZoom; // private boolean mPerspectiveCorrection = false; // private int mTextureMinFilter = GL10.GL_NEAREST; // private int mTextureMagFilter = GL10.GL_NEAREST; // Counters for FPS calculation private boolean mDisplayFPS = false; private boolean mDisplayCounts = false; private int mFramesFPS = 10; private long[] mTimes = new long[mFramesFPS]; private int mTimesIdx = 0; private Map<String,Message> mMessages = new HashMap<String,Message>(); /** * Constructs a new GLView. */ public GLView() { mPaint.setColor(0xffffffff); reset(); } /** * Sets the aspect ratio (width/height) of the screen. * * @param aspectRatio the screen width divided by the screen height */ public void setAspectRatio(float aspectRatio) { this.mAspectRatio = aspectRatio; } /** * Sets the overall ambient light intensity. This intensity will * be used to modify the ambient light value for each of the red, * green, and blue channels passed to glLightfv(...GL_AMBIENT...). * The default value is 0.125f. * * @param intensity a floating-point value controlling the overall * ambient light intensity. */ public void setAmbientIntensity(float intensity) { params[AMBIENT_INTENSITY] = intensity; } /** * Sets the light model ambient intensity. This intensity will be * used to modify the ambient light value for each of the red, * green, and blue channels passed to * glLightModelfv(GL_LIGHT_MODEL_AMBIENT...). The default value * is 0.125f. * * @param intensity a floating-point value controlling the overall * light model ambient intensity. */ public void setLightModelAmbientIntensity(float intensity) { params[LIGHT_MODEL_AMBIENT_INTENSITY] = intensity; } /** * Sets the ambient color for the red, green, and blue channels * that will be multiplied by the value of setAmbientIntensity and * passed to glLightfv(...GL_AMBIENT...). The default values are * {1, 1, 1}. * * @param ambient an arry of three floats containing ambient * red, green, and blue intensity values. */ public void setAmbientColor(float[] ambient) { params[AMBIENT_RED] = ambient[0]; params[AMBIENT_GREEN] = ambient[1]; params[AMBIENT_BLUE] = ambient[2]; } /** * Sets the overall diffuse light intensity. This intensity will * be used to modify the diffuse light value for each of the red, * green, and blue channels passed to glLightfv(...GL_DIFFUSE...). * The default value is 0.125f. * * @param intensity a floating-point value controlling the overall * ambient light intensity. */ public void setDiffuseIntensity(float intensity) { params[DIFFUSE_INTENSITY] = intensity; } /** * Sets the diffuse color for the red, green, and blue channels * that will be multiplied by the value of setDiffuseIntensity and * passed to glLightfv(...GL_DIFFUSE...). The default values are * {1, 1, 1}. * * @param diffuse an array of three floats containing diffuse * red, green, and blue intensity values. */ public void setDiffuseColor(float[] diffuse) { params[DIFFUSE_RED] = diffuse[0]; params[DIFFUSE_GREEN] = diffuse[1]; params[DIFFUSE_BLUE] = diffuse[2]; } /** * Sets the overall specular light intensity. This intensity will * be used to modify the diffuse light value for each of the red, * green, and blue channels passed to glLightfv(...GL_SPECULAR...). * The default value is 0.125f. * * @param intensity a floating-point value controlling the overall * ambient light intensity. */ public void setSpecularIntensity(float intensity) { params[SPECULAR_INTENSITY] = intensity; } /** * Sets the specular color for the red, green, and blue channels * that will be multiplied by the value of setSpecularIntensity and * passed to glLightfv(...GL_SPECULAR...). The default values are * {1, 1, 1}. * * @param specular an array of three floats containing specular * red, green, and blue intensity values. */ public void setSpecularColor(float[] specular) { params[SPECULAR_RED] = specular[0]; params[SPECULAR_GREEN] = specular[1]; params[SPECULAR_BLUE] = specular[2]; } /** * Returns the current X translation of the modelview * transformation as passed to glTranslatef. The default value is * 0.0f. * * @return the X modelview translation as a float. */ public float getTranslateX() { return params[TRANSLATE_X]; } /** * Returns the current Y translation of the modelview * transformation as passed to glTranslatef. The default value is * 0.0f. * * @return the Y modelview translation as a float. */ public float getTranslateY() { return params[TRANSLATE_Y]; } /** * Returns the current Z translation of the modelview * transformation as passed to glTranslatef. The default value is * -50.0f. * * @return the Z modelview translation as a float. */ public float getTranslateZ() { return params[TRANSLATE_Z]; } /** * Sets the position of the near frustum clipping plane as passed * to glFrustumf. The default value is 5.0f; * * @param nearFrustum the near frustum clipping plane distance as * a float. */ public void setNearFrustum(float nearFrustum) { params[NEAR_FRUSTUM] = nearFrustum; } /** * Sets the position of the far frustum clipping plane as passed * to glFrustumf. The default value is 100.0f; * * @param farFrustum the far frustum clipping plane distance as a * float. */ public void setFarFrustum(float farFrustum) { params[FAR_FRUSTUM] = farFrustum; } private void computeZoom() { mZoom = mZoomScale*(float)Math.pow(mZoomBase, -params[ZOOM_EXPONENT]); } /** * Resets all parameters to their default values. */ public void reset() { for (int i = 0; i < params.length; i++) { params[i] = defaults[i]; } computeZoom(); } private void removeExpiredMessages() { long now = System.currentTimeMillis(); List<String> toBeRemoved = new ArrayList<String>(); Iterator<String> keyIter = mMessages.keySet().iterator(); while (keyIter.hasNext()) { String key = keyIter.next(); Message msg = mMessages.get(key); if (msg.getExpirationTime() < now) { toBeRemoved.add(key); } } Iterator<String> tbrIter = toBeRemoved.iterator(); while (tbrIter.hasNext()) { String key = tbrIter.next(); mMessages.remove(key); } } /** * Displays the message overlay on the given Canvas. The * GLContext.waitGL method should be called prior to calling this * method. The interactive command display is drawn by this * method. * * @param canvas the Canvas on which messages are to appear. */ public void showMessages(Canvas canvas) { removeExpiredMessages(); float y = 10.0f; List<String> l = new ArrayList<String>(); l.addAll(mMessages.keySet()); Collections.sort(l); Iterator<String> iter = l.iterator(); while (iter.hasNext()) { String key = iter.next(); String text = mMessages.get(key).getText(); canvas.drawText(text, 10.0f, y, mPaint); y += MESSAGE_Y_SPACING; } } private int mTriangles; /** * Sets the number of triangles drawn in the previous frame for * display by the showStatistics method. The number of triangles * is not computed by GLView but must be supplied by the * calling Activity. * * @param triangles an Activity-supplied estimate of the number of * triangles drawn in the previous frame. */ public void setNumTriangles(int triangles) { this.mTriangles = triangles; } /** * Displays statistics on frames and triangles per second. The * GLContext.waitGL method should be called prior to calling this * method. * * @param canvas the Canvas on which statistics are to appear. * @param width the width of the Canvas. */ public void showStatistics(Canvas canvas, int width) { long endTime = mTimes[mTimesIdx] = System.currentTimeMillis(); mTimesIdx = (mTimesIdx + 1) % mFramesFPS; float th = mPaint.getTextSize(); if (mDisplayFPS) { // Use end time from mFramesFPS frames ago long startTime = mTimes[mTimesIdx]; String fps = "" + (1000.0f*mFramesFPS/(endTime - startTime)); // Normalize fps to XX.XX format if (fps.indexOf(".") == 1) { fps = " " + fps; } int len = fps.length(); if (len == 2) { fps += ".00"; } else if (len == 4) { fps += "0"; } else if (len > 5) { fps = fps.substring(0, 5); } canvas.drawText(fps + " fps", width - 60.0f, 10.0f, mPaint); } if (mDisplayCounts) { canvas.drawText(mTriangles + " triangles", width - 100.0f, 10.0f + th + 5, mPaint); } } private void addMessage(String key, String text, int durationMillis) { long expirationTime = System.currentTimeMillis() + durationMillis; mMessages.put(key, new Message(text, expirationTime)); } private void addMessage(String key, String text) { addMessage(key, text, DEFAULT_DURATION_MILLIS); } private void addMessage(String text) { addMessage(text, text, DEFAULT_DURATION_MILLIS); } private void clearMessages() { mMessages.clear(); } String command = ""; private void toggleFilter() { if (params[mParam] == GL10.GL_NEAREST) { params[mParam] = GL10.GL_LINEAR; } else { params[mParam] = GL10.GL_NEAREST; } addMessage(commands[mParam], "Texture " + (mParam == TEXTURE_MIN_FILTER ? "min" : "mag") + " filter = " + (params[mParam] == GL10.GL_NEAREST ? "nearest" : "linear")); } private void togglePerspectiveCorrection() { if (params[mParam] == GL10.GL_NICEST) { params[mParam] = GL10.GL_FASTEST; } else { params[mParam] = GL10.GL_NICEST; } addMessage(commands[mParam], "Texture perspective correction = " + (params[mParam] == GL10.GL_FASTEST ? "fastest" : "nicest")); } private String valueString() { if (mParam == TEXTURE_MIN_FILTER || mParam == TEXTURE_MAG_FILTER) { if (params[mParam] == GL10.GL_NEAREST) { return "nearest"; } if (params[mParam] == GL10.GL_LINEAR) { return "linear"; } } if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) { if (params[mParam] == GL10.GL_FASTEST) { return "fastest"; } if (params[mParam] == GL10.GL_NICEST) { return "nicest"; } } return "" + params[mParam]; } /** * * @return true if the view */ public boolean hasMessages() { return mState == HAVE_TWO || mDisplayFPS || mDisplayCounts; } /** * Process a key stroke. The calling Activity should pass all * keys from its onKeyDown method to this method. If the key is * part of a GLView command, true is returned and the calling * Activity should ignore the key event. Otherwise, false is * returned and the calling Activity may process the key event * normally. * * @param keyCode the key code as passed to Activity.onKeyDown. * * @return true if the key is part of a GLView command sequence, * false otherwise. */ public boolean processKey(int keyCode) { // Pressing the state key twice enters the UI // Pressing it again exits the UI if ((keyCode == STATE_KEY) || (keyCode == KeyEvent.KEYCODE_SLASH) || (keyCode == KeyEvent.KEYCODE_PERIOD)) { mState = (mState + 1) % 3; if (mState == HAVE_NONE) { clearMessages(); } if (mState == HAVE_TWO) { clearMessages(); addMessage("aaaa", "GL", Integer.MAX_VALUE); addMessage("aaab", "", Integer.MAX_VALUE); command = ""; } return true; } else { if (mState == HAVE_ONE) { mState = HAVE_NONE; return false; } } // If we're not in the UI, exit without handling the key if (mState != HAVE_TWO) { return false; } if (keyCode == KeyEvent.KEYCODE_ENTER) { command = ""; } else if (keyCode == KeyEvent.KEYCODE_DEL) { if (command.length() > 0) { command = command.substring(0, command.length() - 1); } } else if (keyCode >= KeyEvent.KEYCODE_A && keyCode <= KeyEvent.KEYCODE_Z) { command += "" + (char)(keyCode - KeyEvent.KEYCODE_A + 'a'); } addMessage("aaaa", "GL " + command, Integer.MAX_VALUE); if (command.equals("h")) { addMessage("aaaa", "GL", Integer.MAX_VALUE); addMessage("h - help"); addMessage("fn/ff - frustum near/far clip Z"); addMessage("la/lar/lag/lab - abmient intensity/r/g/b"); addMessage("ld/ldr/ldg/ldb - diffuse intensity/r/g/b"); addMessage("ls/lsr/lsg/lsb - specular intensity/r/g/b"); addMessage("s - toggle statistics display"); addMessage("tmin/tmag - texture min/mag filter"); addMessage("tpersp - texture perspective correction"); addMessage("tx/ty/tz - view translate x/y/z"); addMessage("z - zoom"); command = ""; return true; } else if (command.equals("s")) { mDisplayCounts = !mDisplayCounts; mDisplayFPS = !mDisplayFPS; command = ""; return true; } mParam = -1; for (int i = 0; i < commands.length; i++) { if (command.equals(commands[i])) { mParam = i; mIncr = increments[i]; } } if (mParam == -1) { return true; } boolean addMessage = true; // Increment or decrement if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { if (mParam == ZOOM_EXPONENT) { params[mParam] += mIncr; computeZoom(); } else if ((mParam == TEXTURE_MIN_FILTER) || (mParam == TEXTURE_MAG_FILTER)) { toggleFilter(); } else if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) { togglePerspectiveCorrection(); } else { params[mParam] += mIncr; } } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { if (mParam == ZOOM_EXPONENT) { params[mParam] -= mIncr; computeZoom(); } else if ((mParam == TEXTURE_MIN_FILTER) || (mParam == TEXTURE_MAG_FILTER)) { toggleFilter(); } else if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) { togglePerspectiveCorrection(); } else { params[mParam] -= mIncr; } } if (addMessage) { addMessage(commands[mParam], labels[mParam] + ": " + valueString()); } return true; } /** * Zoom in by a given number of steps. A negative value of steps * zooms out. Each step zooms in by 1%. * * @param steps the number of steps to zoom by. */ public void zoom(int steps) { params[ZOOM_EXPONENT] += steps; computeZoom(); } /** * Set the projection matrix using glFrustumf. The left and right * clipping planes are set at -+(aspectRatio*zoom), the bottom and * top clipping planes are set at -+zoom, and the near and far * clipping planes are set to the values set by setNearFrustum and * setFarFrustum or interactively. * * <p> GL side effects: * <ul> * <li>overwrites the matrix mode</li> * <li>overwrites the projection matrix</li> * </ul> * * @param gl a GL10 instance whose projection matrix is to be modified. */ public void setProjection(GL10 gl) { gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); if (mAspectRatio >= 1.0f) { gl.glFrustumf(-mAspectRatio*mZoom, mAspectRatio*mZoom, -mZoom, mZoom, params[NEAR_FRUSTUM], params[FAR_FRUSTUM]); } else { gl.glFrustumf(-mZoom, mZoom, -mZoom / mAspectRatio, mZoom / mAspectRatio, params[NEAR_FRUSTUM], params[FAR_FRUSTUM]); } } /** * Set the modelview matrix using glLoadIdentity and glTranslatef. * The translation values are set interactively. * * <p> GL side effects: * <ul> * <li>overwrites the matrix mode</li> * <li>overwrites the modelview matrix</li> * </ul> * * @param gl a GL10 instance whose modelview matrix is to be modified. */ public void setView(GL10 gl) { gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); // Move the viewpoint backwards gl.glTranslatef(params[TRANSLATE_X], params[TRANSLATE_Y], params[TRANSLATE_Z]); } /** * Sets texture parameters. * * <p> GL side effects: * <ul> * <li>sets the GL_PERSPECTIVE_CORRECTION_HINT</li> * <li>sets the GL_TEXTURE_MIN_FILTER texture parameter</li> * <li>sets the GL_TEXTURE_MAX_FILTER texture parameter</li> * </ul> * * @param gl a GL10 instance whose texture parameters are to be modified. */ public void setTextureParameters(GL10 gl) { gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, (int)params[TEXTURE_PERSPECTIVE_CORRECTION]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, params[TEXTURE_MIN_FILTER]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, params[TEXTURE_MAG_FILTER]); } /** * Sets the lighting parameters for the given light. * * <p> GL side effects: * <ul> * <li>sets the GL_LIGHT_MODEL_AMBIENT intensities * <li>sets the GL_AMBIENT intensities for the given light</li> * <li>sets the GL_DIFFUSE intensities for the given light</li> * <li>sets the GL_SPECULAR intensities for the given light</li> * </ul> * * @param gl a GL10 instance whose texture parameters are to be modified. */ public void setLights(GL10 gl, int lightNum) { float[] light = new float[4]; light[3] = 1.0f; float lmi = params[LIGHT_MODEL_AMBIENT_INTENSITY]; light[0] = params[LIGHT_MODEL_AMBIENT_RED]*lmi; light[1] = params[LIGHT_MODEL_AMBIENT_GREEN]*lmi; light[2] = params[LIGHT_MODEL_AMBIENT_BLUE]*lmi; gl.glLightModelfv(GL10.GL_LIGHT_MODEL_AMBIENT, light, 0); float ai = params[AMBIENT_INTENSITY]; light[0] = params[AMBIENT_RED]*ai; light[1] = params[AMBIENT_GREEN]*ai; light[2] = params[AMBIENT_BLUE]*ai; gl.glLightfv(lightNum, GL10.GL_AMBIENT, light, 0); float di = params[DIFFUSE_INTENSITY]; light[0] = params[DIFFUSE_RED]*di; light[1] = params[DIFFUSE_GREEN]*di; light[2] = params[DIFFUSE_BLUE]*di; gl.glLightfv(lightNum, GL10.GL_DIFFUSE, light, 0); float si = params[SPECULAR_INTENSITY]; light[0] = params[SPECULAR_RED]*si; light[1] = params[SPECULAR_GREEN]*si; light[2] = params[SPECULAR_BLUE]*si; gl.glLightfv(lightNum, GL10.GL_SPECULAR, light, 0); } }
Java
/* * Copyright (C) 2007 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.android.globaltime; public class LatLongSphere extends Sphere { public LatLongSphere(float centerX, float centerY, float centerZ, float radius, int lats, int longs, float minLongitude, float maxLongitude, boolean emitTextureCoordinates, boolean emitNormals, boolean emitColors, boolean flatten) { super(emitTextureCoordinates, emitNormals, emitColors); int tris = 2 * (lats - 1) * (longs - 1); int[] vertices = new int[3 * lats * longs]; int[] texcoords = new int[2 * lats * longs]; int[] colors = new int[4 * lats * longs]; int[] normals = new int[3 * lats * longs]; short[] indices = new short[3 * tris]; int vidx = 0; int tidx = 0; int nidx = 0; int cidx = 0; int iidx = 0; minLongitude *= DEGREES_TO_RADIANS; maxLongitude *= DEGREES_TO_RADIANS; for (int i = 0; i < longs; i++) { float fi = (float) i / (longs - 1); // theta is the longitude float theta = (maxLongitude - minLongitude) * (1.0f - fi) + minLongitude; float sinTheta = (float) Math.sin(theta); float cosTheta = (float) Math.cos(theta); for (int j = 0; j < lats; j++) { float fj = (float) j / (lats - 1); // phi is the latitude float phi = PI * fj; float sinPhi = (float) Math.sin(phi); float cosPhi = (float) Math.cos(phi); float x = cosTheta * sinPhi; float y = cosPhi; float z = sinTheta * sinPhi; if (flatten) { // Place vertices onto a flat projection vertices[vidx++] = toFixed(2.0f * fi - 1.0f); vertices[vidx++] = toFixed(0.5f - fj); vertices[vidx++] = toFixed(0.0f); } else { // Place vertices onto the surface of a sphere // with the given center and radius vertices[vidx++] = toFixed(x * radius + centerX); vertices[vidx++] = toFixed(y * radius + centerY); vertices[vidx++] = toFixed(z * radius + centerZ); } if (emitTextureCoordinates) { texcoords[tidx++] = toFixed(1.0f - (theta / (TWO_PI))); texcoords[tidx++] = toFixed(fj); } if (emitNormals) { float norm = 1.0f / Shape.length(x, y, z); normals[nidx++] = toFixed(x * norm); normals[nidx++] = toFixed(y * norm); normals[nidx++] = toFixed(z * norm); } // 0 == black, 65536 == white if (emitColors) { colors[cidx++] = (i % 2) * 65536; colors[cidx++] = 0; colors[cidx++] = (j % 2) * 65536; colors[cidx++] = 65536; } } } for (int i = 0; i < longs - 1; i++) { for (int j = 0; j < lats - 1; j++) { int base = i * lats + j; // Ensure both triangles have the same final vertex // since this vertex carries the color for flat // shading indices[iidx++] = (short) (base); indices[iidx++] = (short) (base + 1); indices[iidx++] = (short) (base + lats + 1); indices[iidx++] = (short) (base + lats); indices[iidx++] = (short) (base); indices[iidx++] = (short) (base + lats + 1); } } allocateBuffers(vertices, texcoords, normals, colors, indices); } }
Java
/* * Copyright (C) 2007 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.android.globaltime; import java.nio.ByteBuffer; public class Texture { private ByteBuffer data; private int width, height; public Texture(ByteBuffer data, int width, int height) { this.data = data; this.width = width; this.height = height; } public ByteBuffer getData() { return data; } public int getWidth() { return width; } public int getHeight() { return height; } }
Java
/* * Copyright (C) 2009 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.ch_linghu.fanfoudroid; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceScreen; import android.util.Log; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.http.HttpClient; import com.ch_linghu.fanfoudroid.ui.module.MyTextView; public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //禁止横屏 if (TwitterApplication.mPref.getBoolean( Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } // TODO: is this a hack? setResult(RESULT_OK); addPreferencesFromResource(R.xml.preferences); } @Override protected void onResume() { super.onResume(); // Set up a listener whenever a key changes getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { return super.onPreferenceTreeClick(preferenceScreen, preference); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if ( key.equalsIgnoreCase(Preferences.NETWORK_TYPE) ) { HttpClient httpClient = TwitterApplication.mApi.getHttpClient(); String type = sharedPreferences.getString(Preferences.NETWORK_TYPE, ""); if (type.equalsIgnoreCase(getString(R.string.pref_network_type_cmwap))) { Log.d("LDS", "Set proxy for cmwap mode."); httpClient.setProxy("10.0.0.172", 80, "http"); } else { Log.d("LDS", "No proxy."); httpClient.removeProxy(); } } else if ( key.equalsIgnoreCase(Preferences.UI_FONT_SIZE)) { MyTextView.setFontSizeChanged(true); } } }
Java
package com.ch_linghu.fanfoudroid.app; import java.util.HashMap; import android.graphics.Bitmap; public class MemoryImageCache implements ImageCache { private HashMap<String, Bitmap> mCache; public MemoryImageCache() { mCache = new HashMap<String, Bitmap>(); } @Override public Bitmap get(String url) { synchronized(this) { Bitmap bitmap = mCache.get(url); if (bitmap == null){ return mDefaultBitmap; }else{ return bitmap; } } } @Override public void put(String url, Bitmap bitmap) { synchronized(this) { mCache.put(url, bitmap); } } public void putAll(MemoryImageCache imageCache) { synchronized(this) { // TODO: is this thread safe? mCache.putAll(imageCache.mCache); } } }
Java
/* * Copyright (C) 2009 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.ch_linghu.fanfoudroid.app; public class Preferences { public static final String USERNAME_KEY = "username"; public static final String PASSWORD_KEY = "password"; public static final String CHECK_UPDATES_KEY = "check_updates"; public static final String CHECK_UPDATE_INTERVAL_KEY = "check_update_interval"; public static final String VIBRATE_KEY = "vibrate"; public static final String TIMELINE_ONLY_KEY = "timeline_only"; public static final String REPLIES_ONLY_KEY = "replies_only"; public static final String DM_ONLY_KEY = "dm_only"; public static String RINGTONE_KEY = "ringtone"; public static final String RINGTONE_DEFAULT_KEY = "content://settings/system/notification_sound"; public static final String LAST_TWEET_REFRESH_KEY = "last_tweet_refresh"; public static final String LAST_DM_REFRESH_KEY = "last_dm_refresh"; public static final String LAST_FOLLOWERS_REFRESH_KEY = "last_followers_refresh"; public static final String TWITTER_ACTIVITY_STATE_KEY = "twitter_activity_state"; public static final String USE_PROFILE_IMAGE = "use_profile_image"; public static final String PHOTO_PREVIEW = "photo_preview"; public static final String FORCE_SHOW_ALL_IMAGE = "force_show_all_image"; public static final String RT_PREFIX_KEY = "rt_prefix"; public static final String RT_INSERT_APPEND = "rt_insert_append"; // 转发时光标放置在开始还是结尾 public static final String NETWORK_TYPE = "network_type"; // DEBUG标记 public static final String DEBUG = "debug"; // 当前用户相关信息 public static final String CURRENT_USER_ID = "current_user_id"; public static final String CURRENT_USER_SCREEN_NAME = "current_user_screenname"; public static final String UI_FONT_SIZE = "ui_font_size"; public static final String USE_ENTER_SEND = "use_enter_send"; public static final String USE_GESTRUE = "use_gestrue"; public static final String USE_SHAKE = "use_shake"; public static final String FORCE_SCREEN_ORIENTATION_PORTRAIT = "force_screen_orientation_portrait"; }
Java
package com.ch_linghu.fanfoudroid.app; import android.text.Spannable; import android.text.method.LinkMovementMethod; import android.text.method.MovementMethod; import android.view.MotionEvent; import android.widget.TextView; public class TestMovementMethod extends LinkMovementMethod { private double mY; private boolean mIsMoving = false; @Override public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { /* int action = event.getAction(); if (action == MotionEvent.ACTION_MOVE) { double deltaY = mY - event.getY(); mY = event.getY(); Log.d("foo", deltaY + ""); if (Math.abs(deltaY) > 1) { mIsMoving = true; } } else if (action == MotionEvent.ACTION_DOWN) { mIsMoving = false; mY = event.getY(); } else if (action == MotionEvent.ACTION_UP) { boolean wasMoving = mIsMoving; mIsMoving = false; if (wasMoving) { return true; } } */ return super.onTouchEvent(widget, buffer, event); } public static MovementMethod getInstance() { if (sInstance == null) sInstance = new TestMovementMethod(); return sInstance; } private static TestMovementMethod sInstance; }
Java
package com.ch_linghu.fanfoudroid.app; import android.app.Activity; import android.content.Intent; import android.widget.Toast; import com.ch_linghu.fanfoudroid.LoginActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.fanfou.RefuseError; import com.ch_linghu.fanfoudroid.http.HttpAuthException; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.HttpRefusedException; import com.ch_linghu.fanfoudroid.http.HttpServerException; public class ExceptionHandler { private Activity mActivity; public ExceptionHandler(Activity activity) { mActivity = activity; } public void handle(HttpException e) { Throwable cause = e.getCause(); if (null == cause) return; // Handle Different Exception if (cause instanceof HttpAuthException) { // 用户名/密码错误 Toast.makeText(mActivity, R.string.error_not_authorized, Toast.LENGTH_LONG).show(); Intent intent = new Intent(mActivity, LoginActivity.class); mActivity.startActivity(intent); // redirect to the login activity } else if (cause instanceof HttpServerException) { // 服务器暂时无法响应 Toast.makeText(mActivity, R.string.error_not_authorized, Toast.LENGTH_LONG).show(); } else if (cause instanceof HttpAuthException) { //FIXME: 集中处理用户名/密码验证错误,返回到登录界面 } else if (cause instanceof HttpRefusedException) { // 服务器拒绝请求,如没有权限查看某用户信息 RefuseError error = ((HttpRefusedException) cause).getError(); switch (error.getErrorCode()) { // TODO: finish it case -1: default: Toast.makeText(mActivity, error.getMessage(), Toast.LENGTH_LONG).show(); break; } } } private void handleCause() { } }
Java
/* * Copyright (C) 2009 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.ch_linghu.fanfoudroid.app; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.PixelFormat; import android.graphics.drawable.Drawable; import android.util.Log; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.Response; /** * Manages retrieval and storage of icon images. Use the put method to download * and store images. Use the get method to retrieve images from the manager. */ public class ImageManager implements ImageCache { private static final String TAG = "ImageManager"; // 饭否目前最大宽度支持596px, 超过则同比缩小 // 最大高度为1192px, 超过从中截取 public static final int DEFAULT_COMPRESS_QUALITY = 90; public static final int IMAGE_MAX_WIDTH = 596; public static final int IMAGE_MAX_HEIGHT = 1192; private Context mContext; // In memory cache. private Map<String, SoftReference<Bitmap>> mCache; // MD5 hasher. private MessageDigest mDigest; public static Bitmap drawableToBitmap(Drawable drawable) { Bitmap bitmap = Bitmap .createBitmap( drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable .getIntrinsicHeight()); drawable.draw(canvas); return bitmap; } public ImageManager(Context context) { mContext = context; mCache = new HashMap<String, SoftReference<Bitmap>>(); try { mDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { // This shouldn't happen. throw new RuntimeException("No MD5 algorithm."); } } public void setContext(Context context) { mContext = context; } private String getHashString(MessageDigest digest) { StringBuilder builder = new StringBuilder(); for (byte b : digest.digest()) { builder.append(Integer.toHexString((b >> 4) & 0xf)); builder.append(Integer.toHexString(b & 0xf)); } return builder.toString(); } // MD5 hases are used to generate filenames based off a URL. private String getMd5(String url) { mDigest.update(url.getBytes()); return getHashString(mDigest); } // Looks to see if an image is in the file system. private Bitmap lookupFile(String url) { String hashedUrl = getMd5(url); FileInputStream fis = null; try { fis = mContext.openFileInput(hashedUrl); return BitmapFactory.decodeStream(fis); } catch (FileNotFoundException e) { // Not there. return null; } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // Ignore. } } } } /** * Downloads a file * @param url * @return * @throws HttpException */ public Bitmap downloadImage(String url) throws HttpException { Log.d(TAG, "Fetching image: " + url); Response res = TwitterApplication.mApi.getHttpClient().get(url); return BitmapFactory.decodeStream(new BufferedInputStream(res.asStream())); } public Bitmap downloadImage2(String url) throws HttpException { Log.d(TAG, "[NEW]Fetching image: " + url); final Response res = TwitterApplication.mApi.getHttpClient().get(url); String file = writeToFile(res.asStream(), getMd5(url)); return BitmapFactory.decodeFile(file); } /** * 下载远程图片 -> 转换为Bitmap -> 写入缓存器. * @param url * @param quality image quality 1~100 * @throws HttpException */ public void put(String url, int quality, boolean forceOverride) throws HttpException { if (!forceOverride && contains(url)) { // Image already exists. return; // TODO: write to file if not present. } Bitmap bitmap = downloadImage(url); if (bitmap != null) { put(url, bitmap, quality); // file cache } else { Log.w(TAG, "Retrieved bitmap is null."); } } /** * 重载 put(String url, int quality) * @param url * @throws HttpException */ public void put(String url) throws HttpException { put(url, DEFAULT_COMPRESS_QUALITY, false); } /** * 将本地File -> 转换为Bitmap -> 写入缓存器. * 如果图片大小超过MAX_WIDTH/MAX_HEIGHT, 则将会对图片缩放. * * @param file * @param quality 图片质量(0~100) * @param forceOverride * @throws IOException */ public void put(File file, int quality, boolean forceOverride) throws IOException { if (!file.exists()) { Log.w(TAG, file.getName() + " is not exists."); return; } if (!forceOverride && contains(file.getPath())) { // Image already exists. Log.d(TAG, file.getName() + " is exists"); return; // TODO: write to file if not present. } Bitmap bitmap = BitmapFactory.decodeFile(file.getPath()); //bitmap = resizeBitmap(bitmap, MAX_WIDTH, MAX_HEIGHT); if (bitmap == null) { Log.w(TAG, "Retrieved bitmap is null."); } else { put(file.getPath(), bitmap, quality); } } /** * 将Bitmap写入缓存器. * @param filePath file path * @param bitmap * @param quality 1~100 */ public void put(String file, Bitmap bitmap, int quality) { synchronized (this) { mCache.put(file, new SoftReference<Bitmap>(bitmap)); } writeFile(file, bitmap, quality); } /** * 重载 put(String file, Bitmap bitmap, int quality) * @param filePath file path * @param bitmap * @param quality 1~100 */ @Override public void put(String file, Bitmap bitmap) { put(file, bitmap, DEFAULT_COMPRESS_QUALITY); } /** * 将Bitmap写入本地缓存文件. * @param file URL/PATH * @param bitmap * @param quality */ private void writeFile(String file, Bitmap bitmap, int quality) { if (bitmap == null) { Log.w(TAG, "Can't write file. Bitmap is null."); return; } BufferedOutputStream bos = null; try { String hashedUrl = getMd5(file); bos = new BufferedOutputStream( mContext.openFileOutput(hashedUrl, Context.MODE_PRIVATE)); bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos); // PNG Log.d(TAG, "Writing file: " + file); } catch (IOException ioe) { Log.e(TAG, ioe.getMessage()); } finally { try { if (bos != null) { bitmap.recycle(); bos.flush(); bos.close(); } //bitmap.recycle(); } catch (IOException e) { Log.e(TAG, "Could not close file."); } } } private String writeToFile(InputStream is, String filename) { Log.d("LDS", "new write to file"); BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(is); out = new BufferedOutputStream( mContext.openFileOutput(filename, Context.MODE_PRIVATE)); byte[] buffer = new byte[1024]; int l; while ((l = in.read(buffer)) != -1) { out.write(buffer, 0, l); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { try { if (in != null) in.close(); if (out != null) { Log.d("LDS", "new write to file to -> " + filename); out.flush(); out.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } } return mContext.getFilesDir() + "/" + filename; } public Bitmap get(File file) { return get(file.getPath()); } /** * 判断缓存着中是否存在该文件对应的bitmap */ public boolean isContains(String file) { return mCache.containsKey(file); } /** * 获得指定file/URL对应的Bitmap,首先找本地文件,如果有直接使用,否则去网上获取 * @param file file URL/file PATH * @param bitmap * @param quality * @throws HttpException */ public Bitmap safeGet(String file) throws HttpException { Bitmap bitmap = lookupFile(file); // first try file. if (bitmap != null) { synchronized (this) { // memory cache mCache.put(file, new SoftReference<Bitmap>(bitmap)); } return bitmap; } else { //get from web String url = file; bitmap = downloadImage2(url); // 注释掉以测试新的写入文件方法 //put(file, bitmap); // file Cache return bitmap; } } /** * 从缓存器中读取文件 * @param file file URL/file PATH * @param bitmap * @param quality */ public Bitmap get(String file) { SoftReference<Bitmap> ref; Bitmap bitmap; // Look in memory first. synchronized (this) { ref = mCache.get(file); } if (ref != null) { bitmap = ref.get(); if (bitmap != null) { return bitmap; } } // Now try file. bitmap = lookupFile(file); if (bitmap != null) { synchronized (this) { mCache.put(file, new SoftReference<Bitmap>(bitmap)); } return bitmap; } //TODO: why? //upload: see profileImageCacheManager line 96 Log.w(TAG, "Image is missing: " + file); // return the default photo return mDefaultBitmap; } public boolean contains(String url) { return get(url) != mDefaultBitmap; } public void clear() { String[] files = mContext.fileList(); for (String file : files) { mContext.deleteFile(file); } synchronized (this) { mCache.clear(); } } public void cleanup(HashSet<String> keepers) { String[] files = mContext.fileList(); HashSet<String> hashedUrls = new HashSet<String>(); for (String imageUrl : keepers) { hashedUrls.add(getMd5(imageUrl)); } for (String file : files) { if (!hashedUrls.contains(file)) { Log.d(TAG, "Deleting unused file: " + file); mContext.deleteFile(file); } } } /** * Compress and resize the Image * * <br /> * 因为不论图片大小和尺寸如何, 饭否都会对图片进行一次有损压缩, 所以本地压缩应该 * 考虑图片将会被二次压缩所造成的图片质量损耗 * * @param targetFile * @param quality, 0~100, recommend 100 * @return * @throws IOException */ public File compressImage(File targetFile, int quality) throws IOException { String filepath = targetFile.getAbsolutePath(); // 1. Calculate scale int scale = 1; BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeFile(filepath, o); if (o.outWidth > IMAGE_MAX_WIDTH || o.outHeight > IMAGE_MAX_HEIGHT) { scale = (int) Math.pow( 2.0, (int) Math.round(Math.log(IMAGE_MAX_WIDTH / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5))); //scale = 2; } Log.d(TAG, scale + " scale"); // 2. File -> Bitmap (Returning a smaller image) o.inJustDecodeBounds = false; o.inSampleSize = scale; Bitmap bitmap = BitmapFactory.decodeFile(filepath, o); // 2.1. Resize Bitmap //bitmap = resizeBitmap(bitmap, IMAGE_MAX_WIDTH, IMAGE_MAX_HEIGHT); // 3. Bitmap -> File writeFile(filepath, bitmap, quality); // 4. Get resized Image File String filePath = getMd5(targetFile.getPath()); File compressedImage = mContext.getFileStreamPath(filePath); return compressedImage; } /** * 保持长宽比缩小Bitmap * * @param bitmap * @param maxWidth * @param maxHeight * @param quality 1~100 * @return */ public Bitmap resizeBitmap(Bitmap bitmap, int maxWidth, int maxHeight) { int originWidth = bitmap.getWidth(); int originHeight = bitmap.getHeight(); // no need to resize if (originWidth < maxWidth && originHeight < maxHeight) { return bitmap; } int newWidth = originWidth; int newHeight = originHeight; // 若图片过宽, 则保持长宽比缩放图片 if (originWidth > maxWidth) { newWidth = maxWidth; double i = originWidth * 1.0 / maxWidth; newHeight = (int) Math.floor(originHeight / i); bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true); } // 若图片过长, 则从中部截取 if (newHeight > maxHeight) { newHeight = maxHeight; int half_diff = (int)((originHeight - maxHeight) / 2.0); bitmap = Bitmap.createBitmap(bitmap, 0, half_diff, newWidth, newHeight); } Log.d(TAG, newWidth + " width"); Log.d(TAG, newHeight + " height"); return bitmap; } }
Java
package com.ch_linghu.fanfoudroid.app; import android.graphics.Bitmap; import android.widget.ImageView; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; public class SimpleImageLoader { public static void display(final ImageView imageView, String url) { imageView.setTag(url); imageView.setImageBitmap(TwitterApplication.mImageLoader .get(url, createImageViewCallback(imageView, url))); } public static ImageLoaderCallback createImageViewCallback(final ImageView imageView, String url) { return new ImageLoaderCallback() { @Override public void refresh(String url, Bitmap bitmap) { if (url.equals(imageView.getTag())) { imageView.setImageBitmap(bitmap); } } }; } }
Java
package com.ch_linghu.fanfoudroid.app; import java.lang.Thread.State; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.http.HttpException; public class LazyImageLoader { private static final String TAG = "ProfileImageCacheManager"; public static final int HANDLER_MESSAGE_ID = 1; public static final String EXTRA_BITMAP = "extra_bitmap"; public static final String EXTRA_IMAGE_URL = "extra_image_url"; private ImageManager mImageManager = new ImageManager( TwitterApplication.mContext); private BlockingQueue<String> mUrlList = new ArrayBlockingQueue<String>(50); private CallbackManager mCallbackManager = new CallbackManager(); private GetImageTask mTask = new GetImageTask(); /** * 取图片, 可能直接从cache中返回, 或下载图片后返回 * * @param url * @param callback * @return */ public Bitmap get(String url, ImageLoaderCallback callback) { Bitmap bitmap = ImageCache.mDefaultBitmap; if (mImageManager.isContains(url)) { bitmap = mImageManager.get(url); } else { // bitmap不存在,启动Task进行下载 mCallbackManager.put(url, callback); startDownloadThread(url); } return bitmap; } private void startDownloadThread(String url) { if (url != null) { addUrlToDownloadQueue(url); } // Start Thread State state = mTask.getState(); if (Thread.State.NEW == state) { mTask.start(); // first start } else if (Thread.State.TERMINATED == state) { mTask = new GetImageTask(); // restart mTask.start(); } } private void addUrlToDownloadQueue(String url) { if (!mUrlList.contains(url)) { try { mUrlList.put(url); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } // Low-level interface to get ImageManager public ImageManager getImageManager() { return mImageManager; } private class GetImageTask extends Thread { private volatile boolean mTaskTerminated = false; private static final int TIMEOUT = 3 * 60; private boolean isPermanent = true; @Override public void run() { try { while (!mTaskTerminated) { String url; if (isPermanent) { url = mUrlList.take(); } else { url = mUrlList.poll(TIMEOUT, TimeUnit.SECONDS); // waiting if (null == url) { break; } // no more, shutdown } // Bitmap bitmap = ImageCache.mDefaultBitmap; final Bitmap bitmap = mImageManager.safeGet(url); // use handler to process callback final Message m = handler.obtainMessage(HANDLER_MESSAGE_ID); Bundle bundle = m.getData(); bundle.putString(EXTRA_IMAGE_URL, url); bundle.putParcelable(EXTRA_BITMAP, bitmap); handler.sendMessage(m); } } catch (HttpException ioe) { Log.e(TAG, "Get Image failed, " + ioe.getMessage()); } catch (InterruptedException e) { Log.w(TAG, e.getMessage()); } finally { Log.v(TAG, "Get image task terminated."); mTaskTerminated = true; } } @SuppressWarnings("unused") public boolean isPermanent() { return isPermanent; } @SuppressWarnings("unused") public void setPermanent(boolean isPermanent) { this.isPermanent = isPermanent; } @SuppressWarnings("unused") public void shutDown() throws InterruptedException { mTaskTerminated = true; } } Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case HANDLER_MESSAGE_ID: final Bundle bundle = msg.getData(); String url = bundle.getString(EXTRA_IMAGE_URL); Bitmap bitmap = (Bitmap) (bundle.get(EXTRA_BITMAP)); // callback mCallbackManager.call(url, bitmap); break; default: // do nothing. } } }; public interface ImageLoaderCallback { void refresh(String url, Bitmap bitmap); } public static class CallbackManager { private static final String TAG = "CallbackManager"; private ConcurrentHashMap<String, List<ImageLoaderCallback>> mCallbackMap; public CallbackManager() { mCallbackMap = new ConcurrentHashMap<String, List<ImageLoaderCallback>>(); } public void put(String url, ImageLoaderCallback callback) { Log.v(TAG, "url=" + url); if (!mCallbackMap.containsKey(url)) { Log.v(TAG, "url does not exist, add list to map"); mCallbackMap.put(url, new ArrayList<ImageLoaderCallback>()); //mCallbackMap.put(url, Collections.synchronizedList(new ArrayList<ImageLoaderCallback>())); } mCallbackMap.get(url).add(callback); Log.v(TAG, "Add callback to list, count(url)=" + mCallbackMap.get(url).size()); } public void call(String url, Bitmap bitmap) { Log.v(TAG, "call url=" + url); List<ImageLoaderCallback> callbackList = mCallbackMap.get(url); if (callbackList == null) { // FIXME: 有时会到达这里,原因我还没想明白 Log.e(TAG, "callbackList=null"); return; } for (ImageLoaderCallback callback : callbackList) { if (callback != null) { callback.refresh(url, bitmap); } } callbackList.clear(); mCallbackMap.remove(url); } } }
Java
package com.ch_linghu.fanfoudroid.app; import android.graphics.Bitmap; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; public interface ImageCache { public static Bitmap mDefaultBitmap = ImageManager.drawableToBitmap(TwitterApplication.mContext.getResources().getDrawable(R.drawable.user_default_photo)); public Bitmap get(String url); public void put(String url, Bitmap bitmap); }
Java
/* * Copyright (C) 2009 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.ch_linghu.fanfoudroid.data; import java.util.Date; import org.json.JSONException; import org.json.JSONObject; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.fanfou.Status; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.util.TextHelper; public class Tweet extends Message implements Parcelable { private static final String TAG = "Tweet"; public com.ch_linghu.fanfoudroid.fanfou.User user; public String source; public String prevId; private int statusType = -1; // @see StatusTable#TYPE_* public void setStatusType(int type) { statusType = type; } public int getStatusType() { return statusType; } public Tweet(){} public static Tweet create(Status status){ Tweet tweet = new Tweet(); tweet.id = status.getId(); //转义符放到getSimpleTweetText里去处理,这里不做处理 tweet.text = status.getText(); tweet.createdAt = status.getCreatedAt(); tweet.favorited = status.isFavorited()?"true":"false"; tweet.truncated = status.isTruncated()?"true":"false"; tweet.inReplyToStatusId = status.getInReplyToStatusId(); tweet.inReplyToUserId = status.getInReplyToUserId(); tweet.inReplyToScreenName = status.getInReplyToScreenName(); tweet.screenName = TextHelper.getSimpleTweetText(status.getUser().getScreenName()); tweet.profileImageUrl = status.getUser().getProfileImageURL().toString(); tweet.userId = status.getUser().getId(); tweet.user = status.getUser(); tweet.thumbnail_pic = status.getThumbnail_pic(); tweet.bmiddle_pic = status.getBmiddle_pic(); tweet.original_pic = status.getOriginal_pic(); tweet.source = TextHelper.getSimpleTweetText(status.getSource()); return tweet; } public static Tweet createFromSearchApi(JSONObject jsonObject) throws JSONException { Tweet tweet = new Tweet(); tweet.id = jsonObject.getString("id") + ""; //转义符放到getSimpleTweetText里去处理,这里不做处理 tweet.text = jsonObject.getString("text"); tweet.createdAt = DateTimeHelper.parseSearchApiDateTime(jsonObject.getString("created_at")); tweet.favorited = jsonObject.getString("favorited"); tweet.truncated = jsonObject.getString("truncated"); tweet.inReplyToStatusId = jsonObject.getString("in_reply_to_status_id"); tweet.inReplyToUserId = jsonObject.getString("in_reply_to_user_id"); tweet.inReplyToScreenName = jsonObject.getString("in_reply_to_screen_name"); tweet.screenName = TextHelper.getSimpleTweetText(jsonObject.getString("from_user")); tweet.profileImageUrl = jsonObject.getString("profile_image_url"); tweet.userId = jsonObject.getString("from_user_id"); tweet.source = TextHelper.getSimpleTweetText(jsonObject.getString("source")); return tweet; } public static String buildMetaText(StringBuilder builder, Date createdAt, String source, String replyTo) { builder.setLength(0); builder.append(DateTimeHelper.getRelativeDate(createdAt)); builder.append(" "); builder.append(TwitterApplication.mContext.getString(R.string.tweet_source_prefix)); builder.append(source); if (!TextUtils.isEmpty(replyTo)) { builder.append(" " + TwitterApplication.mContext.getString(R.string.tweet_reply_to_prefix)); builder.append(replyTo); builder.append(TwitterApplication.mContext.getString(R.string.tweet_reply_to_suffix)); } return builder.toString(); } // For interface Parcelable public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { out.writeString(id); out.writeString(text); out.writeValue(createdAt); //Date out.writeString(screenName); out.writeString(favorited); out.writeString(inReplyToStatusId); out.writeString(inReplyToUserId); out.writeString(inReplyToScreenName); out.writeString(screenName); out.writeString(profileImageUrl); out.writeString(thumbnail_pic); out.writeString(bmiddle_pic); out.writeString(original_pic); out.writeString(userId); out.writeString(source); } public static final Parcelable.Creator<Tweet> CREATOR = new Parcelable.Creator<Tweet>() { public Tweet createFromParcel(Parcel in) { return new Tweet(in); } public Tweet[] newArray(int size) { // return new Tweet[size]; throw new UnsupportedOperationException(); } }; public Tweet(Parcel in) { id = in.readString(); text = in.readString(); createdAt = (Date) in.readValue(Date.class.getClassLoader()); screenName = in.readString(); favorited = in.readString(); inReplyToStatusId = in.readString(); inReplyToUserId = in.readString(); inReplyToScreenName = in.readString(); screenName = in.readString(); profileImageUrl = in.readString(); thumbnail_pic = in.readString(); bmiddle_pic = in.readString(); original_pic = in.readString(); userId = in.readString(); source = in.readString(); } @Override public String toString() { return "Tweet [source=" + source + ", id=" + id + ", screenName=" + screenName + ", text=" + text + ", profileImageUrl=" + profileImageUrl + ", createdAt=" + createdAt + ", userId=" + userId + ", favorited=" + favorited + ", inReplyToStatusId=" + inReplyToStatusId + ", inReplyToUserId=" + inReplyToUserId + ", inReplyToScreenName=" + inReplyToScreenName + "]"; } }
Java
package com.ch_linghu.fanfoudroid.data; import android.database.Cursor; public interface BaseContent { long insert(); int delete(); int update(); Cursor select(); }
Java
package com.ch_linghu.fanfoudroid.data; import com.ch_linghu.fanfoudroid.fanfou.DirectMessage; import com.ch_linghu.fanfoudroid.fanfou.User; import com.ch_linghu.fanfoudroid.util.TextHelper; public class Dm extends Message { @SuppressWarnings("unused") private static final String TAG = "Dm"; public boolean isSent; public static Dm create(DirectMessage directMessage, boolean isSent){ Dm dm = new Dm(); dm.id = directMessage.getId(); dm.text = directMessage.getText(); dm.createdAt = directMessage.getCreatedAt(); dm.isSent = isSent; User user = dm.isSent ? directMessage.getRecipient() : directMessage.getSender(); dm.screenName = TextHelper.getSimpleTweetText(user.getScreenName()); dm.userId = user.getId(); dm.profileImageUrl = user.getProfileImageURL().toString(); return dm; } }
Java
package com.ch_linghu.fanfoudroid.data; import java.util.Date; import android.os.Parcel; import android.os.Parcelable; public class User implements Parcelable { public String id; public String name; public String screenName; public String location; public String description; public String profileImageUrl; public String url; public boolean isProtected; public int followersCount; public String lastStatus; public int friendsCount; public int favoritesCount; public int statusesCount; public Date createdAt; public boolean isFollowing; // public boolean notifications; // public utc_offset public User() {} public static User create(com.ch_linghu.fanfoudroid.fanfou.User u) { User user = new User(); user.id = u.getId(); user.name = u.getName(); user.screenName = u.getScreenName(); user.location = u.getLocation(); user.description = u.getDescription(); user.profileImageUrl = u.getProfileImageURL().toString(); if (u.getURL() != null) { user.url = u.getURL().toString(); } user.isProtected = u.isProtected(); user.followersCount = u.getFollowersCount(); user.lastStatus = u.getStatusText(); user.friendsCount = u.getFriendsCount(); user.favoritesCount = u.getFavouritesCount(); user.statusesCount = u.getStatusesCount(); user.createdAt = u.getCreatedAt(); user.isFollowing = u.isFollowing(); return user; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out, int flags) { boolean[] boolArray = new boolean[] { isProtected, isFollowing }; out.writeString(id); out.writeString(name); out.writeString(screenName); out.writeString(location); out.writeString(description); out.writeString(profileImageUrl); out.writeString(url); out.writeBooleanArray(boolArray); out.writeInt(friendsCount); out.writeInt(followersCount); out.writeInt(statusesCount); } public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() { public User createFromParcel(Parcel in) { return new User(in); } public User[] newArray(int size) { // return new User[size]; throw new UnsupportedOperationException(); } }; public User(Parcel in){ boolean[] boolArray = new boolean[]{isProtected, isFollowing}; id = in.readString(); name = in.readString(); screenName = in.readString(); location = in.readString(); description = in.readString(); profileImageUrl = in.readString(); url = in.readString(); in.readBooleanArray(boolArray); friendsCount = in.readInt(); followersCount = in.readInt(); statusesCount = in.readInt(); isProtected = boolArray[0]; isFollowing = boolArray[1]; } }
Java
package com.ch_linghu.fanfoudroid.data; import java.util.Date; public class Message { public String id; public String screenName; public String text; public String profileImageUrl; public Date createdAt; public String userId; public String favorited; public String truncated; public String inReplyToStatusId; public String inReplyToUserId; public String inReplyToScreenName; public String thumbnail_pic; public String bmiddle_pic; public String original_pic; }
Java
package com.ch_linghu.fanfoudroid; import java.util.ArrayList; import java.util.List; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.hardware.SensorManager; import android.util.Log; import android.widget.RemoteViews; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.service.TwitterService; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.util.TextHelper; public class FanfouWidget extends AppWidgetProvider { public final String TAG = "FanfouWidget"; public final String NEXTACTION = "com.ch_linghu.fanfoudroid.FanfouWidget.NEXT"; public final String PREACTION = "com.ch_linghu.fanfoudroid.FanfouWidget.PREV"; private static List<Tweet> tweets; private SensorManager sensorManager; private static int position = 0; class CacheCallback implements ImageLoaderCallback { private RemoteViews updateViews; CacheCallback(RemoteViews updateViews) { this.updateViews = updateViews; } @Override public void refresh(String url, Bitmap bitmap) { updateViews.setImageViewBitmap(R.id.status_image, bitmap); } } @Override public void onUpdate(Context context, AppWidgetManager appwidgetmanager, int[] appWidgetIds) { Log.d(TAG, "onUpdate"); TwitterService.setWidgetStatus(true); // if (!isRunning(context, WidgetService.class.getName())) { // Intent i = new Intent(context, WidgetService.class); // context.startService(i); // } update(context); } private void update(Context context) { fetchMessages(); position = 0; refreshView(context, NEXTACTION); } private TwitterDatabase getDb() { return TwitterApplication.mDb; } public String getUserId() { return TwitterApplication.getMyselfId(); } private void fetchMessages() { if (tweets == null) { tweets = new ArrayList<Tweet>(); } else { tweets.clear(); } Cursor cursor = getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_HOME); if (cursor != null) { if (cursor.moveToFirst()) { do { Tweet tweet = StatusTable.parseCursor(cursor); tweets.add(tweet); } while (cursor.moveToNext()); } } Log.d(TAG, "Tweets size " + tweets.size()); } private void refreshView(Context context) { ComponentName fanfouWidget = new ComponentName(context, FanfouWidget.class); AppWidgetManager manager = AppWidgetManager.getInstance(context); manager.updateAppWidget(fanfouWidget, buildLogin(context)); } private RemoteViews buildLogin(Context context) { RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_initial_layout); updateViews.setTextViewText(R.id.status_text, TextHelper.getSimpleTweetText("请登录")); updateViews.setTextViewText(R.id.status_screen_name,""); updateViews.setTextViewText(R.id.tweet_source,""); updateViews.setTextViewText(R.id.tweet_created_at, ""); return updateViews; } private void refreshView(Context context, String action) { // 某些情况下,tweets会为null if (tweets == null) { fetchMessages(); } // 防止引发IndexOutOfBoundsException if (tweets.size() != 0) { if (action.equals(NEXTACTION)) { --position; } else if (action.equals(PREACTION)) { ++position; } // Log.d(TAG, "Tweets size =" + tweets.size()); if (position >= tweets.size() || position < 0) { position = 0; } // Log.d(TAG, "position=" + position); ComponentName fanfouWidget = new ComponentName(context, FanfouWidget.class); AppWidgetManager manager = AppWidgetManager.getInstance(context); manager.updateAppWidget(fanfouWidget, buildUpdate(context)); } } public RemoteViews buildUpdate(Context context) { RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_initial_layout); Tweet t = tweets.get(position); Log.d(TAG, "tweet=" + t); updateViews.setTextViewText(R.id.status_screen_name, t.screenName); updateViews.setTextViewText(R.id.status_text, TextHelper.getSimpleTweetText(t.text)); updateViews.setTextViewText(R.id.tweet_source, context.getString(R.string.tweet_source_prefix) + t.source); updateViews.setTextViewText(R.id.tweet_created_at, DateTimeHelper.getRelativeDate(t.createdAt)); updateViews.setImageViewBitmap(R.id.status_image, TwitterApplication.mImageLoader.get( t.profileImageUrl, new CacheCallback(updateViews))); Intent inext = new Intent(context, FanfouWidget.class); inext.setAction(NEXTACTION); PendingIntent pinext = PendingIntent.getBroadcast(context, 0, inext, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.btn_next, pinext); Intent ipre = new Intent(context, FanfouWidget.class); ipre.setAction(PREACTION); PendingIntent pipre = PendingIntent.getBroadcast(context, 0, ipre, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.btn_pre, pipre); Intent write = WriteActivity.createNewTweetIntent(""); PendingIntent piwrite = PendingIntent.getActivity(context, 0, write, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.write_message, piwrite); Intent home = TwitterActivity.createIntent(context); PendingIntent pihome = PendingIntent.getActivity(context, 0, home, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.logo_image, pihome); Intent status = StatusActivity.createIntent(t); PendingIntent pistatus = PendingIntent.getActivity(context, 0, status, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.main_body, pistatus); return updateViews; } @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "OnReceive"); // FIXME: NullPointerException Log.i(TAG, context.getApplicationContext().toString()); if (!TwitterApplication.mApi.isLoggedIn()) { refreshView(context); } else { super.onReceive(context, intent); String action = intent.getAction(); if (NEXTACTION.equals(action) || PREACTION.equals(action)) { refreshView(context, intent.getAction()); } else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { update(context); } } } /** * * @param c * @param serviceName * @return */ @Deprecated public boolean isRunning(Context c, String serviceName) { ActivityManager myAM = (ActivityManager) c .getSystemService(Context.ACTIVITY_SERVICE); ArrayList<RunningServiceInfo> runningServices = (ArrayList<RunningServiceInfo>) myAM .getRunningServices(40); // 获取最多40个当前正在运行的服务,放进ArrList里,以现在手机的处理能力,要是超过40个服务,估计已经卡死,所以不用考虑超过40个该怎么办 int servicesSize = runningServices.size(); for (int i = 0; i < servicesSize; i++)// 循环枚举对比 { if (runningServices.get(i).service.getClassName().toString() .equals(serviceName)) { return true; } } return false; } @Override public void onDeleted(Context context, int[] appWidgetIds) { Log.d(TAG, "onDeleted"); } @Override public void onEnabled(Context context) { Log.d(TAG, "onEnabled"); TwitterService.setWidgetStatus(true); } @Override public void onDisabled(Context context) { Log.d(TAG, "onDisabled"); TwitterService.setWidgetStatus(false); } }
Java
package com.ch_linghu.fanfoudroid; import java.text.ParseException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Dm; import com.ch_linghu.fanfoudroid.db.MessageTable; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.fanfou.DirectMessage; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.BaseActivity; import com.ch_linghu.fanfoudroid.ui.base.Refreshable; import com.ch_linghu.fanfoudroid.ui.module.Feedback; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType; import com.ch_linghu.fanfoudroid.ui.module.NavBar; import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.util.TextHelper; public class DmActivity extends BaseActivity implements Refreshable { private static final String TAG = "DmActivity"; // Views. private ListView mTweetList; private Adapter mAdapter; private Adapter mInboxAdapter; private Adapter mSendboxAdapter; Button inbox; Button sendbox; Button newMsg; private int mDMType; private static final int DM_TYPE_ALL = 0; private static final int DM_TYPE_INBOX = 1; private static final int DM_TYPE_SENDBOX = 2; private TextView mProgressText; private NavBar mNavbar; private Feedback mFeedback; // Tasks. private GenericTask mRetrieveTask; private GenericTask mDeleteTask; private TaskListener mDeleteTaskListener = new TaskAdapter(){ @Override public void onPreExecute(GenericTask task) { updateProgress(getString(R.string.page_status_deleting)); } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { mAdapter.refresh(); } else { // Do nothing. } updateProgress(""); } @Override public String getName() { return "DmDeleteTask"; } }; private TaskListener mRetrieveTaskListener = new TaskAdapter(){ @Override public void onPreExecute(GenericTask task) { updateProgress(getString(R.string.page_status_refreshing)); } @Override public void onProgressUpdate(GenericTask task, Object params) { draw(); } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { SharedPreferences.Editor editor = mPreferences.edit(); editor.putLong(Preferences.LAST_DM_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); draw(); goTop(); } else { // Do nothing. } updateProgress(""); } @Override public String getName() { return "DmRetrieve"; } }; // Refresh data at startup if last refresh was this long ago or greater. private static final long REFRESH_THRESHOLD = 5 * 60 * 1000; private static final String EXTRA_USER = "user"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMS"; public static Intent createIntent() { return createIntent(""); } public static Intent createIntent(String user) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); if (!TextUtils.isEmpty(user)) { intent.putExtra(EXTRA_USER, user); } return intent; } @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)) { setContentView(R.layout.dm); mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this); mNavbar.setHeaderTitle("我的私信"); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); bindFooterButtonEvent(); mTweetList = (ListView) findViewById(R.id.tweet_list); mProgressText = (TextView) findViewById(R.id.progress_text); TwitterDatabase db = getDb(); // Mark all as read. db.markAllDmsRead(); setupAdapter(); // Make sure call bindFooterButtonEvent first boolean shouldRetrieve = false; long lastRefreshTime = mPreferences.getLong( Preferences.LAST_DM_REFRESH_KEY, 0); long nowTime = DateTimeHelper.getNowTime(); long diff = nowTime - lastRefreshTime; Log.d(TAG, "Last refresh was " + diff + " ms ago."); if (diff > REFRESH_THRESHOLD) { shouldRetrieve = true; } else if (isTrue(savedInstanceState, SIS_RUNNING_KEY)) { // Check to see if it was running a send or retrieve task. // It makes no sense to resend the send request (don't want dupes) // so we instead retrieve (refresh) to see if the message has // posted. Log.d(TAG, "Was last running a retrieve or send task. Let's refresh."); shouldRetrieve = true; } if (shouldRetrieve) { doRetrieve(); } // Want to be able to focus on the items with the trackball. // That way, we can navigate up and down by changing item focus. mTweetList.setItemsCanFocus(true); return true; }else{ return false; } } @Override protected void onResume() { super.onResume(); checkIsLogedIn(); } private static final String SIS_RUNNING_KEY = "running"; @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { mRetrieveTask.cancel(true); } if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { mDeleteTask.cancel(true); } super.onDestroy(); } // UI helpers. private void bindFooterButtonEvent() { inbox = (Button) findViewById(R.id.inbox); sendbox = (Button) findViewById(R.id.sendbox); newMsg = (Button) findViewById(R.id.new_message); inbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mDMType != DM_TYPE_INBOX) { mDMType = DM_TYPE_INBOX; inbox.setEnabled(false); sendbox.setEnabled(true); mTweetList.setAdapter(mInboxAdapter); mInboxAdapter.refresh(); } } }); sendbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mDMType != DM_TYPE_SENDBOX) { mDMType = DM_TYPE_SENDBOX; inbox.setEnabled(true); sendbox.setEnabled(false); mTweetList.setAdapter(mSendboxAdapter); mSendboxAdapter.refresh(); } } }); newMsg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(DmActivity.this, WriteDmActivity.class); intent.putExtra("reply_to_id", 0); // TODO: 传入实际的reply_to_id startActivity(intent); } }); } private void setupAdapter() { Cursor cursor = getDb().fetchAllDms(-1); startManagingCursor(cursor); mAdapter = new Adapter(this, cursor); Cursor inboxCursor = getDb().fetchInboxDms(); startManagingCursor(inboxCursor); mInboxAdapter = new Adapter(this, inboxCursor); Cursor sendboxCursor = getDb().fetchSendboxDms(); startManagingCursor(sendboxCursor); mSendboxAdapter = new Adapter(this, sendboxCursor); mTweetList.setAdapter(mInboxAdapter); registerForContextMenu(mTweetList); inbox.setEnabled(false); } private class DmRetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams...params) { List<DirectMessage> dmList; ArrayList<Dm> dms = new ArrayList<Dm>(); TwitterDatabase db = getDb(); //ImageManager imageManager = getImageManager(); String maxId = db.fetchMaxDmId(false); HashSet<String> imageUrls = new HashSet<String>(); try { if (maxId != null) { Paging paging = new Paging(maxId); dmList = getApi().getDirectMessages(paging); } else { dmList = getApi().getDirectMessages(); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } publishProgress(SimpleFeedback.calProgressBySize(40, 20, dmList)); for (DirectMessage directMessage : dmList) { if (isCancelled()) { return TaskResult.CANCELLED; } Dm dm; dm = Dm.create(directMessage, false); dms.add(dm); imageUrls.add(dm.profileImageUrl); if (isCancelled()) { return TaskResult.CANCELLED; } } maxId = db.fetchMaxDmId(true); try { if (maxId != null) { Paging paging = new Paging(maxId); dmList = getApi().getSentDirectMessages(paging); } else { dmList = getApi().getSentDirectMessages(); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } for (DirectMessage directMessage : dmList) { if (isCancelled()) { return TaskResult.CANCELLED; } Dm dm; dm = Dm.create(directMessage, true); dms.add(dm); imageUrls.add(dm.profileImageUrl); if (isCancelled()) { return TaskResult.CANCELLED; } } db.addDms(dms, false); // if (isCancelled()) { // return TaskResult.CANCELLED; // } // // publishProgress(null); // // for (String imageUrl : imageUrls) { // if (!Utils.isEmpty(imageUrl)) { // // Fetch image to cache. // try { // imageManager.put(imageUrl); // } catch (IOException e) { // Log.e(TAG, e.getMessage(), e); // } // } // // if (isCancelled()) { // return TaskResult.CANCELLED; // } // } return TaskResult.OK; } } private static class Adapter extends CursorAdapter { public Adapter(Context context, Cursor cursor) { super(context, cursor); mInflater = LayoutInflater.from(context); // TODO: 可使用: //DM dm = MessageTable.parseCursor(cursor); mUserTextColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_USER_SCREEN_NAME); mTextColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_TEXT); mProfileImageUrlColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_PROFILE_IMAGE_URL); mCreatedAtColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_CREATED_AT); mIsSentColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_IS_SENT); } private LayoutInflater mInflater; private int mUserTextColumn; private int mTextColumn; private int mProfileImageUrlColumn; private int mIsSentColumn; private int mCreatedAtColumn; @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater.inflate(R.layout.direct_message, parent, false); ViewHolder holder = new ViewHolder(); holder.userText = (TextView) view .findViewById(R.id.tweet_user_text); holder.tweetText = (TextView) view.findViewById(R.id.tweet_text); holder.profileImage = (ImageView) view .findViewById(R.id.profile_image); holder.metaText = (TextView) view .findViewById(R.id.tweet_meta_text); view.setTag(holder); return view; } class ViewHolder { public TextView userText; public TextView tweetText; public ImageView profileImage; public TextView metaText; } @Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder holder = (ViewHolder) view.getTag(); int isSent = cursor.getInt(mIsSentColumn); String user = cursor.getString(mUserTextColumn); if (0 == isSent) { holder.userText.setText(context .getString(R.string.direct_message_label_from_prefix) + user); } else { holder.userText.setText(context .getString(R.string.direct_message_label_to_prefix) + user); } TextHelper.setTweetText(holder.tweetText, cursor.getString(mTextColumn)); String profileImageUrl = cursor.getString(mProfileImageUrlColumn); if (!TextUtils.isEmpty(profileImageUrl)) { holder.profileImage .setImageBitmap(TwitterApplication.mImageLoader .get(profileImageUrl, new ImageLoaderCallback(){ @Override public void refresh(String url, Bitmap bitmap) { Adapter.this.refresh(); } })); } try { holder.metaText.setText(DateTimeHelper .getRelativeDate(TwitterDatabase.DB_DATE_FORMATTER .parse(cursor.getString(mCreatedAtColumn)))); } catch (ParseException e) { Log.w(TAG, "Invalid created at data."); } } public void refresh() { getCursor().requery(); } } // Menu. @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // FIXME: 将刷新功能绑定到顶部的刷新按钮上,主菜单中的刷新选项已删除 // case OPTIONS_MENU_ID_REFRESH: // doRetrieve(); // return true; case OPTIONS_MENU_ID_TWEETS: launchActivity(TwitterActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_REPLIES: launchActivity(MentionActivity.createIntent(this)); return true; } return super.onOptionsItemSelected(item); } private static final int CONTEXT_REPLY_ID = 0; private static final int CONTEXT_DELETE_ID = 1; @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply); menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); Cursor cursor = (Cursor) mAdapter.getItem(info.position); if (cursor == null) { Log.w(TAG, "Selected item not available."); return super.onContextItemSelected(item); } switch (item.getItemId()) { case CONTEXT_REPLY_ID: String user_id = cursor.getString(cursor .getColumnIndexOrThrow(MessageTable.FIELD_USER_ID)); Intent intent = WriteDmActivity.createIntent(user_id); startActivity(intent); return true; case CONTEXT_DELETE_ID: int idIndex = cursor.getColumnIndexOrThrow(MessageTable._ID); String id = cursor.getString(idIndex); doDestroy(id); return true; default: return super.onContextItemSelected(item); } } private void doDestroy(String id) { Log.d(TAG, "Attempting delete."); if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mDeleteTask = new DmDeleteTask(); mDeleteTask.setListener(mDeleteTaskListener); TaskParams params = new TaskParams(); params.put("id", id); mDeleteTask.execute(params); } } private class DmDeleteTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams...params) { TaskParams param = params[0]; try { String id = param.getString("id"); DirectMessage directMessage = getApi().destroyDirectMessage(id); Dm.create(directMessage, false); getDb().deleteDm(id); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } if (isCancelled()) { return TaskResult.CANCELLED; } return TaskResult.OK; } } public void doRetrieve() { Log.d(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mRetrieveTask = new DmRetrieveTask(); mRetrieveTask.setFeedback(mFeedback); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); } } public void goTop() { mTweetList.setSelection(0); } public void draw() { mAdapter.refresh(); mInboxAdapter.refresh(); mSendboxAdapter.refresh(); } private void updateProgress(String msg) { mProgressText.setText(msg); } }
Java
/* * Copyright (C) 2009 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.ch_linghu.fanfoudroid; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.Menu; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.fanfou.Status; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity; //TODO: 数据来源换成 getFavorites() public class FavoritesActivity extends TwitterCursorBaseActivity { private static final String TAG = "FavoritesActivity"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FAVORITES"; private static final String USER_ID = "userid"; private static final String USER_NAME = "userName"; private static final int DIALOG_WRITE_ID = 0; private String userId = null; private String userName = null; public static Intent createIntent(String userId, String userName) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(USER_ID, userId); intent.putExtra(USER_NAME, userName); return intent; } @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)){ mNavbar.setHeaderTitle(getActivityTitle()); return true; }else{ return false; } } public static Intent createNewTaskIntent(String userId, String userName) { Intent intent = createIntent(userId, userName); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } // Menu. @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } @Override protected Cursor fetchMessages() { // TODO Auto-generated method stub return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_FAVORITE); } @Override protected String getActivityTitle() { // TODO Auto-generated method stub String template = getString(R.string.page_title_favorites); String who; if (getUserId().equals(TwitterApplication.getMyselfId())){ who = "我"; }else{ who = getUserName(); } return MessageFormat.format(template, who); } @Override protected void markAllRead() { // TODO Auto-generated method stub getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_FAVORITE); } // hasRetrieveListTask interface @Override public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) { return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_FAVORITE, isUnread); } @Override public String fetchMaxId() { return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_FAVORITE); } @Override public List<Status> getMessageSinceId(String maxId) throws HttpException { if (maxId != null){ return getApi().getFavorites(getUserId(), new Paging(maxId)); }else{ return getApi().getFavorites(getUserId()); } } @Override public String fetchMinId() { return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_FAVORITE); } @Override public List<Status> getMoreMessageFromId(String minId) throws HttpException { Paging paging = new Paging(1, 20); paging.setMaxId(minId); return getApi().getFavorites(getUserId(), paging); } @Override public int getDatabaseType() { return StatusTable.TYPE_FAVORITE; } @Override public String getUserId() { Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null){ userId = extras.getString(USER_ID); } else { userId = TwitterApplication.getMyselfId(); } return userId; } public String getUserName(){ Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null){ userName = extras.getString(USER_NAME); } else { userName = TwitterApplication.getMyselfName(); } return userName; } }
Java
package com.ch_linghu.fanfoudroid; import java.text.MessageFormat; import java.util.List; import android.content.Intent; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ListView; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.ui.base.UserArrayBaseActivity; import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter; public class FollowingActivity extends UserArrayBaseActivity { private ListView mUserList; private UserArrayAdapter mAdapter; private String userId; private String userName; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FOLLOWING"; private static final String USER_ID = "userId"; private static final String USER_NAME = "userName"; private int currentPage=1; String myself=""; @Override protected boolean _onCreate(Bundle savedInstanceState) { Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { this.userId = extras.getString(USER_ID); this.userName = extras.getString(USER_NAME); } else { // 获取登录用户id userId=TwitterApplication.getMyselfId(); userName = TwitterApplication.getMyselfName(); } if(super._onCreate(savedInstanceState)){ myself = TwitterApplication.getMyselfId(); if(getUserId()==myself){ mNavbar.setHeaderTitle(MessageFormat.format( getString(R.string.profile_friends_count_title), "我")); } else { mNavbar.setHeaderTitle(MessageFormat.format( getString(R.string.profile_friends_count_title), userName)); } return true; }else{ return false; } } /* * 添加取消关注按钮 * @see com.ch_linghu.fanfoudroid.ui.base.UserListBaseActivity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo) */ @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if(getUserId()==myself){ AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; User user = getContextItemUser(info.position); menu.add(0,CONTENT_DEL_FRIEND,0,getResources().getString(R.string.cmenu_user_addfriend_prefix)+user.screenName+getResources().getString(R.string.cmenu_user_friend_suffix)); } } public static Intent createIntent(String userId, String userName) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(USER_ID, userId); intent.putExtra(USER_NAME, userName); return intent; } @Override public Paging getNextPage() { currentPage+=1; return new Paging(currentPage); } @Override protected String getUserId() { return this.userId; } @Override public Paging getCurrentPage() { return new Paging(this.currentPage); } @Override protected List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers( String userId, Paging page) throws HttpException { return getApi().getFriendsStatuses(userId, page); } }
Java
package com.ch_linghu.fanfoudroid; import java.text.MessageFormat; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.BaseColumns; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.db.UserInfoTable; import com.ch_linghu.fanfoudroid.fanfou.User; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.BaseActivity; import com.ch_linghu.fanfoudroid.ui.module.Feedback; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType; import com.ch_linghu.fanfoudroid.ui.module.NavBar; /** * * @author Dino 2011-02-26 */ // public class ProfileActivity extends WithHeaderActivity { public class ProfileActivity extends BaseActivity { private static final String TAG = "ProfileActivity"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.PROFILE"; private static final String STATUS_COUNT = "status_count"; private static final String EXTRA_USER = "user"; private static final String FANFOUROOT = "http://fanfou.com/"; private static final String USER_ID = "userid"; private static final String USER_NAME = "userName"; private GenericTask profileInfoTask;// 获取用户信息 private GenericTask setFollowingTask; private GenericTask cancelFollowingTask; private String userId; private String userName; private String myself; private User profileInfo;// 用户信息 private ImageView profileImageView;// 头像 private TextView profileName;// 名称 private TextView profileScreenName;// 昵称 private TextView userLocation;// 地址 private TextView userUrl;// url private TextView userInfo;// 自述 private TextView friendsCount;// 好友 private TextView followersCount;// 收听 private TextView statusCount;// 消息 private TextView favouritesCount;// 收藏 private TextView isFollowingText;// 是否关注 private Button followingBtn;// 收听/取消关注按钮 private Button sendMentionBtn;// 发送留言按钮 private Button sendDmBtn;// 发送私信按钮 private ProgressDialog dialog; // 请稍候 private RelativeLayout friendsLayout; private LinearLayout followersLayout; private LinearLayout statusesLayout; private LinearLayout favouritesLayout; private NavBar mNavBar; private Feedback mFeedback; private TwitterDatabase db; public static Intent createIntent(String userId) { Intent intent = new Intent(LAUNCH_ACTION); intent.putExtra(USER_ID, userId); return intent; } private ImageLoaderCallback callback = new ImageLoaderCallback() { @Override public void refresh(String url, Bitmap bitmap) { profileImageView.setImageBitmap(bitmap); } }; @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "OnCreate start"); if (super._onCreate(savedInstanceState)) { setContentView(R.layout.profile); Intent intent = getIntent(); Bundle extras = intent.getExtras(); myself = TwitterApplication.getMyselfId(); if (extras != null) { this.userId = extras.getString(USER_ID); this.userName = extras.getString(USER_NAME); } else { this.userId = myself; this.userName = TwitterApplication.getMyselfName(); } Uri data = intent.getData(); if (data != null) { userId = data.getLastPathSegment(); } // 初始化控件 initControls(); Log.d(TAG, "the userid is " + userId); db = this.getDb(); draw(); return true; } else { return false; } } private void initControls() { mNavBar = new NavBar(NavBar.HEADER_STYLE_HOME, this); mNavBar.setHeaderTitle(""); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); sendMentionBtn = (Button) findViewById(R.id.sendmetion_btn); sendDmBtn = (Button) findViewById(R.id.senddm_btn); profileImageView = (ImageView) findViewById(R.id.profileimage); profileName = (TextView) findViewById(R.id.profilename); profileScreenName = (TextView) findViewById(R.id.profilescreenname); userLocation = (TextView) findViewById(R.id.user_location); userUrl = (TextView) findViewById(R.id.user_url); userInfo = (TextView) findViewById(R.id.tweet_user_info); friendsCount = (TextView) findViewById(R.id.friends_count); followersCount = (TextView) findViewById(R.id.followers_count); TextView friendsCountTitle = (TextView) findViewById(R.id.friends_count_title); TextView followersCountTitle = (TextView) findViewById(R.id.followers_count_title); String who; if (userId.equals(myself)) { who = "我"; } else { who = "ta"; } friendsCountTitle.setText(MessageFormat.format( getString(R.string.profile_friends_count_title), who)); followersCountTitle.setText(MessageFormat.format( getString(R.string.profile_followers_count_title), who)); statusCount = (TextView) findViewById(R.id.statuses_count); favouritesCount = (TextView) findViewById(R.id.favourites_count); friendsLayout = (RelativeLayout) findViewById(R.id.friendsLayout); followersLayout = (LinearLayout) findViewById(R.id.followersLayout); statusesLayout = (LinearLayout) findViewById(R.id.statusesLayout); favouritesLayout = (LinearLayout) findViewById(R.id.favouritesLayout); isFollowingText = (TextView) findViewById(R.id.isfollowing_text); followingBtn = (Button) findViewById(R.id.following_btn); // 为按钮面板添加事件 friendsLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 在没有得到profileInfo时,不允许点击事件生效 if (profileInfo == null) { return; } String showName; if (!TextUtils.isEmpty(profileInfo.getScreenName())) { showName = profileInfo.getScreenName(); } else { showName = profileInfo.getName(); } Intent intent = FollowingActivity .createIntent(userId, showName); intent.setClass(ProfileActivity.this, FollowingActivity.class); startActivity(intent); } }); followersLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 在没有得到profileInfo时,不允许点击事件生效 if (profileInfo == null) { return; } String showName; if (!TextUtils.isEmpty(profileInfo.getScreenName())) { showName = profileInfo.getScreenName(); } else { showName = profileInfo.getName(); } Intent intent = FollowersActivity .createIntent(userId, showName); intent.setClass(ProfileActivity.this, FollowersActivity.class); startActivity(intent); } }); statusesLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 在没有得到profileInfo时,不允许点击事件生效 if (profileInfo == null) { return; } String showName; if (!TextUtils.isEmpty(profileInfo.getScreenName())) { showName = profileInfo.getScreenName(); } else { showName = profileInfo.getName(); } Intent intent = UserTimelineActivity.createIntent( profileInfo.getId(), showName); launchActivity(intent); } }); favouritesLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 在没有得到profileInfo时,不允许点击事件生效 if (profileInfo == null) { return; } Intent intent = FavoritesActivity.createIntent(userId, profileInfo.getName()); intent.setClass(ProfileActivity.this, FavoritesActivity.class); startActivity(intent); } }); // 刷新 View.OnClickListener refreshListener = new View.OnClickListener() { @Override public void onClick(View v) { doGetProfileInfo(); } }; mNavBar.getRefreshButton().setOnClickListener(refreshListener); } private void draw() { Log.d(TAG, "draw"); bindProfileInfo(); // doGetProfileInfo(); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume."); } @Override protected void onStart() { super.onStart(); Log.d(TAG, "onStart."); } @Override protected void onStop() { super.onStop(); Log.d(TAG, "onStop."); } /** * 从数据库获取,如果数据库不存在则创建 */ private void bindProfileInfo() { dialog = ProgressDialog.show(ProfileActivity.this, "请稍候", "正在加载信息..."); if (null != db && db.existsUser(userId)) { Cursor cursor = db.getUserInfoById(userId); profileInfo = User.parseUser(cursor); cursor.close(); if (profileInfo == null) { Log.w(TAG, "cannot get userinfo from userinfotable the id is" + userId); } bindControl(); if (dialog != null) { dialog.dismiss(); } } else { doGetProfileInfo(); } } private void doGetProfileInfo() { mFeedback.start(""); if (profileInfoTask != null && profileInfoTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { profileInfoTask = new GetProfileTask(); profileInfoTask.setListener(profileInfoTaskListener); TaskParams params = new TaskParams(); profileInfoTask.execute(params); } } private void bindControl() { if (profileInfo.getId().equals(myself)) { sendMentionBtn.setVisibility(View.GONE); sendDmBtn.setVisibility(View.GONE); } else { // 发送留言 sendMentionBtn.setVisibility(View.VISIBLE); sendMentionBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = WriteActivity.createNewTweetIntent(String .format("@%s ", profileInfo.getScreenName())); startActivity(intent); } }); // 发送私信 sendDmBtn.setVisibility(View.VISIBLE); sendDmBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = WriteDmActivity.createIntent(profileInfo .getId()); startActivity(intent); } }); } if (userId.equals(myself)) { mNavBar.setHeaderTitle("我" + getString(R.string.cmenu_user_profile_prefix)); } else { mNavBar.setHeaderTitle(profileInfo.getScreenName() + getString(R.string.cmenu_user_profile_prefix)); } profileImageView .setImageBitmap(TwitterApplication.mImageLoader .get(profileInfo.getProfileImageURL().toString(), callback)); profileName.setText(profileInfo.getId()); profileScreenName.setText(profileInfo.getScreenName()); if (profileInfo.getId().equals(myself)) { isFollowingText.setText(R.string.profile_isyou); followingBtn.setVisibility(View.GONE); } else if (profileInfo.isFollowing()) { isFollowingText.setText(R.string.profile_isfollowing); followingBtn.setVisibility(View.VISIBLE); followingBtn.setText(R.string.user_label_unfollow); followingBtn.setOnClickListener(cancelFollowingListener); followingBtn.setCompoundDrawablesWithIntrinsicBounds(getResources() .getDrawable(R.drawable.ic_unfollow), null, null, null); } else { isFollowingText.setText(R.string.profile_notfollowing); followingBtn.setVisibility(View.VISIBLE); followingBtn.setText(R.string.user_label_follow); followingBtn.setOnClickListener(setfollowingListener); followingBtn.setCompoundDrawablesWithIntrinsicBounds(getResources() .getDrawable(R.drawable.ic_follow), null, null, null); } String location = profileInfo.getLocation(); if (location == null || location.length() == 0) { location = getResources().getString(R.string.profile_location_null); } userLocation.setText(location); if (profileInfo.getURL() != null) { userUrl.setText(profileInfo.getURL().toString()); } else { userUrl.setText(FANFOUROOT + profileInfo.getId()); } String description = profileInfo.getDescription(); if (description == null || description.length() == 0) { description = getResources().getString( R.string.profile_description_null); } userInfo.setText(description); friendsCount.setText(String.valueOf(profileInfo.getFriendsCount())); followersCount.setText(String.valueOf(profileInfo.getFollowersCount())); statusCount.setText(String.valueOf(profileInfo.getStatusesCount())); favouritesCount .setText(String.valueOf(profileInfo.getFavouritesCount())); } private TaskListener profileInfoTaskListener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { // 加载成功 if (result == TaskResult.OK) { mFeedback.success(""); // 绑定控件 bindControl(); if (dialog != null) { dialog.dismiss(); } } } @Override public String getName() { return "GetProfileInfo"; } }; /** * 更新数据库中的用户 * * @return */ private boolean updateUser() { ContentValues v = new ContentValues(); v.put(BaseColumns._ID, profileInfo.getName()); v.put(UserInfoTable.FIELD_USER_NAME, profileInfo.getName()); v.put(UserInfoTable.FIELD_USER_SCREEN_NAME, profileInfo.getScreenName()); v.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, profileInfo .getProfileImageURL().toString()); v.put(UserInfoTable.FIELD_LOCALTION, profileInfo.getLocation()); v.put(UserInfoTable.FIELD_DESCRIPTION, profileInfo.getDescription()); v.put(UserInfoTable.FIELD_PROTECTED, profileInfo.isProtected()); v.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, profileInfo.getFollowersCount()); v.put(UserInfoTable.FIELD_LAST_STATUS, profileInfo.getStatusSource()); v.put(UserInfoTable.FIELD_FRIENDS_COUNT, profileInfo.getFriendsCount()); v.put(UserInfoTable.FIELD_FAVORITES_COUNT, profileInfo.getFavouritesCount()); v.put(UserInfoTable.FIELD_STATUSES_COUNT, profileInfo.getStatusesCount()); v.put(UserInfoTable.FIELD_FOLLOWING, profileInfo.isFollowing()); if (profileInfo.getURL() != null) { v.put(UserInfoTable.FIELD_URL, profileInfo.getURL().toString()); } return db.updateUser(profileInfo.getId(), v); } /** * 获取用户信息task * * @author Dino * */ private class GetProfileTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.v(TAG, "get profile task"); try { profileInfo = getApi().showUser(userId); mFeedback.update(80); if (profileInfo != null) { if (null != db && !db.existsUser(userId)) { com.ch_linghu.fanfoudroid.data.User userinfodb = profileInfo .parseUser(); db.createUserInfo(userinfodb); } else { // 更新用户 updateUser(); } } } catch (HttpException e) { Log.e(TAG, e.getMessage()); return TaskResult.FAILED; } mFeedback.update(99); return TaskResult.OK; } } /** * 设置关注监听 */ private OnClickListener setfollowingListener = new OnClickListener() { @Override public void onClick(View v) { Builder diaBuilder = new AlertDialog.Builder(ProfileActivity.this) .setTitle("关注提示").setMessage("确实要添加关注吗?"); diaBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (setFollowingTask != null && setFollowingTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { setFollowingTask = new SetFollowingTask(); setFollowingTask .setListener(setFollowingTaskLinstener); TaskParams params = new TaskParams(); setFollowingTask.execute(params); } } }); diaBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = diaBuilder.create(); dialog.show(); } }; /* * 取消关注监听 */ private OnClickListener cancelFollowingListener = new OnClickListener() { @Override public void onClick(View v) { Builder diaBuilder = new AlertDialog.Builder(ProfileActivity.this) .setTitle("关注提示").setMessage("确实要取消关注吗?"); diaBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (cancelFollowingTask != null && cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { cancelFollowingTask = new CancelFollowingTask(); cancelFollowingTask .setListener(cancelFollowingTaskLinstener); TaskParams params = new TaskParams(); cancelFollowingTask.execute(params); } } }); diaBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = diaBuilder.create(); dialog.show(); } }; /** * 设置关注 * * @author Dino * */ private class SetFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { getApi().createFriendship(userId); } catch (HttpException e) { Log.w(TAG, "create friend ship error"); return TaskResult.FAILED; } return TaskResult.OK; } } private TaskListener setFollowingTaskLinstener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { followingBtn.setText("取消关注"); isFollowingText.setText(getResources().getString( R.string.profile_isfollowing)); followingBtn.setOnClickListener(cancelFollowingListener); Toast.makeText(getBaseContext(), "关注成功", Toast.LENGTH_SHORT) .show(); } else if (result == TaskResult.FAILED) { Toast.makeText(getBaseContext(), "关注失败", Toast.LENGTH_SHORT) .show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; /** * 取消关注 * * @author Dino * */ private class CancelFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { getApi().destroyFriendship(userId); } catch (HttpException e) { Log.w(TAG, "create friend ship error"); return TaskResult.FAILED; } return TaskResult.OK; } } private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { followingBtn.setText("添加关注"); isFollowingText.setText(getResources().getString( R.string.profile_notfollowing)); followingBtn.setOnClickListener(setfollowingListener); Toast.makeText(getBaseContext(), "取消关注成功", Toast.LENGTH_SHORT) .show(); } else if (result == TaskResult.FAILED) { Toast.makeText(getBaseContext(), "取消关注失败", Toast.LENGTH_SHORT) .show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; }
Java
package com.ch_linghu.fanfoudroid.dao; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.text.TextUtils; import android.util.Log; import com.ch_linghu.fanfoudroid.dao.SQLiteTemplate.RowMapper; import com.ch_linghu.fanfoudroid.data2.Photo; import com.ch_linghu.fanfoudroid.data2.Status; import com.ch_linghu.fanfoudroid.data2.User; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.db2.FanContent; import com.ch_linghu.fanfoudroid.db2.FanContent.StatusesPropertyTable; import com.ch_linghu.fanfoudroid.db2.FanDatabase; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.db2.FanContent.*; public class StatusDAO { private static final String TAG = "StatusDAO"; private SQLiteTemplate mSqlTemplate; public StatusDAO(Context context) { mSqlTemplate = new SQLiteTemplate(FanDatabase.getInstance(context) .getSQLiteOpenHelper()); } /** * Insert a Status * * 若报 SQLiteconstraintexception 异常, 检查是否某not null字段为空 * * @param status * @param isUnread * @return */ public long insertStatus(Status status) { if (!isExists(status)) { return mSqlTemplate.getDb(true).insert(StatusesTable.TABLE_NAME, null, statusToContentValues(status)); } else { Log.e(TAG, status.getId() + " is exists."); return -1; } } // TODO: public int insertStatuses(List<Status> statuses) { int result = 0; SQLiteDatabase db = mSqlTemplate.getDb(true); try { db.beginTransaction(); for (int i = statuses.size() - 1; i >= 0; i--) { Status status = statuses.get(i); long id = db.insertWithOnConflict(StatusesTable.TABLE_NAME, null, statusToContentValues(status), SQLiteDatabase.CONFLICT_IGNORE); if (-1 == id) { Log.e(TAG, "cann't insert the tweet : " + status.toString()); } else { ++result; Log.v(TAG, String.format( "Insert a status into database : %s", status.toString())); } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } return result; } /** * Delete a status * * @param statusId * @param owner_id * owner id * @param type * status type * @return * @see StatusDAO#deleteStatus(Status) */ public int deleteStatus(String statusId, String owner_id, int type) { //FIXME: 数据模型改变后这里的逻辑需要完全重写,目前仅保证编译可通过 String where = StatusesTable.Columns.ID + " =? "; String[] binds; if (!TextUtils.isEmpty(owner_id)) { where += " AND " + StatusesPropertyTable.Columns.OWNER_ID + " = ? "; binds = new String[] { statusId, owner_id }; } else { binds = new String[] { statusId }; } if (-1 != type) { where += " AND " + StatusesPropertyTable.Columns.TYPE + " = " + type; } return mSqlTemplate.getDb(true).delete(StatusesTable.TABLE_NAME, where.toString(), binds); } /** * Delete a Status * * @param status * @return * @see StatusDAO#deleteStatus(String, String, int) */ public int deleteStatus(Status status) { return deleteStatus(status.getId(), status.getOwnerId(), status.getType()); } /** * Find a status by status ID * * @param statusId * @return */ public Status fetchStatus(String statusId) { return mSqlTemplate.queryForObject(mRowMapper, StatusesTable.TABLE_NAME, null, StatusesTable.Columns.ID + " = ?", new String[] { statusId }, null, null, "created_at DESC", "1"); } /** * Find user's statuses * * @param userId * user id * @param statusType * status type, see {@link StatusTable#TYPE_USER}... * @return list of statuses */ public List<Status> fetchStatuses(String userId, int statusType) { return mSqlTemplate.queryForList(mRowMapper, FanContent.StatusesTable.TABLE_NAME, null, StatusesPropertyTable.Columns.OWNER_ID + " = ? AND " + StatusesPropertyTable.Columns.TYPE + " = " + statusType, new String[] { userId }, null, null, "created_at DESC", null); } /** * @see StatusDAO#fetchStatuses(String, int) */ public List<Status> fetchStatuses(String userId, String statusType) { return fetchStatuses(userId, Integer.parseInt(statusType)); } /** * Update by using {@link ContentValues} * * @param statusId * @param newValues * @return */ public int updateStatus(String statusId, ContentValues values) { return mSqlTemplate.updateById(FanContent.StatusesTable.TABLE_NAME, statusId, values); } /** * Update by using {@link Status} * * @param status * @return */ public int updateStatus(Status status) { return updateStatus(status.getId(), statusToContentValues(status)); } /** * Check if status exists * * FIXME: 取消使用Query * * @param status * @return */ public boolean isExists(Status status) { StringBuilder sql = new StringBuilder(); sql.append("SELECT COUNT(*) FROM ").append(FanContent.StatusesTable.TABLE_NAME) .append(" WHERE ").append(StatusesTable.Columns.ID).append(" =? AND ") .append(StatusesPropertyTable.Columns.OWNER_ID).append(" =? AND ") .append(StatusesPropertyTable.Columns.TYPE).append(" = ") .append(status.getType()); return mSqlTemplate.isExistsBySQL(sql.toString(), new String[] { status.getId(), status.getUser().getId() }); } /** * Status -> ContentValues * * @param status * @param isUnread * @return */ private ContentValues statusToContentValues(Status status) { final ContentValues v = new ContentValues(); v.put(StatusesTable.Columns.ID, status.getId()); v.put(StatusesPropertyTable.Columns.TYPE, status.getType()); v.put(StatusesTable.Columns.TEXT, status.getText()); v.put(StatusesPropertyTable.Columns.OWNER_ID, status.getOwnerId()); v.put(StatusesTable.Columns.FAVORITED, status.isFavorited() + ""); v.put(StatusesTable.Columns.TRUNCATED, status.isTruncated()); // TODO: v.put(StatusesTable.Columns.IN_REPLY_TO_STATUS_ID, status.getInReplyToStatusId()); v.put(StatusesTable.Columns.IN_REPLY_TO_USER_ID, status.getInReplyToUserId()); // v.put(StatusTable.Columns.IN_REPLY_TO_SCREEN_NAME, // status.getInReplyToScreenName()); // v.put(IS_REPLY, status.isReply()); v.put(StatusesTable.Columns.CREATED_AT, TwitterDatabase.DB_DATE_FORMATTER.format(status.getCreatedAt())); v.put(StatusesTable.Columns.SOURCE, status.getSource()); // v.put(StatusTable.Columns.IS_UNREAD, status.isUnRead()); final User user = status.getUser(); if (user != null) { v.put(UserTable.Columns.USER_ID, user.getId()); v.put(UserTable.Columns.SCREEN_NAME, user.getScreenName()); v.put(UserTable.Columns.PROFILE_IMAGE_URL, user.getProfileImageUrl()); } final Photo photo = status.getPhotoUrl(); /*if (photo != null) { v.put(StatusTable.Columns.PIC_THUMB, photo.getThumburl()); v.put(StatusTable.Columns.PIC_MID, photo.getImageurl()); v.put(StatusTable.Columns.PIC_ORIG, photo.getLargeurl()); }*/ return v; } private static final RowMapper<Status> mRowMapper = new RowMapper<Status>() { @Override public Status mapRow(Cursor cursor, int rowNum) { Photo photo = new Photo(); /*photo.setImageurl(cursor.getString(cursor .getColumnIndex(StatusTable.Columns.PIC_MID))); photo.setLargeurl(cursor.getString(cursor .getColumnIndex(StatusTable.Columns.PIC_ORIG))); photo.setThumburl(cursor.getString(cursor .getColumnIndex(StatusTable.Columns.PIC_THUMB))); */ User user = new User(); user.setScreenName(cursor.getString(cursor .getColumnIndex(UserTable.Columns.SCREEN_NAME))); user.setId(cursor.getString(cursor .getColumnIndex(UserTable.Columns.USER_ID))); user.setProfileImageUrl(cursor.getString(cursor .getColumnIndex(UserTable.Columns.PROFILE_IMAGE_URL))); Status status = new Status(); status.setPhotoUrl(photo); status.setUser(user); status.setOwnerId(cursor.getString(cursor .getColumnIndex(StatusesPropertyTable.Columns.OWNER_ID))); // TODO: 将数据库中的statusType改成Int类型 status.setType(cursor.getInt(cursor .getColumnIndex(StatusesPropertyTable.Columns.TYPE))); status.setId(cursor.getString(cursor .getColumnIndex(StatusesTable.Columns.ID))); status.setCreatedAt(DateTimeHelper.parseDateTimeFromSqlite(cursor .getString(cursor.getColumnIndex(StatusesTable.Columns.CREATED_AT)))); // TODO: 更改favorite 在数据库类型为boolean后改为 " != 0 " status.setFavorited(cursor.getString( cursor.getColumnIndex(StatusesTable.Columns.FAVORITED)) .equals("true")); status.setText(cursor.getString(cursor .getColumnIndex(StatusesTable.Columns.TEXT))); status.setSource(cursor.getString(cursor .getColumnIndex(StatusesTable.Columns.SOURCE))); // status.setInReplyToScreenName(cursor.getString(cursor // .getColumnIndex(StatusTable.IN_REPLY_TO_SCREEN_NAME))); status.setInReplyToStatusId(cursor.getString(cursor .getColumnIndex(StatusesTable.Columns.IN_REPLY_TO_STATUS_ID))); status.setInReplyToUserId(cursor.getString(cursor .getColumnIndex(StatusesTable.Columns.IN_REPLY_TO_USER_ID))); status.setTruncated(cursor.getInt(cursor .getColumnIndex(StatusesTable.Columns.TRUNCATED)) != 0); // status.setUnRead(cursor.getInt(cursor // .getColumnIndex(StatusTable.Columns.IS_UNREAD)) != 0); return status; } }; }
Java
package com.ch_linghu.fanfoudroid.dao; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Database Helper * * @see SQLiteDatabase */ public class SQLiteTemplate { /** * Default Primary key */ protected String mPrimaryKey = "_id"; /** * SQLiteDatabase Open Helper */ protected SQLiteOpenHelper mDatabaseOpenHelper; /** * Construct * * @param databaseOpenHelper */ public SQLiteTemplate(SQLiteOpenHelper databaseOpenHelper) { mDatabaseOpenHelper = databaseOpenHelper; } /** * Construct * * @param databaseOpenHelper * @param primaryKey */ public SQLiteTemplate(SQLiteOpenHelper databaseOpenHelper, String primaryKey) { this(databaseOpenHelper); setPrimaryKey(primaryKey); } /** * 根据某一个字段和值删除一行数据, 如 name="jack" * * @param table * @param field * @param value * @return */ public int deleteByField(String table, String field, String value) { return getDb(true).delete(table, field + "=?", new String[] { value }); } /** * 根据主键删除一行数据 * * @param table * @param id * @return */ public int deleteById(String table, String id) { return deleteByField(table, mPrimaryKey, id); } /** * 根据主键更新一行数据 * * @param table * @param id * @param values * @return */ public int updateById(String table, String id, ContentValues values) { return getDb(true).update(table, values, mPrimaryKey + "=?", new String[] { id }); } /** * 根据主键查看某条数据是否存在 * * @param table * @param id * @return */ public boolean isExistsById(String table, String id) { return isExistsByField(table, mPrimaryKey, id); } /** * 根据某字段/值查看某条数据是否存在 * * @param status * @return */ public boolean isExistsByField(String table, String field, String value) { StringBuilder sql = new StringBuilder(); sql.append("SELECT COUNT(*) FROM ").append(table).append(" WHERE ") .append(field).append(" =?"); return isExistsBySQL(sql.toString(), new String[] { value }); } /** * 使用SQL语句查看某条数据是否存在 * * @param sql * @param selectionArgs * @return */ public boolean isExistsBySQL(String sql, String[] selectionArgs) { boolean result = false; final Cursor c = getDb(false).rawQuery(sql, selectionArgs); try { if (c.moveToFirst()) { result = (c.getInt(0) > 0); } } finally { c.close(); } return result; } /** * Query for cursor * * @param <T> * @param rowMapper * @return a cursor * * @see SQLiteDatabase#query(String, String[], String, String[], String, * String, String, String) */ public <T> T queryForObject(RowMapper<T> rowMapper, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) { T object = null; final Cursor c = getDb(false).query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit); try { if (c.moveToFirst()) { object = rowMapper.mapRow(c, c.getCount()); } } finally { c.close(); } return object; } /** * Query for list * * @param <T> * @param rowMapper * @return list of object * * @see SQLiteDatabase#query(String, String[], String, String[], String, * String, String, String) */ public <T> List<T> queryForList(RowMapper<T> rowMapper, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) { List<T> list = new ArrayList<T>(); final Cursor c = getDb(false).query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit); try { while (c.moveToNext()) { list.add(rowMapper.mapRow(c, 1)); } } finally { c.close(); } return list; } /** * Get Primary Key * * @return */ public String getPrimaryKey() { return mPrimaryKey; } /** * Set Primary Key * * @param primaryKey */ public void setPrimaryKey(String primaryKey) { this.mPrimaryKey = primaryKey; } /** * Get Database Connection * * @param writeable * @return * @see SQLiteOpenHelper#getWritableDatabase(); * @see SQLiteOpenHelper#getReadableDatabase(); */ public SQLiteDatabase getDb(boolean writeable) { if (writeable) { return mDatabaseOpenHelper.getWritableDatabase(); } else { return mDatabaseOpenHelper.getReadableDatabase(); } } /** * Some as Spring JDBC RowMapper * * @see org.springframework.jdbc.core.RowMapper * @see com.ch_linghu.fanfoudroid.db.dao.SqliteTemplate * @param <T> */ public interface RowMapper<T> { public T mapRow(Cursor cursor, int rowNum); } }
Java
package com.ch_linghu.fanfoudroid.db2; import android.content.Context; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.ch_linghu.fanfoudroid.db2.FanContent.*; public class FanDatabase { private static final String TAG = FanDatabase.class.getSimpleName(); /** * SQLite Database file name */ private static final String DATABASE_NAME = "fanfoudroid.db"; /** * Database Version */ public static final int DATABASE_VERSION = 2; /** * self instance */ private static FanDatabase sInstance = null; /** * SQLiteDatabase Open Helper */ private DatabaseHelper mOpenHelper = null; /** * SQLiteOpenHelper */ private static class DatabaseHelper extends SQLiteOpenHelper { // Construct public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { Log.d(TAG, "Create Database."); // TODO: create tables createAllTables(db); createAllIndexes(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.d(TAG, "Upgrade Database."); // TODO: DROP TABLE onCreate(db); } } /** * Construct * * @param context */ private FanDatabase(Context context) { mOpenHelper = new DatabaseHelper(context); } /** * Get Database * * @param context * @return */ public static synchronized FanDatabase getInstance(Context context) { if (null == sInstance) { sInstance = new FanDatabase(context); } return sInstance; } /** * Get SQLiteDatabase Open Helper * * @return */ public SQLiteOpenHelper getSQLiteOpenHelper() { return mOpenHelper; } /** * Get Database Connection * * @param writeable * @return */ public SQLiteDatabase getDb(boolean writeable) { if (writeable) { return mOpenHelper.getWritableDatabase(); } else { return mOpenHelper.getReadableDatabase(); } } /** * Close Database */ public void close() { if (null != sInstance) { mOpenHelper.close(); sInstance = null; } } // Create All tables private static void createAllTables(SQLiteDatabase db) { db.execSQL(StatusesTable.getCreateSQL()); db.execSQL(StatusesPropertyTable.getCreateSQL()); db.execSQL(UserTable.getCreateSQL()); db.execSQL(DirectMessageTable.getCreateSQL()); db.execSQL(FollowRelationshipTable.getCreateSQL()); db.execSQL(TrendTable.getCreateSQL()); db.execSQL(SavedSearchTable.getCreateSQL()); } private static void dropAllTables(SQLiteDatabase db) { db.execSQL(StatusesTable.getDropSQL()); db.execSQL(StatusesPropertyTable.getDropSQL()); db.execSQL(UserTable.getDropSQL()); db.execSQL(DirectMessageTable.getDropSQL()); db.execSQL(FollowRelationshipTable.getDropSQL()); db.execSQL(TrendTable.getDropSQL()); db.execSQL(SavedSearchTable.getDropSQL()); } private static void resetAllTables(SQLiteDatabase db, int oldVersion, int newVersion) { try { dropAllTables(db); } catch (SQLException e) { Log.e(TAG, "resetAllTables ERROR!"); } createAllTables(db); } //indexes private static void createAllIndexes(SQLiteDatabase db) { db.execSQL(StatusesTable.getCreateIndexSQL()); } }
Java
package com.ch_linghu.fanfoudroid.db2; import java.util.zip.CheckedOutputStream; import android.R.color; public abstract class FanContent { /** * 消息表 消息表存放消息本身 * * @author phoenix * */ public static class StatusesTable { public static final String TABLE_NAME = "t_statuses"; public static class Columns { public static final String ID = "_id"; public static final String STATUS_ID = "status_id"; public static final String AUTHOR_ID = "author_id"; public static final String TEXT = "text"; public static final String SOURCE = "source"; public static final String CREATED_AT = "created_at"; public static final String TRUNCATED = "truncated"; public static final String FAVORITED = "favorited"; public static final String PHOTO_URL = "photo_url"; public static final String IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id"; public static final String IN_REPLY_TO_USER_ID = "in_reply_to_user_id"; public static final String IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name"; } public static String getCreateSQL() { String createString = TABLE_NAME + "( " + Columns.ID + " INTEGER PRIMARY KEY, " + Columns.STATUS_ID + " TEXT UNIQUE NOT NULL, " + Columns.AUTHOR_ID + " TEXT, " + Columns.TEXT + " TEXT, " + Columns.SOURCE + " TEXT, " + Columns.CREATED_AT + " INT, " + Columns.TRUNCATED + " INT DEFAULT 0, " + Columns.FAVORITED + " INT DEFAULT 0, " + Columns.PHOTO_URL + " TEXT, " + Columns.IN_REPLY_TO_STATUS_ID + " TEXT, " + Columns.IN_REPLY_TO_USER_ID + " TEXT, " + Columns.IN_REPLY_TO_SCREEN_NAME + " TEXT " + ");"; return "CREATE TABLE " + createString; } public static String getDropSQL() { return "DROP TABLE " + TABLE_NAME; } public static String[] getIndexColumns() { return new String[] { Columns.ID, Columns.STATUS_ID, Columns.AUTHOR_ID, Columns.TEXT, Columns.SOURCE, Columns.CREATED_AT, Columns.TRUNCATED, Columns.FAVORITED, Columns.PHOTO_URL, Columns.IN_REPLY_TO_STATUS_ID, Columns.IN_REPLY_TO_USER_ID, Columns.IN_REPLY_TO_SCREEN_NAME }; } public static String getCreateIndexSQL() { String createIndexSQL = "CREATE INDEX " + TABLE_NAME + "_idx ON " + TABLE_NAME + " ( " + getIndexColumns()[1] + " );"; return createIndexSQL; } } /** * 消息属性表 每一条消息所属类别、所有者等信息 消息ID(外键) 所有者(随便看看的所有者为空) * 消息类别(随便看看/首页(自己及自己好友)/个人(仅自己)/收藏/照片) * * @author phoenix * */ public static class StatusesPropertyTable { public static final String TABLE_NAME = "t_statuses_property"; public static class Columns { public static final String ID = "_id"; public static final String STATUS_ID = "status_id"; public static final String OWNER_ID = "owner_id"; public static final String TYPE = "type"; public static final String SEQUENCE_FLAG = "sequence_flag"; public static final String LOAD_TIME = "load_time"; } public static String getCreateSQL() { String createString = TABLE_NAME + "( " + Columns.ID + " INTEGER PRIMARY KEY, " + Columns.STATUS_ID + " TEXT NOT NULL, " + Columns.OWNER_ID + " TEXT, " + Columns.TYPE + " INT, " + Columns.SEQUENCE_FLAG + " INT, " + Columns.LOAD_TIME + " TIMESTAMP default (DATETIME('now', 'localtime')) " + ");"; return "CREATE TABLE " + createString; } public static String getDropSQL() { return "DROP TABLE " + TABLE_NAME; } public static String[] getIndexColumns() { return new String[] { Columns.ID, Columns.STATUS_ID, Columns.OWNER_ID, Columns.TYPE, Columns.SEQUENCE_FLAG, Columns.LOAD_TIME }; } } /** * User表 包括User的基本信息和扩展信息(每次获得最新User信息都update进User表) * 每次更新User表时希望能更新LOAD_TIME,记录最后更新时间 * * @author phoenix * */ public static class UserTable { public static final String TABLE_NAME = "t_user"; public static class Columns { public static final String ID = "_id"; public static final String USER_ID = "user_id"; public static final String USER_NAME = "user_name"; public static final String SCREEN_NAME = "screen_name"; public static final String LOCATION = "location"; public static final String DESCRIPTION = "description"; public static final String URL = "url"; public static final String PROTECTED = "protected"; public static final String PROFILE_IMAGE_URL = "profile_image_url"; public static final String FOLLOWERS_COUNT = "followers_count"; public static final String FRIENDS_COUNT = "friends_count"; public static final String FAVOURITES_COUNT = "favourites_count"; public static final String STATUSES_COUNT = "statuses_count"; public static final String CREATED_AT = "created_at"; public static final String FOLLOWING = "following"; public static final String NOTIFICATIONS = "notifications"; public static final String UTC_OFFSET = "utc_offset"; public static final String LOAD_TIME = "load_time"; } public static String getCreateSQL() { String createString = TABLE_NAME + "( " + Columns.ID + " INTEGER PRIMARY KEY, " + Columns.USER_ID + " TEXT UNIQUE NOT NULL, " + Columns.USER_NAME + " TEXT UNIQUE NOT NULL, " + Columns.SCREEN_NAME + " TEXT, " + Columns.LOCATION + " TEXT, " + Columns.DESCRIPTION + " TEXT, " + Columns.URL + " TEXT, " + Columns.PROTECTED + " INT DEFAULT 0, " + Columns.PROFILE_IMAGE_URL + " TEXT " + Columns.FOLLOWERS_COUNT + " INT, " + Columns.FRIENDS_COUNT + " INT, " + Columns.FAVOURITES_COUNT + " INT, " + Columns.STATUSES_COUNT + " INT, " + Columns.CREATED_AT + " INT, " + Columns.FOLLOWING + " INT DEFAULT 0, " + Columns.NOTIFICATIONS + " INT DEFAULT 0, " + Columns.UTC_OFFSET + " TEXT, " + Columns.LOAD_TIME + " TIMESTAMP default (DATETIME('now', 'localtime')) " + ");"; return "CREATE TABLE " + createString; } public static String getDropSQL() { return "DROP TABLE " + TABLE_NAME; } public static String[] getIndexColumns() { return new String[] { Columns.ID, Columns.USER_ID, Columns.USER_NAME, Columns.SCREEN_NAME, Columns.LOCATION, Columns.DESCRIPTION, Columns.URL, Columns.PROTECTED, Columns.PROFILE_IMAGE_URL, Columns.FOLLOWERS_COUNT, Columns.FRIENDS_COUNT, Columns.FAVOURITES_COUNT, Columns.STATUSES_COUNT, Columns.CREATED_AT, Columns.FOLLOWING, Columns.NOTIFICATIONS, Columns.UTC_OFFSET, Columns.LOAD_TIME }; } } /** * 私信表 私信的基本信息 * * @author phoenix * */ public static class DirectMessageTable { public static final String TABLE_NAME = "t_direct_message"; public static class Columns { public static final String ID = "_id"; public static final String MSG_ID = "msg_id"; public static final String TEXT = "text"; public static final String SENDER_ID = "sender_id"; public static final String RECIPINET_ID = "recipinet_id"; public static final String CREATED_AT = "created_at"; public static final String LOAD_TIME = "load_time"; public static final String SEQUENCE_FLAG = "sequence_flag"; } public static String getCreateSQL() { String createString = TABLE_NAME + "( " + Columns.ID + " INTEGER PRIMARY KEY, " + Columns.MSG_ID + " TEXT UNIQUE NOT NULL, " + Columns.TEXT + " TEXT, " + Columns.SENDER_ID + " TEXT, " + Columns.RECIPINET_ID + " TEXT, " + Columns.CREATED_AT + " INT, " + Columns.SEQUENCE_FLAG + " INT, " + Columns.LOAD_TIME + " TIMESTAMP default (DATETIME('now', 'localtime')) " + ");"; return "CREATE TABLE " + createString; } public static String getDropSQL() { return "DROP TABLE " + TABLE_NAME; } public static String[] getIndexColumns() { return new String[] { Columns.ID, Columns.MSG_ID, Columns.TEXT, Columns.SENDER_ID, Columns.RECIPINET_ID, Columns.CREATED_AT, Columns.SEQUENCE_FLAG, Columns.LOAD_TIME }; } } /** * Follow关系表 某个特定用户的Follow关系(User1 following User2, * 查找关联某人好友只需限定User1或者User2) * * @author phoenix * */ public static class FollowRelationshipTable { public static final String TABLE_NAME = "t_follow_relationship"; public static class Columns { public static final String USER1_ID = "user1_id"; public static final String USER2_ID = "user2_id"; public static final String LOAD_TIME = "load_time"; } public static String getCreateSQL() { String createString = TABLE_NAME + "( " + Columns.USER1_ID + " TEXT, " + Columns.USER2_ID + " TEXT, " + Columns.LOAD_TIME + " TIMESTAMP default (DATETIME('now', 'localtime')) " + ");"; return "CREATE TABLE " + createString; } public static String getDropSQL() { return "DROP TABLE " + TABLE_NAME; } public static String[] getIndexColumns() { return new String[] { Columns.USER1_ID, Columns.USER2_ID, Columns.LOAD_TIME }; } } /** * 热门话题表 记录每次查询得到的热词 * * @author phoenix * */ public static class TrendTable { public static final String TABLE_NAME = "t_trend"; public static class Columns { public static final String NAME = "name"; public static final String QUERY = "query"; public static final String URL = "url"; public static final String LOAD_TIME = "load_time"; } public static String getCreateSQL() { String createString = TABLE_NAME + "( " + Columns.NAME + " TEXT, " + Columns.QUERY + " TEXT, " + Columns.URL + " TEXT, " + Columns.LOAD_TIME + " TIMESTAMP default (DATETIME('now', 'localtime')) " + ");"; return "CREATE TABLE " + createString; } public static String getDropSQL() { return "DROP TABLE " + TABLE_NAME; } public static String[] getIndexColumns() { return new String[] { Columns.NAME, Columns.QUERY, Columns.URL, Columns.LOAD_TIME }; } } /** * 保存搜索表 QUERY_ID(这个ID在API删除保存搜索词时使用) * * @author phoenix * */ public static class SavedSearchTable { public static final String TABLE_NAME = "t_saved_search"; public static class Columns { public static final String QUERY_ID = "query_id"; public static final String QUERY = "query"; public static final String NAME = "name"; public static final String CREATED_AT = "created_at"; public static final String LOAD_TIME = "load_time"; } public static String getCreateSQL() { String createString = TABLE_NAME + "( " + Columns.QUERY_ID + " INT, " + Columns.QUERY + " TEXT, " + Columns.NAME + " TEXT, " + Columns.CREATED_AT + " INT, " + Columns.LOAD_TIME + " TIMESTAMP default (DATETIME('now', 'localtime')) " + ");"; return "CREATE TABLE " + createString; } public static String getDropSQL() { return "DROP TABLE " + TABLE_NAME; } public static String[] getIndexColumns() { return new String[] { Columns.QUERY_ID, Columns.QUERY, Columns.NAME, Columns.CREATED_AT, Columns.LOAD_TIME }; } } }
Java
package com.ch_linghu.fanfoudroid.db2; import java.util.ArrayList; import java.util.Arrays; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; /** * Wrapper of SQliteDatabse#query, OOP style. * * Usage: * ------------------------------------------------ * Query select = new Query(SQLiteDatabase); * * // SELECT * query.from("tableName", new String[] { "colName" }) * .where("id = ?", 123456) * .where("name = ?", "jack") * .orderBy("created_at DESC") * .limit(1); * Cursor cursor = query.select(); * * // DELETE * query.from("tableName") * .where("id = ?", 123455); * .delete(); * * // UPDATE * query.setTable("tableName") * .values(contentValues) * .update(); * * // INSERT * query.into("tableName") * .values(contentValues) * .insert(); * ------------------------------------------------ * * @see SQLiteDatabase#query(String, String[], String, String[], String, String, String, String) */ public class Query { private static final String TAG = "Query-Builder"; /** TEMP list for selctionArgs */ private ArrayList<String> binds = new ArrayList<String>(); private SQLiteDatabase mDb = null; private String mTable; private String[] mColumns; private String mSelection = null; private String[] mSelectionArgs = null; private String mGroupBy = null; private String mHaving = null; private String mOrderBy = null; private String mLimit = null; private ContentValues mValues = null; private String mNullColumnHack = null; public Query() { } /** * Construct * * @param db */ public Query(SQLiteDatabase db) { this.setDb(db); } /** * Query the given table, returning a Cursor over the result set. * * @param db SQLitedatabase * @return A Cursor object, which is positioned before the first entry, or NULL */ public Cursor select() { if ( preCheck() ) { buildQuery(); return mDb.query(mTable, mColumns, mSelection, mSelectionArgs, mGroupBy, mHaving, mOrderBy, mLimit); } else { //throw new SelectException("Cann't build the query . " + toString()); Log.e(TAG, "Cann't build the query " + toString()); return null; } } /** * @return the number of rows affected if a whereClause is passed in, 0 * otherwise. To remove all rows and get a count pass "1" as the * whereClause. */ public int delete() { if ( preCheck() ) { buildQuery(); return mDb.delete(mTable, mSelection, mSelectionArgs); } else { Log.e(TAG, "Cann't build the query " + toString()); return -1; } } /** * Set FROM * * @param table * The table name to compile the query against. * @param columns * A list of which columns to return. Passing null will return * all columns, which is discouraged to prevent reading data from * storage that isn't going to be used. * @return self * */ public Query from(String table, String[] columns) { mTable = table; mColumns = columns; return this; } /** * @see Query#from(String table, String[] columns) * @param table * @return self */ public Query from(String table) { return from(table, null); // all columns } /** * Add WHERE * * @param selection * A filter declaring which rows to return, formatted as an SQL * WHERE clause (excluding the WHERE itself). Passing null will * return all rows for the given table. * @param selectionArgs * You may include ?s in selection, which will be replaced by the * values from selectionArgs, in order that they appear in the * selection. The values will be bound as Strings. * @return self */ public Query where(String selection, String[] selectionArgs) { addSelection(selection); binds.addAll(Arrays.asList(selectionArgs)); return this; } /** * @see Query#where(String selection, String[] selectionArgs) */ public Query where(String selection, String selectionArg) { addSelection(selection); binds.add(selectionArg); return this; } /** * @see Query#where(String selection, String[] selectionArgs) */ public Query where(String selection) { addSelection(selection); return this; } /** * add selection part * * @param selection */ private void addSelection(String selection) { if (null == mSelection) { mSelection = selection; } else { mSelection += " AND " + selection; } } /** * set HAVING * * @param having * A filter declare which row groups to include in the cursor, if * row grouping is being used, formatted as an SQL HAVING clause * (excluding the HAVING itself). Passing null will cause all row * groups to be included, and is required when row grouping is * not being used. * @return self */ public Query having(String having) { this.mHaving = having; return this; } /** * Set GROUP BY * * @param groupBy * A filter declaring how to group rows, formatted as an SQL * GROUP BY clause (excluding the GROUP BY itself). Passing null * will cause the rows to not be grouped. * @return self */ public Query groupBy(String groupBy) { this.mGroupBy = groupBy; return this; } /** * Set ORDER BY * * @param orderBy * How to order the rows, formatted as an SQL ORDER BY clause * (excluding the ORDER BY itself). Passing null will use the * default sort order, which may be unordered. * @return self */ public Query orderBy(String orderBy) { this.mOrderBy = orderBy; return this; } /** * @param limit * Limits the number of rows returned by the query, formatted as * LIMIT clause. Passing null denotes no LIMIT clause. * @return self */ public Query limit(String limit) { this.mLimit = limit; return this; } /** * @see Query#limit(String limit) */ public Query limit(int limit) { return limit(limit + ""); } /** * Merge selectionArgs */ private void buildQuery() { mSelectionArgs = new String[binds.size()]; binds.toArray(mSelectionArgs); Log.v(TAG, toString()); } private boolean preCheck() { return (mTable != null && mDb != null); } // For Insert /** * set insert table * * @param table table name * @return self */ public Query into(String table) { return setTable(table); } /** * Set new values * * @param values new values * @return self */ public Query values(ContentValues values) { mValues = values; return this; } /** * Insert a row * * @return the row ID of the newly inserted row, or -1 if an error occurred */ public long insert() { return mDb.insert(mTable, mNullColumnHack, mValues); } // For update /** * Set target table * * @param table table name * @return self */ public Query setTable(String table) { mTable = table; return this; } /** * Update a row * * @return the number of rows affected, or -1 if an error occurred */ public int update() { if ( preCheck() ) { buildQuery(); return mDb.update(mTable, mValues, mSelection, mSelectionArgs); } else { Log.e(TAG, "Cann't build the query " + toString()); return -1; } } /** * Set back-end database * @param db */ public void setDb(SQLiteDatabase db) { if (null == this.mDb) { this.mDb = db; } } @Override public String toString() { return "Query [table=" + mTable + ", columns=" + Arrays.toString(mColumns) + ", selection=" + mSelection + ", selectionArgs=" + Arrays.toString(mSelectionArgs) + ", groupBy=" + mGroupBy + ", having=" + mHaving + ", orderBy=" + mOrderBy + "]"; } /** for debug */ public ContentValues getContentValues() { return mValues; } }
Java
package com.ch_linghu.fanfoudroid.http; import java.util.HashMap; import java.util.Map; public class HTMLEntity { public static String escape(String original) { StringBuffer buf = new StringBuffer(original); escape(buf); return buf.toString(); } public static void escape(StringBuffer original) { int index = 0; String escaped; while (index < original.length()) { escaped = entityEscapeMap.get(original.substring(index, index + 1)); if (null != escaped) { original.replace(index, index + 1, escaped); index += escaped.length(); } else { index++; } } } public static String unescape(String original) { StringBuffer buf = new StringBuffer(original); unescape(buf); return buf.toString(); } public static void unescape(StringBuffer original) { int index = 0; int semicolonIndex = 0; String escaped; String entity; while (index < original.length()) { index = original.indexOf("&", index); if (-1 == index) { break; } semicolonIndex = original.indexOf(";", index); if (-1 != semicolonIndex && 10 > (semicolonIndex - index)) { escaped = original.substring(index, semicolonIndex + 1); entity = escapeEntityMap.get(escaped); if (null != entity) { original.replace(index, semicolonIndex + 1, entity); } index++; } else { break; } } } private static Map<String, String> entityEscapeMap = new HashMap<String, String>(); private static Map<String, String> escapeEntityMap = new HashMap<String, String>(); static { String[][] entities = {{"&nbsp;", "&#160;"/* no-break space = non-breaking space */, "\u00A0"} , {"&iexcl;", "&#161;"/* inverted exclamation mark */, "\u00A1"} , {"&cent;", "&#162;"/* cent sign */, "\u00A2"} , {"&pound;", "&#163;"/* pound sign */, "\u00A3"} , {"&curren;", "&#164;"/* currency sign */, "\u00A4"} , {"&yen;", "&#165;"/* yen sign = yuan sign */, "\u00A5"} , {"&brvbar;", "&#166;"/* broken bar = broken vertical bar */, "\u00A6"} , {"&sect;", "&#167;"/* section sign */, "\u00A7"} , {"&uml;", "&#168;"/* diaeresis = spacing diaeresis */, "\u00A8"} , {"&copy;", "&#169;"/* copyright sign */, "\u00A9"} , {"&ordf;", "&#170;"/* feminine ordinal indicator */, "\u00AA"} , {"&laquo;", "&#171;"/* left-pointing double angle quotation mark = left pointing guillemet */, "\u00AB"} , {"&not;", "&#172;"/* not sign = discretionary hyphen */, "\u00AC"} , {"&shy;", "&#173;"/* soft hyphen = discretionary hyphen */, "\u00AD"} , {"&reg;", "&#174;"/* registered sign = registered trade mark sign */, "\u00AE"} , {"&macr;", "&#175;"/* macron = spacing macron = overline = APL overbar */, "\u00AF"} , {"&deg;", "&#176;"/* degree sign */, "\u00B0"} , {"&plusmn;", "&#177;"/* plus-minus sign = plus-or-minus sign */, "\u00B1"} , {"&sup2;", "&#178;"/* superscript two = superscript digit two = squared */, "\u00B2"} , {"&sup3;", "&#179;"/* superscript three = superscript digit three = cubed */, "\u00B3"} , {"&acute;", "&#180;"/* acute accent = spacing acute */, "\u00B4"} , {"&micro;", "&#181;"/* micro sign */, "\u00B5"} , {"&para;", "&#182;"/* pilcrow sign = paragraph sign */, "\u00B6"} , {"&middot;", "&#183;"/* middle dot = Georgian comma = Greek middle dot */, "\u00B7"} , {"&cedil;", "&#184;"/* cedilla = spacing cedilla */, "\u00B8"} , {"&sup1;", "&#185;"/* superscript one = superscript digit one */, "\u00B9"} , {"&ordm;", "&#186;"/* masculine ordinal indicator */, "\u00BA"} , {"&raquo;", "&#187;"/* right-pointing double angle quotation mark = right pointing guillemet */, "\u00BB"} , {"&frac14;", "&#188;"/* vulgar fraction one quarter = fraction one quarter */, "\u00BC"} , {"&frac12;", "&#189;"/* vulgar fraction one half = fraction one half */, "\u00BD"} , {"&frac34;", "&#190;"/* vulgar fraction three quarters = fraction three quarters */, "\u00BE"} , {"&iquest;", "&#191;"/* inverted question mark = turned question mark */, "\u00BF"} , {"&Agrave;", "&#192;"/* latin capital letter A with grave = latin capital letter A grave */, "\u00C0"} , {"&Aacute;", "&#193;"/* latin capital letter A with acute */, "\u00C1"} , {"&Acirc;", "&#194;"/* latin capital letter A with circumflex */, "\u00C2"} , {"&Atilde;", "&#195;"/* latin capital letter A with tilde */, "\u00C3"} , {"&Auml;", "&#196;"/* latin capital letter A with diaeresis */, "\u00C4"} , {"&Aring;", "&#197;"/* latin capital letter A with ring above = latin capital letter A ring */, "\u00C5"} , {"&AElig;", "&#198;"/* latin capital letter AE = latin capital ligature AE */, "\u00C6"} , {"&Ccedil;", "&#199;"/* latin capital letter C with cedilla */, "\u00C7"} , {"&Egrave;", "&#200;"/* latin capital letter E with grave */, "\u00C8"} , {"&Eacute;", "&#201;"/* latin capital letter E with acute */, "\u00C9"} , {"&Ecirc;", "&#202;"/* latin capital letter E with circumflex */, "\u00CA"} , {"&Euml;", "&#203;"/* latin capital letter E with diaeresis */, "\u00CB"} , {"&Igrave;", "&#204;"/* latin capital letter I with grave */, "\u00CC"} , {"&Iacute;", "&#205;"/* latin capital letter I with acute */, "\u00CD"} , {"&Icirc;", "&#206;"/* latin capital letter I with circumflex */, "\u00CE"} , {"&Iuml;", "&#207;"/* latin capital letter I with diaeresis */, "\u00CF"} , {"&ETH;", "&#208;"/* latin capital letter ETH */, "\u00D0"} , {"&Ntilde;", "&#209;"/* latin capital letter N with tilde */, "\u00D1"} , {"&Ograve;", "&#210;"/* latin capital letter O with grave */, "\u00D2"} , {"&Oacute;", "&#211;"/* latin capital letter O with acute */, "\u00D3"} , {"&Ocirc;", "&#212;"/* latin capital letter O with circumflex */, "\u00D4"} , {"&Otilde;", "&#213;"/* latin capital letter O with tilde */, "\u00D5"} , {"&Ouml;", "&#214;"/* latin capital letter O with diaeresis */, "\u00D6"} , {"&times;", "&#215;"/* multiplication sign */, "\u00D7"} , {"&Oslash;", "&#216;"/* latin capital letter O with stroke = latin capital letter O slash */, "\u00D8"} , {"&Ugrave;", "&#217;"/* latin capital letter U with grave */, "\u00D9"} , {"&Uacute;", "&#218;"/* latin capital letter U with acute */, "\u00DA"} , {"&Ucirc;", "&#219;"/* latin capital letter U with circumflex */, "\u00DB"} , {"&Uuml;", "&#220;"/* latin capital letter U with diaeresis */, "\u00DC"} , {"&Yacute;", "&#221;"/* latin capital letter Y with acute */, "\u00DD"} , {"&THORN;", "&#222;"/* latin capital letter THORN */, "\u00DE"} , {"&szlig;", "&#223;"/* latin small letter sharp s = ess-zed */, "\u00DF"} , {"&agrave;", "&#224;"/* latin small letter a with grave = latin small letter a grave */, "\u00E0"} , {"&aacute;", "&#225;"/* latin small letter a with acute */, "\u00E1"} , {"&acirc;", "&#226;"/* latin small letter a with circumflex */, "\u00E2"} , {"&atilde;", "&#227;"/* latin small letter a with tilde */, "\u00E3"} , {"&auml;", "&#228;"/* latin small letter a with diaeresis */, "\u00E4"} , {"&aring;", "&#229;"/* latin small letter a with ring above = latin small letter a ring */, "\u00E5"} , {"&aelig;", "&#230;"/* latin small letter ae = latin small ligature ae */, "\u00E6"} , {"&ccedil;", "&#231;"/* latin small letter c with cedilla */, "\u00E7"} , {"&egrave;", "&#232;"/* latin small letter e with grave */, "\u00E8"} , {"&eacute;", "&#233;"/* latin small letter e with acute */, "\u00E9"} , {"&ecirc;", "&#234;"/* latin small letter e with circumflex */, "\u00EA"} , {"&euml;", "&#235;"/* latin small letter e with diaeresis */, "\u00EB"} , {"&igrave;", "&#236;"/* latin small letter i with grave */, "\u00EC"} , {"&iacute;", "&#237;"/* latin small letter i with acute */, "\u00ED"} , {"&icirc;", "&#238;"/* latin small letter i with circumflex */, "\u00EE"} , {"&iuml;", "&#239;"/* latin small letter i with diaeresis */, "\u00EF"} , {"&eth;", "&#240;"/* latin small letter eth */, "\u00F0"} , {"&ntilde;", "&#241;"/* latin small letter n with tilde */, "\u00F1"} , {"&ograve;", "&#242;"/* latin small letter o with grave */, "\u00F2"} , {"&oacute;", "&#243;"/* latin small letter o with acute */, "\u00F3"} , {"&ocirc;", "&#244;"/* latin small letter o with circumflex */, "\u00F4"} , {"&otilde;", "&#245;"/* latin small letter o with tilde */, "\u00F5"} , {"&ouml;", "&#246;"/* latin small letter o with diaeresis */, "\u00F6"} , {"&divide;", "&#247;"/* division sign */, "\u00F7"} , {"&oslash;", "&#248;"/* latin small letter o with stroke = latin small letter o slash */, "\u00F8"} , {"&ugrave;", "&#249;"/* latin small letter u with grave */, "\u00F9"} , {"&uacute;", "&#250;"/* latin small letter u with acute */, "\u00FA"} , {"&ucirc;", "&#251;"/* latin small letter u with circumflex */, "\u00FB"} , {"&uuml;", "&#252;"/* latin small letter u with diaeresis */, "\u00FC"} , {"&yacute;", "&#253;"/* latin small letter y with acute */, "\u00FD"} , {"&thorn;", "&#254;"/* latin small letter thorn with */, "\u00FE"} , {"&yuml;", "&#255;"/* latin small letter y with diaeresis */, "\u00FF"} , {"&fnof;", "&#402;"/* latin small f with hook = function = florin */, "\u0192"} /* Greek */ , {"&Alpha;", "&#913;"/* greek capital letter alpha */, "\u0391"} , {"&Beta;", "&#914;"/* greek capital letter beta */, "\u0392"} , {"&Gamma;", "&#915;"/* greek capital letter gamma */, "\u0393"} , {"&Delta;", "&#916;"/* greek capital letter delta */, "\u0394"} , {"&Epsilon;", "&#917;"/* greek capital letter epsilon */, "\u0395"} , {"&Zeta;", "&#918;"/* greek capital letter zeta */, "\u0396"} , {"&Eta;", "&#919;"/* greek capital letter eta */, "\u0397"} , {"&Theta;", "&#920;"/* greek capital letter theta */, "\u0398"} , {"&Iota;", "&#921;"/* greek capital letter iota */, "\u0399"} , {"&Kappa;", "&#922;"/* greek capital letter kappa */, "\u039A"} , {"&Lambda;", "&#923;"/* greek capital letter lambda */, "\u039B"} , {"&Mu;", "&#924;"/* greek capital letter mu */, "\u039C"} , {"&Nu;", "&#925;"/* greek capital letter nu */, "\u039D"} , {"&Xi;", "&#926;"/* greek capital letter xi */, "\u039E"} , {"&Omicron;", "&#927;"/* greek capital letter omicron */, "\u039F"} , {"&Pi;", "&#928;"/* greek capital letter pi */, "\u03A0"} , {"&Rho;", "&#929;"/* greek capital letter rho */, "\u03A1"} /* there is no Sigmaf and no \u03A2 */ , {"&Sigma;", "&#931;"/* greek capital letter sigma */, "\u03A3"} , {"&Tau;", "&#932;"/* greek capital letter tau */, "\u03A4"} , {"&Upsilon;", "&#933;"/* greek capital letter upsilon */, "\u03A5"} , {"&Phi;", "&#934;"/* greek capital letter phi */, "\u03A6"} , {"&Chi;", "&#935;"/* greek capital letter chi */, "\u03A7"} , {"&Psi;", "&#936;"/* greek capital letter psi */, "\u03A8"} , {"&Omega;", "&#937;"/* greek capital letter omega */, "\u03A9"} , {"&alpha;", "&#945;"/* greek small letter alpha */, "\u03B1"} , {"&beta;", "&#946;"/* greek small letter beta */, "\u03B2"} , {"&gamma;", "&#947;"/* greek small letter gamma */, "\u03B3"} , {"&delta;", "&#948;"/* greek small letter delta */, "\u03B4"} , {"&epsilon;", "&#949;"/* greek small letter epsilon */, "\u03B5"} , {"&zeta;", "&#950;"/* greek small letter zeta */, "\u03B6"} , {"&eta;", "&#951;"/* greek small letter eta */, "\u03B7"} , {"&theta;", "&#952;"/* greek small letter theta */, "\u03B8"} , {"&iota;", "&#953;"/* greek small letter iota */, "\u03B9"} , {"&kappa;", "&#954;"/* greek small letter kappa */, "\u03BA"} , {"&lambda;", "&#955;"/* greek small letter lambda */, "\u03BB"} , {"&mu;", "&#956;"/* greek small letter mu */, "\u03BC"} , {"&nu;", "&#957;"/* greek small letter nu */, "\u03BD"} , {"&xi;", "&#958;"/* greek small letter xi */, "\u03BE"} , {"&omicron;", "&#959;"/* greek small letter omicron */, "\u03BF"} , {"&pi;", "&#960;"/* greek small letter pi */, "\u03C0"} , {"&rho;", "&#961;"/* greek small letter rho */, "\u03C1"} , {"&sigmaf;", "&#962;"/* greek small letter final sigma */, "\u03C2"} , {"&sigma;", "&#963;"/* greek small letter sigma */, "\u03C3"} , {"&tau;", "&#964;"/* greek small letter tau */, "\u03C4"} , {"&upsilon;", "&#965;"/* greek small letter upsilon */, "\u03C5"} , {"&phi;", "&#966;"/* greek small letter phi */, "\u03C6"} , {"&chi;", "&#967;"/* greek small letter chi */, "\u03C7"} , {"&psi;", "&#968;"/* greek small letter psi */, "\u03C8"} , {"&omega;", "&#969;"/* greek small letter omega */, "\u03C9"} , {"&thetasym;", "&#977;"/* greek small letter theta symbol */, "\u03D1"} , {"&upsih;", "&#978;"/* greek upsilon with hook symbol */, "\u03D2"} , {"&piv;", "&#982;"/* greek pi symbol */, "\u03D6"} /* General Punctuation */ , {"&bull;", "&#8226;"/* bullet = black small circle */, "\u2022"} /* bullet is NOT the same as bullet operator ,"\u2219*/ , {"&hellip;", "&#8230;"/* horizontal ellipsis = three dot leader */, "\u2026"} , {"&prime;", "&#8242;"/* prime = minutes = feet */, "\u2032"} , {"&Prime;", "&#8243;"/* double prime = seconds = inches */, "\u2033"} , {"&oline;", "&#8254;"/* overline = spacing overscore */, "\u203E"} , {"&frasl;", "&#8260;"/* fraction slash */, "\u2044"} /* Letterlike Symbols */ , {"&weierp;", "&#8472;"/* script capital P = power set = Weierstrass p */, "\u2118"} , {"&image;", "&#8465;"/* blackletter capital I = imaginary part */, "\u2111"} , {"&real;", "&#8476;"/* blackletter capital R = real part symbol */, "\u211C"} , {"&trade;", "&#8482;"/* trade mark sign */, "\u2122"} , {"&alefsym;", "&#8501;"/* alef symbol = first transfinite cardinal */, "\u2135"} /* alef symbol is NOT the same as hebrew letter alef ,"\u05D0"}*/ /* Arrows */ , {"&larr;", "&#8592;"/* leftwards arrow */, "\u2190"} , {"&uarr;", "&#8593;"/* upwards arrow */, "\u2191"} , {"&rarr;", "&#8594;"/* rightwards arrow */, "\u2192"} , {"&darr;", "&#8595;"/* downwards arrow */, "\u2193"} , {"&harr;", "&#8596;"/* left right arrow */, "\u2194"} , {"&crarr;", "&#8629;"/* downwards arrow with corner leftwards = carriage return */, "\u21B5"} , {"&lArr;", "&#8656;"/* leftwards double arrow */, "\u21D0"} /* Unicode does not say that lArr is the same as the 'is implied by' arrow but also does not have any other character for that function. So ? lArr can be used for 'is implied by' as ISOtech suggests */ , {"&uArr;", "&#8657;"/* upwards double arrow */, "\u21D1"} , {"&rArr;", "&#8658;"/* rightwards double arrow */, "\u21D2"} /* Unicode does not say this is the 'implies' character but does not have another character with this function so ? rArr can be used for 'implies' as ISOtech suggests */ , {"&dArr;", "&#8659;"/* downwards double arrow */, "\u21D3"} , {"&hArr;", "&#8660;"/* left right double arrow */, "\u21D4"} /* Mathematical Operators */ , {"&forall;", "&#8704;"/* for all */, "\u2200"} , {"&part;", "&#8706;"/* partial differential */, "\u2202"} , {"&exist;", "&#8707;"/* there exists */, "\u2203"} , {"&empty;", "&#8709;"/* empty set = null set = diameter */, "\u2205"} , {"&nabla;", "&#8711;"/* nabla = backward difference */, "\u2207"} , {"&isin;", "&#8712;"/* element of */, "\u2208"} , {"&notin;", "&#8713;"/* not an element of */, "\u2209"} , {"&ni;", "&#8715;"/* contains as member */, "\u220B"} /* should there be a more memorable name than 'ni'? */ , {"&prod;", "&#8719;"/* n-ary product = product sign */, "\u220F"} /* prod is NOT the same character as ,"\u03A0"}*/ , {"&sum;", "&#8721;"/* n-ary sumation */, "\u2211"} /* sum is NOT the same character as ,"\u03A3"}*/ , {"&minus;", "&#8722;"/* minus sign */, "\u2212"} , {"&lowast;", "&#8727;"/* asterisk operator */, "\u2217"} , {"&radic;", "&#8730;"/* square root = radical sign */, "\u221A"} , {"&prop;", "&#8733;"/* proportional to */, "\u221D"} , {"&infin;", "&#8734;"/* infinity */, "\u221E"} , {"&ang;", "&#8736;"/* angle */, "\u2220"} , {"&and;", "&#8743;"/* logical and = wedge */, "\u2227"} , {"&or;", "&#8744;"/* logical or = vee */, "\u2228"} , {"&cap;", "&#8745;"/* intersection = cap */, "\u2229"} , {"&cup;", "&#8746;"/* union = cup */, "\u222A"} , {"&int;", "&#8747;"/* integral */, "\u222B"} , {"&there4;", "&#8756;"/* therefore */, "\u2234"} , {"&sim;", "&#8764;"/* tilde operator = varies with = similar to */, "\u223C"} /* tilde operator is NOT the same character as the tilde ,"\u007E"}*/ , {"&cong;", "&#8773;"/* approximately equal to */, "\u2245"} , {"&asymp;", "&#8776;"/* almost equal to = asymptotic to */, "\u2248"} , {"&ne;", "&#8800;"/* not equal to */, "\u2260"} , {"&equiv;", "&#8801;"/* identical to */, "\u2261"} , {"&le;", "&#8804;"/* less-than or equal to */, "\u2264"} , {"&ge;", "&#8805;"/* greater-than or equal to */, "\u2265"} , {"&sub;", "&#8834;"/* subset of */, "\u2282"} , {"&sup;", "&#8835;"/* superset of */, "\u2283"} /* note that nsup 'not a superset of ,"\u2283"}*/ , {"&sube;", "&#8838;"/* subset of or equal to */, "\u2286"} , {"&supe;", "&#8839;"/* superset of or equal to */, "\u2287"} , {"&oplus;", "&#8853;"/* circled plus = direct sum */, "\u2295"} , {"&otimes;", "&#8855;"/* circled times = vector product */, "\u2297"} , {"&perp;", "&#8869;"/* up tack = orthogonal to = perpendicular */, "\u22A5"} , {"&sdot;", "&#8901;"/* dot operator */, "\u22C5"} /* dot operator is NOT the same character as ,"\u00B7"} /* Miscellaneous Technical */ , {"&lceil;", "&#8968;"/* left ceiling = apl upstile */, "\u2308"} , {"&rceil;", "&#8969;"/* right ceiling */, "\u2309"} , {"&lfloor;", "&#8970;"/* left floor = apl downstile */, "\u230A"} , {"&rfloor;", "&#8971;"/* right floor */, "\u230B"} , {"&lang;", "&#9001;"/* left-pointing angle bracket = bra */, "\u2329"} /* lang is NOT the same character as ,"\u003C"}*/ , {"&rang;", "&#9002;"/* right-pointing angle bracket = ket */, "\u232A"} /* rang is NOT the same character as ,"\u003E"}*/ /* Geometric Shapes */ , {"&loz;", "&#9674;"/* lozenge */, "\u25CA"} /* Miscellaneous Symbols */ , {"&spades;", "&#9824;"/* black spade suit */, "\u2660"} /* black here seems to mean filled as opposed to hollow */ , {"&clubs;", "&#9827;"/* black club suit = shamrock */, "\u2663"} , {"&hearts;", "&#9829;"/* black heart suit = valentine */, "\u2665"} , {"&diams;", "&#9830;"/* black diamond suit */, "\u2666"} , {"&quot;", "&#34;" /* quotation mark = APL quote */, "\""} , {"&amp;", "&#38;" /* ampersand */, "\u0026"} , {"&lt;", "&#60;" /* less-than sign */, "\u003C"} , {"&gt;", "&#62;" /* greater-than sign */, "\u003E"} /* Latin Extended-A */ , {"&OElig;", "&#338;" /* latin capital ligature OE */, "\u0152"} , {"&oelig;", "&#339;" /* latin small ligature oe */, "\u0153"} /* ligature is a misnomer this is a separate character in some languages */ , {"&Scaron;", "&#352;" /* latin capital letter S with caron */, "\u0160"} , {"&scaron;", "&#353;" /* latin small letter s with caron */, "\u0161"} , {"&Yuml;", "&#376;" /* latin capital letter Y with diaeresis */, "\u0178"} /* Spacing Modifier Letters */ , {"&circ;", "&#710;" /* modifier letter circumflex accent */, "\u02C6"} , {"&tilde;", "&#732;" /* small tilde */, "\u02DC"} /* General Punctuation */ , {"&ensp;", "&#8194;"/* en space */, "\u2002"} , {"&emsp;", "&#8195;"/* em space */, "\u2003"} , {"&thinsp;", "&#8201;"/* thin space */, "\u2009"} , {"&zwnj;", "&#8204;"/* zero width non-joiner */, "\u200C"} , {"&zwj;", "&#8205;"/* zero width joiner */, "\u200D"} , {"&lrm;", "&#8206;"/* left-to-right mark */, "\u200E"} , {"&rlm;", "&#8207;"/* right-to-left mark */, "\u200F"} , {"&ndash;", "&#8211;"/* en dash */, "\u2013"} , {"&mdash;", "&#8212;"/* em dash */, "\u2014"} , {"&lsquo;", "&#8216;"/* left single quotation mark */, "\u2018"} , {"&rsquo;", "&#8217;"/* right single quotation mark */, "\u2019"} , {"&sbquo;", "&#8218;"/* single low-9 quotation mark */, "\u201A"} , {"&ldquo;", "&#8220;"/* left double quotation mark */, "\u201C"} , {"&rdquo;", "&#8221;"/* right double quotation mark */, "\u201D"} , {"&bdquo;", "&#8222;"/* double low-9 quotation mark */, "\u201E"} , {"&dagger;", "&#8224;"/* dagger */, "\u2020"} , {"&Dagger;", "&#8225;"/* double dagger */, "\u2021"} , {"&permil;", "&#8240;"/* per mille sign */, "\u2030"} , {"&lsaquo;", "&#8249;"/* single left-pointing angle quotation mark */, "\u2039"} /* lsaquo is proposed but not yet ISO standardized */ , {"&rsaquo;", "&#8250;"/* single right-pointing angle quotation mark */, "\u203A"} /* rsaquo is proposed but not yet ISO standardized */ , {"&euro;", "&#8364;" /* euro sign */, "\u20AC"}}; for (String[] entity : entities) { entityEscapeMap.put(entity[2], entity[0]); escapeEntityMap.put(entity[0], entity[2]); escapeEntityMap.put(entity[1], entity[2]); } } }
Java
package com.ch_linghu.fanfoudroid.http; /** * HTTP StatusCode is not 200 */ public class HttpException extends Exception { private int statusCode = -1; public HttpException(String msg) { super(msg); } public HttpException(Exception cause) { super(cause); } public HttpException(String msg, int statusCode) { super(msg); this.statusCode = statusCode; } public HttpException(String msg, Exception cause) { super(msg, cause); } public HttpException(String msg, Exception cause, int statusCode) { super(msg, cause); this.statusCode = statusCode; } public int getStatusCode() { return this.statusCode; } }
Java
package com.ch_linghu.fanfoudroid.http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.util.CharArrayBuffer; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import android.util.Log; import com.ch_linghu.fanfoudroid.util.DebugTimer; public class Response { private final HttpResponse mResponse; private boolean mStreamConsumed = false; public Response(HttpResponse res) { mResponse = res; } /** * Convert Response to inputStream * * @return InputStream or null * @throws ResponseException */ public InputStream asStream() throws ResponseException { try { final HttpEntity entity = mResponse.getEntity(); if (entity != null) { return entity.getContent(); } } catch (IllegalStateException e) { throw new ResponseException(e.getMessage(), e); } catch (IOException e) { throw new ResponseException(e.getMessage(), e); } return null; } /** * @deprecated use entity.getContent(); * @param entity * @return * @throws ResponseException */ private InputStream asStream(HttpEntity entity) throws ResponseException { if (null == entity) { return null; } InputStream is = null; try { is = entity.getContent(); } catch (IllegalStateException e) { throw new ResponseException(e.getMessage(), e); } catch (IOException e) { throw new ResponseException(e.getMessage(), e); } //mResponse = null; return is; } /** * Convert Response to Context String * * @return response context string or null * @throws ResponseException */ public String asString() throws ResponseException { try { return entityToString(mResponse.getEntity()); } catch (IOException e) { throw new ResponseException(e.getMessage(), e); } } /** * EntityUtils.toString(entity, "UTF-8"); * * @param entity * @return * @throws IOException * @throws ResponseException */ private String entityToString(final HttpEntity entity) throws IOException, ResponseException { DebugTimer.betweenStart("AS STRING"); if (null == entity) { throw new IllegalArgumentException("HTTP entity may not be null"); } InputStream instream = entity.getContent(); //InputStream instream = asStream(entity); if (instream == null) { return ""; } if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); } int i = (int) entity.getContentLength(); if (i < 0) { i = 4096; } Log.i("LDS", i + " content length"); Reader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8")); CharArrayBuffer buffer = new CharArrayBuffer(i); try { char[] tmp = new char[1024]; int l; while ((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); } } finally { reader.close(); } DebugTimer.betweenEnd("AS STRING"); return buffer.toString(); } /** * @deprecated use entityToString() * @param in * @return * @throws ResponseException */ private String inputStreamToString(final InputStream in) throws IOException { if (null == in) { return null; } BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); StringBuffer buf = new StringBuffer(); try { char[] buffer = new char[1024]; while ((reader.read(buffer)) != -1) { buf.append(buffer); } return buf.toString(); } finally { if (reader != null) { reader.close(); setStreamConsumed(true); } } } public JSONObject asJSONObject() throws ResponseException { try { return new JSONObject(asString()); } catch (JSONException jsone) { throw new ResponseException(jsone.getMessage() + ":" + asString(), jsone); } } public JSONArray asJSONArray() throws ResponseException { try { return new JSONArray(asString()); } catch (Exception jsone) { throw new ResponseException(jsone.getMessage(), jsone); } } private void setStreamConsumed(boolean mStreamConsumed) { this.mStreamConsumed = mStreamConsumed; } public boolean isStreamConsumed() { return mStreamConsumed; } /** * @deprecated * @return */ public Document asDocument() { // TODO Auto-generated method stub return null; } private static Pattern escaped = Pattern.compile("&#([0-9]{3,5});"); /** * Unescape UTF-8 escaped characters to string. * @author pengjianq...@gmail.com * * @param original The string to be unescaped. * @return The unescaped string */ public static String unescape(String original) { Matcher mm = escaped.matcher(original); StringBuffer unescaped = new StringBuffer(); while (mm.find()) { mm.appendReplacement(unescaped, Character.toString( (char) Integer.parseInt(mm.group(1), 10))); } mm.appendTail(unescaped); return unescaped.toString(); } }
Java