code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import android.graphics.Canvas; import com.android.spritemethodtest.CanvasSurfaceView.Renderer; /** * An extremely simple renderer based on the CanvasSurfaceView drawing * framework. Simply draws a list of sprites to a canvas every frame. */ public class SimpleCanvasRenderer implements Renderer { private CanvasSprite[] mSprites; public void setSprites(CanvasSprite[] sprites) { mSprites = sprites; } public void drawFrame(Canvas canvas) { if (mSprites != null) { for (int x = 0; x < mSprites.length; x++) { mSprites[x].draw(canvas); } } } public void sizeChanged(int width, int height) { } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // This file was lifted from the APIDemos sample. See: // http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/index.html package com.android.spritemethodtest; import java.util.concurrent.Semaphore; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; /** * An implementation of SurfaceView that uses the dedicated surface for * displaying an OpenGL animation. This allows the animation to run in a * separate thread, without requiring that it be driven by the update mechanism * of the view hierarchy. * * The application-specific rendering code is delegated to a GLView.Renderer * instance. */ public class GLSurfaceView extends SurfaceView implements SurfaceHolder.Callback { public GLSurfaceView(Context context) { super(context); init(); } public GLSurfaceView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU); } public SurfaceHolder getSurfaceHolder() { return mHolder; } public void setGLWrapper(GLWrapper glWrapper) { mGLWrapper = glWrapper; } public void setRenderer(Renderer renderer) { mGLThread = new GLThread(renderer); mGLThread.start(); } public void surfaceCreated(SurfaceHolder holder) { mGLThread.surfaceCreated(); } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return mGLThread.surfaceDestroyed(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Surface size or format has changed. This should not happen in this // example. mGLThread.onWindowResize(w, h); } /** * Inform the view that the activity is paused. */ public void onPause() { mGLThread.onPause(); } /** * Inform the view that the activity is resumed. */ public void onResume() { mGLThread.onResume(); } /** * Inform the view that the window focus has changed. */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mGLThread.onWindowFocusChanged(hasFocus); } /** * Set an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void setEvent(Runnable r) { mGLThread.setEvent(r); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mGLThread.requestExitAndWait(); } // ---------------------------------------------------------------------- public interface GLWrapper { GL wrap(GL gl); } // ---------------------------------------------------------------------- /** * A generic renderer interface. */ public interface Renderer { /** * @return the EGL configuration specification desired by the renderer. */ int[] getConfigSpec(); /** * Surface created. * Called when the surface is created. Called when the application * starts, and whenever the GPU is reinitialized. This will * typically happen when the device awakes after going to sleep. * Set your textures here. */ void surfaceCreated(GL10 gl); /** * Called when the rendering thread is about to shut down. This is a * good place to release OpenGL ES resources (textures, buffers, etc). * @param gl */ void shutdown(GL10 gl); /** * Surface changed size. * Called after the surface is created and whenever * the OpenGL ES surface size changes. Set your viewport here. * @param gl * @param width * @param height */ void sizeChanged(GL10 gl, int width, int height); /** * Draw the current frame. * @param gl */ void drawFrame(GL10 gl); } /** * An EGL helper class. */ private class EglHelper { public EglHelper() { } /** * Initialize EGL for a given configuration spec. * @param configSpec */ public void start(int[] configSpec){ /* * Get an EGL instance */ mEgl = (EGL10) EGLContext.getEGL(); /* * Get to the default display. */ mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); /* * We can now initialize EGL for that display */ int[] version = new int[2]; mEgl.eglInitialize(mEglDisplay, version); EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1, num_config); mEglConfig = configs[0]; /* * Create an OpenGL ES context. This must be done only once, an * OpenGL context is a somewhat heavy object. */ mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig, EGL10.EGL_NO_CONTEXT, null); mEglSurface = null; } /* * Create and return an OpenGL surface */ public GL createSurface(SurfaceHolder holder) { /* * The window size has changed, so we need to create a new * surface. */ if (mEglSurface != null) { /* * Unbind and destroy the old EGL surface, if * there is one. */ mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); } /* * Create an EGL surface we can render into. */ mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, holder, null); /* * Before we can issue GL commands, we need to make sure * the context is current and bound to a surface. */ mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext); GL gl = mEglContext.getGL(); if (mGLWrapper != null) { gl = mGLWrapper.wrap(gl); } return gl; } /** * Display the current render surface. * @return false if the context has been lost. */ public boolean swap() { mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); /* * Always check for EGL_CONTEXT_LOST, which means the context * and all associated data were lost (For instance because * the device went to sleep). We need to sleep until we * get a new surface. */ return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; } public void finish() { if (mEglSurface != null) { mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); mEglSurface = null; } if (mEglContext != null) { mEgl.eglDestroyContext(mEglDisplay, mEglContext); mEglContext = null; } if (mEglDisplay != null) { mEgl.eglTerminate(mEglDisplay); mEglDisplay = null; } } EGL10 mEgl; EGLDisplay mEglDisplay; EGLSurface mEglSurface; EGLConfig mEglConfig; EGLContext mEglContext; } /** * A generic GL Thread. Takes care of initializing EGL and GL. Delegates * to a Renderer instance to do the actual drawing. * */ class GLThread extends Thread { GLThread(Renderer renderer) { super(); mDone = false; mWidth = 0; mHeight = 0; mRenderer = renderer; setName("GLThread"); } @Override public void run() { /* * When the android framework launches a second instance of * an activity, the new instance's onCreate() method may be * called before the first instance returns from onDestroy(). * * This semaphore ensures that only one instance at a time * accesses EGL. */ try { try { sEglSemaphore.acquire(); } catch (InterruptedException e) { return; } guardedRun(); } catch (InterruptedException e) { // fall thru and exit normally } finally { sEglSemaphore.release(); } } private void guardedRun() throws InterruptedException { mEglHelper = new EglHelper(); /* * Specify a configuration for our opengl session * and grab the first configuration that matches is */ int[] configSpec = mRenderer.getConfigSpec(); mEglHelper.start(configSpec); GL10 gl = null; boolean tellRendererSurfaceCreated = true; boolean tellRendererSurfaceChanged = true; /* * This is our main activity thread's loop, we go until * asked to quit. */ while (!mDone) { ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_FRAME); /* * Update the asynchronous state (window size) */ int w, h; boolean changed; boolean needStart = false; synchronized (this) { if (mEvent != null) { ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_SIM); mEvent.run(); ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_SIM); } if (mPaused) { mEglHelper.finish(); needStart = true; } if(needToWait()) { while (needToWait()) { wait(); } } if (mDone) { break; } changed = mSizeChanged; w = mWidth; h = mHeight; mSizeChanged = false; } if (needStart) { mEglHelper.start(configSpec); tellRendererSurfaceCreated = true; changed = true; } if (changed) { gl = (GL10) mEglHelper.createSurface(mHolder); tellRendererSurfaceChanged = true; } if (tellRendererSurfaceCreated) { mRenderer.surfaceCreated(gl); tellRendererSurfaceCreated = false; } if (tellRendererSurfaceChanged) { mRenderer.sizeChanged(gl, w, h); tellRendererSurfaceChanged = false; } if ((w > 0) && (h > 0)) { ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_DRAW); /* draw a frame here */ mRenderer.drawFrame(gl); ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_DRAW); /* * Once we're done with GL, we need to call swapBuffers() * to instruct the system to display the rendered frame */ ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_PAGE_FLIP); mEglHelper.swap(); ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_PAGE_FLIP); } ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_FRAME); ProfileRecorder.sSingleton.endFrame(); } /* * clean-up everything... */ if (gl != null) { mRenderer.shutdown(gl); } mEglHelper.finish(); } private boolean needToWait() { return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost) && (! mDone); } public void surfaceCreated() { synchronized(this) { mHasSurface = true; mContextLost = false; notify(); } } public void surfaceDestroyed() { synchronized(this) { mHasSurface = false; notify(); } } public void onPause() { synchronized (this) { mPaused = true; } } public void onResume() { synchronized (this) { mPaused = false; notify(); } } public void onWindowFocusChanged(boolean hasFocus) { synchronized (this) { mHasFocus = hasFocus; if (mHasFocus == true) { notify(); } } } public void onWindowResize(int w, int h) { synchronized (this) { mWidth = w; mHeight = h; mSizeChanged = true; } } public void requestExitAndWait() { // don't call this from GLThread thread or it is a guaranteed // deadlock! synchronized(this) { mDone = true; notify(); } try { join(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void setEvent(Runnable r) { synchronized(this) { mEvent = r; } } public void clearEvent() { synchronized(this) { mEvent = null; } } private boolean mDone; private boolean mPaused; private boolean mHasFocus; private boolean mHasSurface; private boolean mContextLost; private int mWidth; private int mHeight; private Renderer mRenderer; private Runnable mEvent; private EglHelper mEglHelper; } private static final Semaphore sEglSemaphore = new Semaphore(1); private boolean mSizeChanged = true; private SurfaceHolder mHolder; private GLThread mGLThread; private GLWrapper mGLWrapper; }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.RadioGroup; /** * Main entry point for the SpriteMethodTest application. This application * provides a simple interface for testing the relative speed of 2D rendering * systems available on Android, namely the Canvas system and OpenGL ES. It * also serves as an example of how SurfaceHolders can be used to create an * efficient rendering thread for drawing. */ public class SpriteMethodTest extends Activity { private static final int ACTIVITY_TEST = 0; private static final int RESULTS_DIALOG = 0; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Sets up a click listener for the Run Test button. Button button; button = (Button) findViewById(R.id.runTest); button.setOnClickListener(mRunTestListener); // Turns on one item by default in our radio groups--as it should be! RadioGroup group = (RadioGroup)findViewById(R.id.renderMethod); group.setOnCheckedChangeListener(mMethodChangedListener); group.check(R.id.methodCanvas); RadioGroup glSettings = (RadioGroup)findViewById(R.id.GLSettings); glSettings.check(R.id.settingVerts); } /** Passes preferences about the test via its intent. */ protected void initializeIntent(Intent i) { final CheckBox checkBox = (CheckBox) findViewById(R.id.animateSprites); final boolean animate = checkBox.isChecked(); final EditText editText = (EditText) findViewById(R.id.spriteCount); final String spriteCountText = editText.getText().toString(); final int stringCount = Integer.parseInt(spriteCountText); i.putExtra("animate", animate); i.putExtra("spriteCount", stringCount); } /** * Responds to a click on the Run Test button by launching a new test * activity. */ View.OnClickListener mRunTestListener = new OnClickListener() { public void onClick(View v) { RadioGroup group = (RadioGroup)findViewById(R.id.renderMethod); Intent i; if (group.getCheckedRadioButtonId() == R.id.methodCanvas) { i = new Intent(v.getContext(), CanvasTestActivity.class); } else { i = new Intent(v.getContext(), OpenGLTestActivity.class); RadioGroup glSettings = (RadioGroup)findViewById(R.id.GLSettings); if (glSettings.getCheckedRadioButtonId() == R.id.settingVerts) { i.putExtra("useVerts", true); } else if (glSettings.getCheckedRadioButtonId() == R.id.settingVBO) { i.putExtra("useVerts", true); i.putExtra("useHardwareBuffers", true); } } initializeIntent(i); startActivityForResult(i, ACTIVITY_TEST); } }; /** * Enables or disables OpenGL ES-specific settings controls when the render * method option changes. */ RadioGroup.OnCheckedChangeListener mMethodChangedListener = new RadioGroup.OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup group, int checkedId) { if (checkedId == R.id.methodCanvas) { findViewById(R.id.settingDrawTexture).setEnabled(false); findViewById(R.id.settingVerts).setEnabled(false); findViewById(R.id.settingVBO).setEnabled(false); } else { findViewById(R.id.settingDrawTexture).setEnabled(true); findViewById(R.id.settingVerts).setEnabled(true); findViewById(R.id.settingVBO).setEnabled(true); } } }; /** Creates the test results dialog and fills in a dummy message. */ @Override protected Dialog onCreateDialog(int id) { Dialog dialog = null; if (id == RESULTS_DIALOG) { String dummy = "No results yet."; CharSequence sequence = dummy.subSequence(0, dummy.length() -1); dialog = new AlertDialog.Builder(this) .setTitle(R.string.dialog_title) .setPositiveButton(R.string.dialog_ok, null) .setMessage(sequence) .create(); } return dialog; } /** * Replaces the dummy message in the test results dialog with a string that * describes the actual test results. */ protected void onPrepareDialog (int id, Dialog dialog) { if (id == RESULTS_DIALOG) { // Extract final timing information from the profiler. final ProfileRecorder profiler = ProfileRecorder.sSingleton; final long frameTime = profiler.getAverageTime(ProfileRecorder.PROFILE_FRAME); final long frameMin = profiler.getMinTime(ProfileRecorder.PROFILE_FRAME); final long frameMax = profiler.getMaxTime(ProfileRecorder.PROFILE_FRAME); final long drawTime = profiler.getAverageTime(ProfileRecorder.PROFILE_DRAW); final long drawMin = profiler.getMinTime(ProfileRecorder.PROFILE_DRAW); final long drawMax = profiler.getMaxTime(ProfileRecorder.PROFILE_DRAW); final long flipTime = profiler.getAverageTime(ProfileRecorder.PROFILE_PAGE_FLIP); final long flipMin = profiler.getMinTime(ProfileRecorder.PROFILE_PAGE_FLIP); final long flipMax = profiler.getMaxTime(ProfileRecorder.PROFILE_PAGE_FLIP); final long simTime = profiler.getAverageTime(ProfileRecorder.PROFILE_SIM); final long simMin = profiler.getMinTime(ProfileRecorder.PROFILE_SIM); final long simMax = profiler.getMaxTime(ProfileRecorder.PROFILE_SIM); final float fps = frameTime > 0 ? 1000.0f / frameTime : 0.0f; String result = "Frame: " + frameTime + "ms (" + fps + " fps)\n" + "\t\tMin: " + frameMin + "ms\t\tMax: " + frameMax + "\n" + "Draw: " + drawTime + "ms\n" + "\t\tMin: " + drawMin + "ms\t\tMax: " + drawMax + "\n" + "Page Flip: " + flipTime + "ms\n" + "\t\tMin: " + flipMin + "ms\t\tMax: " + flipMax + "\n" + "Sim: " + simTime + "ms\n" + "\t\tMin: " + simMin + "ms\t\tMax: " + simMax + "\n"; CharSequence sequence = result.subSequence(0, result.length() -1); AlertDialog alertDialog = (AlertDialog)dialog; alertDialog.setMessage(sequence); } } /** Shows the results dialog when the test activity closes. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); showDialog(RESULTS_DIALOG); } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11Ext; /** * This is the OpenGL ES version of a sprite. It is more complicated than the * CanvasSprite class because it can be used in more than one way. This class * can draw using a grid of verts, a grid of verts stored in VBO objects, or * using the DrawTexture extension. */ public class GLSprite extends Renderable { // The OpenGL ES texture handle to draw. private int mTextureName; // The id of the original resource that mTextureName is based on. private int mResourceId; // If drawing with verts or VBO verts, the grid object defining those verts. private Grid mGrid; public GLSprite(int resourceId) { super(); mResourceId = resourceId; } public void setTextureName(int name) { mTextureName = name; } public int getTextureName() { return mTextureName; } public void setResourceId(int id) { mResourceId = id; } public int getResourceId() { return mResourceId; } public void setGrid(Grid grid) { mGrid = grid; } public Grid getGrid() { return mGrid; } public void draw(GL10 gl) { gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureName); if (mGrid == null) { // Draw using the DrawTexture extension. ((GL11Ext) gl).glDrawTexfOES(x, y, z, width, height); } else { // Draw using verts or VBO verts. gl.glPushMatrix(); gl.glLoadIdentity(); gl.glTranslatef( x, y, z); mGrid.draw(gl, true, false); gl.glPopMatrix(); } } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import java.io.IOException; import java.io.InputStream; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.util.DisplayMetrics; /** * Activity for testing Canvas drawing speed. This activity sets up sprites and * passes them off to a CanvasSurfaceView for rendering and movement. It is * very similar to OpenGLTestActivity. Note that Bitmap objects come out of a * pool and must be explicitly recycled on shutdown. See onDestroy(). */ public class CanvasTestActivity extends Activity { private CanvasSurfaceView mCanvasSurfaceView; // Describes the image format our bitmaps should be converted to. private static BitmapFactory.Options sBitmapOptions = new BitmapFactory.Options(); private Bitmap[] mBitmaps; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCanvasSurfaceView = new CanvasSurfaceView(this); SimpleCanvasRenderer spriteRenderer = new SimpleCanvasRenderer(); // Sets our preferred image format to 16-bit, 565 format. sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565; // Clear out any old profile results. ProfileRecorder.sSingleton.resetAll(); final Intent callingIntent = getIntent(); // Allocate our sprites and add them to an array. final int robotCount = callingIntent.getIntExtra("spriteCount", 10); final boolean animate = callingIntent.getBooleanExtra("animate", true); // Allocate space for the robot sprites + one background sprite. CanvasSprite[] spriteArray = new CanvasSprite[robotCount + 1]; mBitmaps = new Bitmap[4]; mBitmaps[0] = loadBitmap(this, R.drawable.background); mBitmaps[1] = loadBitmap(this, R.drawable.skate1); mBitmaps[2] = loadBitmap(this, R.drawable.skate2); mBitmaps[3] = loadBitmap(this, R.drawable.skate3); // We need to know the width and height of the display pretty soon, // so grab the information now. DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); // Make the background. // Note that the background image is larger than the screen, // so some clipping will occur when it is drawn. CanvasSprite background = new CanvasSprite(mBitmaps[0]); background.width = mBitmaps[0].getWidth(); background.height = mBitmaps[0].getHeight(); spriteArray[0] = background; // This list of things to move. It points to the same content as // spriteArray except for the background. Renderable[] renderableArray = new Renderable[robotCount]; final int robotBucketSize = robotCount / 3; for (int x = 0; x < robotCount; x++) { CanvasSprite robot; // Our robots come in three flavors. Split them up accordingly. if (x < robotBucketSize) { robot = new CanvasSprite(mBitmaps[1]); } else if (x < robotBucketSize * 2) { robot = new CanvasSprite(mBitmaps[2]); } else { robot = new CanvasSprite(mBitmaps[3]); } robot.width = 64; robot.height = 64; // Pick a random location for this sprite. robot.x = (float)(Math.random() * dm.widthPixels); robot.y = (float)(Math.random() * dm.heightPixels); // Add this robot to the spriteArray so it gets drawn and to the // renderableArray so that it gets moved. spriteArray[x + 1] = robot; renderableArray[x] = robot; } // Now's a good time to run the GC. Since we won't do any explicit // allocation during the test, the GC should stay dormant and not // influence our results. Runtime r = Runtime.getRuntime(); r.gc(); spriteRenderer.setSprites(spriteArray); mCanvasSurfaceView.setRenderer(spriteRenderer); if (animate) { Mover simulationRuntime = new Mover(); simulationRuntime.setRenderables(renderableArray); simulationRuntime.setViewSize(dm.widthPixels, dm.heightPixels); mCanvasSurfaceView.setEvent(simulationRuntime); } setContentView(mCanvasSurfaceView); } /** Recycles all of the bitmaps loaded in onCreate(). */ @Override protected void onDestroy() { super.onDestroy(); mCanvasSurfaceView.clearEvent(); mCanvasSurfaceView.stopDrawing(); for (int x = 0; x < mBitmaps.length; x++) { mBitmaps[x].recycle(); mBitmaps[x] = null; } } /** * Loads a bitmap from a resource and converts it to a bitmap. This is * a much-simplified version of the loadBitmap() that appears in * SimpleGLRenderer. * @param context The application context. * @param resourceId The id of the resource to load. * @return A bitmap containing the image contents of the resource, or null * if there was an error. */ protected Bitmap loadBitmap(Context context, int resourceId) { Bitmap bitmap = null; if (context != null) { InputStream is = context.getResources().openRawResource(resourceId); try { bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions); } finally { try { is.close(); } catch (IOException e) { // Ignore. } } } return bitmap; } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import android.os.SystemClock; /** * A simple runnable that updates the position of each sprite on the screen * every frame by applying a very simple gravity and bounce simulation. The * sprites are jumbled with random velocities every once and a while. */ public class Mover implements Runnable { private Renderable[] mRenderables; private long mLastTime; private long mLastJumbleTime; private int mViewWidth; private int mViewHeight; static final float COEFFICIENT_OF_RESTITUTION = 0.75f; static final float SPEED_OF_GRAVITY = 150.0f; static final long JUMBLE_EVERYTHING_DELAY = 15 * 1000; static final float MAX_VELOCITY = 8000.0f; public void run() { // Perform a single simulation step. if (mRenderables != null) { final long time = SystemClock.uptimeMillis(); final long timeDelta = time - mLastTime; final float timeDeltaSeconds = mLastTime > 0.0f ? timeDelta / 1000.0f : 0.0f; mLastTime = time; // Check to see if it's time to jumble again. final boolean jumble = (time - mLastJumbleTime > JUMBLE_EVERYTHING_DELAY); if (jumble) { mLastJumbleTime = time; } for (int x = 0; x < mRenderables.length; x++) { Renderable object = mRenderables[x]; // Jumble! Apply random velocities. if (jumble) { object.velocityX += (MAX_VELOCITY / 2.0f) - (float)(Math.random() * MAX_VELOCITY); object.velocityY += (MAX_VELOCITY / 2.0f) - (float)(Math.random() * MAX_VELOCITY); } // Move. object.x = object.x + (object.velocityX * timeDeltaSeconds); object.y = object.y + (object.velocityY * timeDeltaSeconds); object.z = object.z + (object.velocityZ * timeDeltaSeconds); // Apply Gravity. object.velocityY -= SPEED_OF_GRAVITY * timeDeltaSeconds; // Bounce. if ((object.x < 0.0f && object.velocityX < 0.0f) || (object.x > mViewWidth - object.width && object.velocityX > 0.0f)) { object.velocityX = -object.velocityX * COEFFICIENT_OF_RESTITUTION; object.x = Math.max(0.0f, Math.min(object.x, mViewWidth - object.width)); if (Math.abs(object.velocityX) < 0.1f) { object.velocityX = 0.0f; } } if ((object.y < 0.0f && object.velocityY < 0.0f) || (object.y > mViewHeight - object.height && object.velocityY > 0.0f)) { object.velocityY = -object.velocityY * COEFFICIENT_OF_RESTITUTION; object.y = Math.max(0.0f, Math.min(object.y, mViewHeight - object.height)); if (Math.abs(object.velocityY) < 0.1f) { object.velocityY = 0.0f; } } } } } public void setRenderables(Renderable[] renderables) { mRenderables = renderables; } public void setViewSize(int width, int height) { mViewHeight = height; mViewWidth = width; } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import java.io.IOException; import java.io.InputStream; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import javax.microedition.khronos.opengles.GL11Ext; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLUtils; import android.util.Log; /** * An OpenGL ES renderer based on the GLSurfaceView rendering framework. This * class is responsible for drawing a list of renderables to the screen every * frame. It also manages loading of textures and (when VBOs are used) the * allocation of vertex buffer objects. */ public class SimpleGLRenderer implements GLSurfaceView.Renderer { // Specifies the format our textures should be converted to upon load. private static BitmapFactory.Options sBitmapOptions = new BitmapFactory.Options(); // An array of things to draw every frame. private GLSprite[] mSprites; // Pre-allocated arrays to use at runtime so that allocation during the // test can be avoided. private int[] mTextureNameWorkspace; private int[] mCropWorkspace; // A reference to the application context. private Context mContext; // Determines the use of vertex arrays. private boolean mUseVerts; // Determines the use of vertex buffer objects. private boolean mUseHardwareBuffers; public SimpleGLRenderer(Context context) { // Pre-allocate and store these objects so we can use them at runtime // without allocating memory mid-frame. mTextureNameWorkspace = new int[1]; mCropWorkspace = new int[4]; // Set our bitmaps to 16-bit, 565 format. sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565; mContext = context; } public int[] getConfigSpec() { // We don't need a depth buffer, and don't care about our // color depth. int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_NONE }; return configSpec; } public void setSprites(GLSprite[] sprites) { mSprites = sprites; } /** * Changes the vertex mode used for drawing. * @param useVerts Specifies whether to use a vertex array. If false, the * DrawTexture extension is used. * @param useHardwareBuffers Specifies whether to store vertex arrays in * main memory or on the graphics card. Ignored if useVerts is false. */ public void setVertMode(boolean useVerts, boolean useHardwareBuffers) { mUseVerts = useVerts; mUseHardwareBuffers = useVerts ? useHardwareBuffers : false; } /** Draws the sprites. */ public void drawFrame(GL10 gl) { if (mSprites != null) { gl.glMatrixMode(GL10.GL_MODELVIEW); if (mUseVerts) { Grid.beginDrawing(gl, true, false); } for (int x = 0; x < mSprites.length; x++) { mSprites[x].draw(gl); } if (mUseVerts) { Grid.endDrawing(gl); } } } /* Called when the size of the window changes. */ public void sizeChanged(GL10 gl, int width, int height) { gl.glViewport(0, 0, width, height); /* * Set our projection matrix. This doesn't have to be done each time we * draw, but usually a new projection needs to be set when the viewport * is resized. */ gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glOrthof(0.0f, width, 0.0f, height, 0.0f, 1.0f); gl.glShadeModel(GL10.GL_FLAT); gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000); gl.glEnable(GL10.GL_TEXTURE_2D); } /** * Called whenever the surface is created. This happens at startup, and * may be called again at runtime if the device context is lost (the screen * goes to sleep, etc). This function must fill the contents of vram with * texture data and (when using VBOs) hardware vertex arrays. */ public void surfaceCreated(GL10 gl) { /* * Some one-time OpenGL initialization can be made here probably based * on features of this particular context */ gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); gl.glClearColor(0.5f, 0.5f, 0.5f, 1); gl.glShadeModel(GL10.GL_FLAT); gl.glDisable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_TEXTURE_2D); /* * By default, OpenGL enables features that improve quality but reduce * performance. One might want to tweak that especially on software * renderer. */ gl.glDisable(GL10.GL_DITHER); gl.glDisable(GL10.GL_LIGHTING); gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); if (mSprites != null) { // If we are using hardware buffers and the screen lost context // then the buffer indexes that we recorded previously are now // invalid. Forget them here and recreate them below. if (mUseHardwareBuffers) { for (int x = 0; x < mSprites.length; x++) { // Ditch old buffer indexes. mSprites[x].getGrid().invalidateHardwareBuffers(); } } // Load our texture and set its texture name on all sprites. // To keep this sample simple we will assume that sprites that share // the same texture are grouped together in our sprite list. A real // app would probably have another level of texture management, // like a texture hash. int lastLoadedResource = -1; int lastTextureId = -1; for (int x = 0; x < mSprites.length; x++) { int resource = mSprites[x].getResourceId(); if (resource != lastLoadedResource) { lastTextureId = loadBitmap(mContext, gl, resource); lastLoadedResource = resource; } mSprites[x].setTextureName(lastTextureId); if (mUseHardwareBuffers) { Grid currentGrid = mSprites[x].getGrid(); if (!currentGrid.usingHardwareBuffers()) { currentGrid.generateHardwareBuffers(gl); } //mSprites[x].getGrid().generateHardwareBuffers(gl); } } } } /** * Called when the rendering thread shuts down. This is a good place to * release OpenGL ES resources. * @param gl */ public void shutdown(GL10 gl) { if (mSprites != null) { int lastFreedResource = -1; int[] textureToDelete = new int[1]; for (int x = 0; x < mSprites.length; x++) { int resource = mSprites[x].getResourceId(); if (resource != lastFreedResource) { textureToDelete[0] = mSprites[x].getTextureName(); gl.glDeleteTextures(1, textureToDelete, 0); mSprites[x].setTextureName(0); } if (mUseHardwareBuffers) { mSprites[x].getGrid().releaseHardwareBuffers(gl); } } } } /** * Loads a bitmap into OpenGL and sets up the common parameters for * 2D texture maps. */ protected int loadBitmap(Context context, GL10 gl, int resourceId) { int textureName = -1; if (context != null && gl != null) { gl.glGenTextures(1, mTextureNameWorkspace, 0); textureName = mTextureNameWorkspace[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); InputStream is = context.getResources().openRawResource(resourceId); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions); } finally { try { is.close(); } catch (IOException e) { // Ignore. } } GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); mCropWorkspace[0] = 0; mCropWorkspace[1] = bitmap.getHeight(); mCropWorkspace[2] = bitmap.getWidth(); mCropWorkspace[3] = -bitmap.getHeight(); bitmap.recycle(); ((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D, GL11Ext.GL_TEXTURE_CROP_RECT_OES, mCropWorkspace, 0); int error = gl.glGetError(); if (error != GL10.GL_NO_ERROR) { Log.e("SpriteMethodTest", "Texture Load GLError: " + error); } } return textureName; } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.spritemethodtest; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.CharBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; /** * A 2D rectangular mesh. Can be drawn textured or untextured. * This version is modified from the original Grid.java (found in * the SpriteText package in the APIDemos Android sample) to support hardware * vertex buffers. */ class Grid { private FloatBuffer mFloatVertexBuffer; private FloatBuffer mFloatTexCoordBuffer; private FloatBuffer mFloatColorBuffer; private IntBuffer mFixedVertexBuffer; private IntBuffer mFixedTexCoordBuffer; private IntBuffer mFixedColorBuffer; private CharBuffer mIndexBuffer; private Buffer mVertexBuffer; private Buffer mTexCoordBuffer; private Buffer mColorBuffer; private int mCoordinateSize; private int mCoordinateType; private int mW; private int mH; private int mIndexCount; private boolean mUseHardwareBuffers; private int mVertBufferIndex; private int mIndexBufferIndex; private int mTextureCoordBufferIndex; private int mColorBufferIndex; public Grid(int vertsAcross, int vertsDown, boolean useFixedPoint) { if (vertsAcross < 0 || vertsAcross >= 65536) { throw new IllegalArgumentException("vertsAcross"); } if (vertsDown < 0 || vertsDown >= 65536) { throw new IllegalArgumentException("vertsDown"); } if (vertsAcross * vertsDown >= 65536) { throw new IllegalArgumentException("vertsAcross * vertsDown >= 65536"); } mUseHardwareBuffers = false; mW = vertsAcross; mH = vertsDown; int size = vertsAcross * vertsDown; final int FLOAT_SIZE = 4; final int FIXED_SIZE = 4; final int CHAR_SIZE = 2; if (useFixedPoint) { mFixedVertexBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 3) .order(ByteOrder.nativeOrder()).asIntBuffer(); mFixedTexCoordBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 2) .order(ByteOrder.nativeOrder()).asIntBuffer(); mFixedColorBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 4) .order(ByteOrder.nativeOrder()).asIntBuffer(); mVertexBuffer = mFixedVertexBuffer; mTexCoordBuffer = mFixedTexCoordBuffer; mColorBuffer = mFixedColorBuffer; mCoordinateSize = FIXED_SIZE; mCoordinateType = GL10.GL_FIXED; } else { mFloatVertexBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 3) .order(ByteOrder.nativeOrder()).asFloatBuffer(); mFloatTexCoordBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2) .order(ByteOrder.nativeOrder()).asFloatBuffer(); mFloatColorBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 4) .order(ByteOrder.nativeOrder()).asFloatBuffer(); mVertexBuffer = mFloatVertexBuffer; mTexCoordBuffer = mFloatTexCoordBuffer; mColorBuffer = mFloatColorBuffer; mCoordinateSize = FLOAT_SIZE; mCoordinateType = GL10.GL_FLOAT; } int quadW = mW - 1; int quadH = mH - 1; int quadCount = quadW * quadH; int indexCount = quadCount * 6; mIndexCount = indexCount; mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount) .order(ByteOrder.nativeOrder()).asCharBuffer(); /* * Initialize triangle list mesh. * * [0]-----[ 1] ... * | / | * | / | * | / | * [w]-----[w+1] ... * | | * */ { int i = 0; for (int y = 0; y < quadH; y++) { for (int x = 0; x < quadW; x++) { char a = (char) (y * mW + x); char b = (char) (y * mW + x + 1); char c = (char) ((y + 1) * mW + x); char d = (char) ((y + 1) * mW + x + 1); mIndexBuffer.put(i++, a); mIndexBuffer.put(i++, b); mIndexBuffer.put(i++, c); mIndexBuffer.put(i++, b); mIndexBuffer.put(i++, c); mIndexBuffer.put(i++, d); } } } mVertBufferIndex = 0; } void set(int i, int j, float x, float y, float z, float u, float v, float[] color) { if (i < 0 || i >= mW) { throw new IllegalArgumentException("i"); } if (j < 0 || j >= mH) { throw new IllegalArgumentException("j"); } final int index = mW * j + i; final int posIndex = index * 3; final int texIndex = index * 2; final int colorIndex = index * 4; if (mCoordinateType == GL10.GL_FLOAT) { mFloatVertexBuffer.put(posIndex, x); mFloatVertexBuffer.put(posIndex + 1, y); mFloatVertexBuffer.put(posIndex + 2, z); mFloatTexCoordBuffer.put(texIndex, u); mFloatTexCoordBuffer.put(texIndex + 1, v); if (color != null) { mFloatColorBuffer.put(colorIndex, color[0]); mFloatColorBuffer.put(colorIndex + 1, color[1]); mFloatColorBuffer.put(colorIndex + 2, color[2]); mFloatColorBuffer.put(colorIndex + 3, color[3]); } } else { mFixedVertexBuffer.put(posIndex, (int)(x * (1 << 16))); mFixedVertexBuffer.put(posIndex + 1, (int)(y * (1 << 16))); mFixedVertexBuffer.put(posIndex + 2, (int)(z * (1 << 16))); mFixedTexCoordBuffer.put(texIndex, (int)(u * (1 << 16))); mFixedTexCoordBuffer.put(texIndex + 1, (int)(v * (1 << 16))); if (color != null) { mFixedColorBuffer.put(colorIndex, (int)(color[0] * (1 << 16))); mFixedColorBuffer.put(colorIndex + 1, (int)(color[1] * (1 << 16))); mFixedColorBuffer.put(colorIndex + 2, (int)(color[2] * (1 << 16))); mFixedColorBuffer.put(colorIndex + 3, (int)(color[3] * (1 << 16))); } } } public static void beginDrawing(GL10 gl, boolean useTexture, boolean useColor) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); if (useTexture) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glEnable(GL10.GL_TEXTURE_2D); } else { gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glDisable(GL10.GL_TEXTURE_2D); } if (useColor) { gl.glEnableClientState(GL10.GL_COLOR_ARRAY); } else { gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } } public void draw(GL10 gl, boolean useTexture, boolean useColor) { if (!mUseHardwareBuffers) { gl.glVertexPointer(3, mCoordinateType, 0, mVertexBuffer); if (useTexture) { gl.glTexCoordPointer(2, mCoordinateType, 0, mTexCoordBuffer); } if (useColor) { gl.glColorPointer(4, mCoordinateType, 0, mColorBuffer); } gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); } else { GL11 gl11 = (GL11)gl; // draw using hardware buffers gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex); gl11.glVertexPointer(3, mCoordinateType, 0, 0); if (useTexture) { gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTextureCoordBufferIndex); gl11.glTexCoordPointer(2, mCoordinateType, 0, 0); } if (useColor) { gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mColorBufferIndex); gl11.glColorPointer(4, mCoordinateType, 0, 0); } gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex); gl11.glDrawElements(GL11.GL_TRIANGLES, mIndexCount, GL11.GL_UNSIGNED_SHORT, 0); gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0); gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); } } public static void endDrawing(GL10 gl) { gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } public boolean usingHardwareBuffers() { return mUseHardwareBuffers; } /** * When the OpenGL ES device is lost, GL handles become invalidated. * In that case, we just want to "forget" the old handles (without * explicitly deleting them) and make new ones. */ public void invalidateHardwareBuffers() { mVertBufferIndex = 0; mIndexBufferIndex = 0; mTextureCoordBufferIndex = 0; mColorBufferIndex = 0; mUseHardwareBuffers = false; } /** * Deletes the hardware buffers allocated by this object (if any). */ public void releaseHardwareBuffers(GL10 gl) { if (mUseHardwareBuffers) { if (gl instanceof GL11) { GL11 gl11 = (GL11)gl; int[] buffer = new int[1]; buffer[0] = mVertBufferIndex; gl11.glDeleteBuffers(1, buffer, 0); buffer[0] = mTextureCoordBufferIndex; gl11.glDeleteBuffers(1, buffer, 0); buffer[0] = mColorBufferIndex; gl11.glDeleteBuffers(1, buffer, 0); buffer[0] = mIndexBufferIndex; gl11.glDeleteBuffers(1, buffer, 0); } invalidateHardwareBuffers(); } } /** * Allocates hardware buffers on the graphics card and fills them with * data if a buffer has not already been previously allocated. Note that * this function uses the GL_OES_vertex_buffer_object extension, which is * not guaranteed to be supported on every device. * @param gl A pointer to the OpenGL ES context. */ public void generateHardwareBuffers(GL10 gl) { if (!mUseHardwareBuffers) { if (gl instanceof GL11) { GL11 gl11 = (GL11)gl; int[] buffer = new int[1]; // Allocate and fill the vertex buffer. gl11.glGenBuffers(1, buffer, 0); mVertBufferIndex = buffer[0]; gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex); final int vertexSize = mVertexBuffer.capacity() * mCoordinateSize; gl11.glBufferData(GL11.GL_ARRAY_BUFFER, vertexSize, mVertexBuffer, GL11.GL_STATIC_DRAW); // Allocate and fill the texture coordinate buffer. gl11.glGenBuffers(1, buffer, 0); mTextureCoordBufferIndex = buffer[0]; gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTextureCoordBufferIndex); final int texCoordSize = mTexCoordBuffer.capacity() * mCoordinateSize; gl11.glBufferData(GL11.GL_ARRAY_BUFFER, texCoordSize, mTexCoordBuffer, GL11.GL_STATIC_DRAW); // Allocate and fill the color buffer. gl11.glGenBuffers(1, buffer, 0); mColorBufferIndex = buffer[0]; gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mColorBufferIndex); final int colorSize = mColorBuffer.capacity() * mCoordinateSize; gl11.glBufferData(GL11.GL_ARRAY_BUFFER, colorSize, mColorBuffer, GL11.GL_STATIC_DRAW); // Unbind the array buffer. gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0); // Allocate and fill the index buffer. gl11.glGenBuffers(1, buffer, 0); mIndexBufferIndex = buffer[0]; gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex); // A char is 2 bytes. final int indexSize = mIndexBuffer.capacity() * 2; gl11.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, indexSize, mIndexBuffer, GL11.GL_STATIC_DRAW); // Unbind the element array buffer. gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); mUseHardwareBuffers = true; assert mVertBufferIndex != 0; assert mTextureCoordBufferIndex != 0; assert mIndexBufferIndex != 0; assert gl11.glGetError() == 0; } } } // These functions exposed to patch Grid info into native code. public final int getVertexBuffer() { return mVertBufferIndex; } public final int getTextureBuffer() { return mTextureCoordBufferIndex; } public final int getIndexBuffer() { return mIndexBufferIndex; } public final int getColorBuffer() { return mColorBufferIndex; } public final int getIndexCount() { return mIndexCount; } public boolean getFixedPoint() { return (mCoordinateType == GL10.GL_FIXED); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.radar; import com.google.android.maps.GeoPoint; /** * Library for some use useful latitude/longitude math */ public class GeoUtils { private static int EARTH_RADIUS_KM = 6371; public static int MILLION = 1000000; /** * Computes the distance in kilometers between two points on Earth. * * @param lat1 Latitude of the first point * @param lon1 Longitude of the first point * @param lat2 Latitude of the second point * @param lon2 Longitude of the second point * @return Distance between the two points in kilometers. */ public static double distanceKm(double lat1, double lon1, double lat2, double lon2) { double lat1Rad = Math.toRadians(lat1); double lat2Rad = Math.toRadians(lat2); double deltaLonRad = Math.toRadians(lon2 - lon1); return Math.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad)) * EARTH_RADIUS_KM; } /** * Computes the distance in kilometers between two points on Earth. * * @param p1 First point * @param p2 Second point * @return Distance between the two points in kilometers. */ public static double distanceKm(GeoPoint p1, GeoPoint p2) { double lat1 = p1.getLatitudeE6() / (double)MILLION; double lon1 = p1.getLongitudeE6() / (double)MILLION; double lat2 = p2.getLatitudeE6() / (double)MILLION; double lon2 = p2.getLongitudeE6() / (double)MILLION; return distanceKm(lat1, lon1, lat2, lon2); } /** * Computes the bearing in degrees between two points on Earth. * * @param p1 First point * @param p2 Second point * @return Bearing between the two points in degrees. A value of 0 means due * north. */ public static double bearing(GeoPoint p1, GeoPoint p2) { double lat1 = p1.getLatitudeE6() / (double) MILLION; double lon1 = p1.getLongitudeE6() / (double) MILLION; double lat2 = p2.getLatitudeE6() / (double) MILLION; double lon2 = p2.getLongitudeE6() / (double) MILLION; return bearing(lat1, lon1, lat2, lon2); } /** * Computes the bearing in degrees between two points on Earth. * * @param lat1 Latitude of the first point * @param lon1 Longitude of the first point * @param lat2 Latitude of the second point * @param lon2 Longitude of the second point * @return Bearing between the two points in degrees. A value of 0 means due * north. */ public static double bearing(double lat1, double lon1, double lat2, double lon2) { double lat1Rad = Math.toRadians(lat1); double lat2Rad = Math.toRadians(lat2); double deltaLonRad = Math.toRadians(lon2 - lon1); double y = Math.sin(deltaLonRad) * Math.cos(lat2Rad); double x = Math.cos(lat1Rad) * Math.sin(lat2Rad) - Math.sin(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad); return radToBearing(Math.atan2(y, x)); } /** * Converts an angle in radians to degrees */ public static double radToBearing(double rad) { return (Math.toDegrees(rad) + 360) % 360; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.radar; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.drawable.BitmapDrawable; import android.hardware.SensorListener; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.os.Bundle; import android.os.SystemClock; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; public class RadarView extends View implements SensorListener, LocationListener { private static final long RETAIN_GPS_MILLIS = 10000L; private Paint mGridPaint; private Paint mErasePaint; private float mOrientation; private double mTargetLat; private double mTargetLon; private double mMyLocationLat; private double mMyLocationLon; private int mLastScale = -1; private String[] mDistanceScale = new String[4]; private static float KM_PER_METERS = 0.001f; private static float METERS_PER_KM = 1000f; /** * These are the list of choices for the radius of the outer circle on the * screen when using metric units. All items are in kilometers. This array is * used to choose the scale of the radar display. */ private static double mMetricScaleChoices[] = { 100 * KM_PER_METERS, 200 * KM_PER_METERS, 400 * KM_PER_METERS, 1, 2, 4, 8, 20, 40, 100, 200, 400, 1000, 2000, 4000, 10000, 20000, 40000, 80000 }; /** * Once the scale is chosen, this array is used to convert the number of * kilometers on the screen to an integer. (Note that for short distances we * use meters, so we multiply the distance by {@link #METERS_PER_KM}. (This * array is for metric measurements.) */ private static float mMetricDisplayUnitsPerKm[] = { METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }; /** * This array holds the formatting string used to display the distance to * the target. (This array is for metric measurements.) */ private static String mMetricDisplayFormats[] = { "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.1fkm", "%.1fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm" }; /** * This array holds the formatting string used to display the distance on * each ring of the radar screen. (This array is for metric measurements.) */ private static String mMetricScaleFormats[] = { "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm" }; private static float KM_PER_YARDS = 0.0009144f; private static float KM_PER_MILES = 1.609344f; private static float YARDS_PER_KM = 1093.6133f; private static float MILES_PER_KM = 0.621371192f; /** * These are the list of choices for the radius of the outer circle on the * screen when using standard units. All items are in kilometers. This array is * used to choose the scale of the radar display. */ private static double mEnglishScaleChoices[] = { 100 * KM_PER_YARDS, 200 * KM_PER_YARDS, 400 * KM_PER_YARDS, 1000 * KM_PER_YARDS, 1 * KM_PER_MILES, 2 * KM_PER_MILES, 4 * KM_PER_MILES, 8 * KM_PER_MILES, 20 * KM_PER_MILES, 40 * KM_PER_MILES, 100 * KM_PER_MILES, 200 * KM_PER_MILES, 400 * KM_PER_MILES, 1000 * KM_PER_MILES, 2000 * KM_PER_MILES, 4000 * KM_PER_MILES, 10000 * KM_PER_MILES, 20000 * KM_PER_MILES, 40000 * KM_PER_MILES, 80000 * KM_PER_MILES }; /** * Once the scale is chosen, this array is used to convert the number of * kilometers on the screen to an integer. (Note that for short distances we * use meters, so we multiply the distance by {@link #YARDS_PER_KM}. (This * array is for standard measurements.) */ private static float mEnglishDisplayUnitsPerKm[] = { YARDS_PER_KM, YARDS_PER_KM, YARDS_PER_KM, YARDS_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM }; /** * This array holds the formatting string used to display the distance to * the target. (This array is for standard measurements.) */ private static String mEnglishDisplayFormats[] = { "%.0fyd", "%.0fyd", "%.0fyd", "%.0fyd", "%.1fmi", "%.1fmi", "%.1fmi", "%.1fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi" }; /** * This array holds the formatting string used to display the distance on * each ring of the radar screen. (This array is for standard measurements.) */ private static String mEnglishScaleFormats[] = { "%.0fyd", "%.0fyd", "%.0fyd", "%.0fyd", "%.2fmi", "%.1fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi" }; /** * True when we have know our own location */ private boolean mHaveLocation = false; /** * The view that will display the distance text */ private TextView mDistanceView; /** * Distance to target, in KM */ private double mDistance; /** * Bearing to target, in degrees */ private double mBearing; /** * Ratio of the distance to the target to the radius of the outermost ring on the radar screen */ private float mDistanceRatio; /** * Utility rect for calculating the ring labels */ private Rect mTextBounds = new Rect(); /** * The bitmap used to draw the target */ private Bitmap mBlip; /** * Used to draw the animated ring that sweeps out from the center */ private Paint mSweepPaint0; /** * Used to draw the animated ring that sweeps out from the center */ private Paint mSweepPaint1; /** * Used to draw the animated ring that sweeps out from the center */ private Paint mSweepPaint2; /** * Time in millis when the most recent sweep began */ private long mSweepTime; /** * True if the sweep has not yet intersected the blip */ private boolean mSweepBefore; /** * Time in millis when the sweep last crossed the blip */ private long mBlipTime; /** * True if the display should use metric units; false if the display should use standard * units */ private boolean mUseMetric; /** * Time in millis for the last time GPS reported a location */ private long mLastGpsFixTime = 0L; /** * The last location reported by the network provider. Use this if we can't get a location from * GPS */ private Location mNetworkLocation; /** * True if GPS is reporting a location */ private boolean mGpsAvailable; /** * True if the network provider is reporting a location */ private boolean mNetworkAvailable; public RadarView(Context context) { this(context, null); } public RadarView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RadarView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // Paint used for the rings and ring text mGridPaint = new Paint(); mGridPaint.setColor(0xFF00FF00); mGridPaint.setAntiAlias(true); mGridPaint.setStyle(Style.STROKE); mGridPaint.setStrokeWidth(1.0f); mGridPaint.setTextSize(10.0f); mGridPaint.setTextAlign(Align.CENTER); // Paint used to erase the rectangle behing the ring text mErasePaint = new Paint(); mErasePaint.setColor(0xFF191919); mErasePaint.setStyle(Style.FILL); // Outer ring of the sweep mSweepPaint0 = new Paint(); mSweepPaint0.setColor(0xFF33FF33); mSweepPaint0.setAntiAlias(true); mSweepPaint0.setStyle(Style.STROKE); mSweepPaint0.setStrokeWidth(2f); // Middle ring of the sweep mSweepPaint1 = new Paint(); mSweepPaint1.setColor(0x7733FF33); mSweepPaint1.setAntiAlias(true); mSweepPaint1.setStyle(Style.STROKE); mSweepPaint1.setStrokeWidth(2f); // Inner ring of the sweep mSweepPaint2 = new Paint(); mSweepPaint2.setColor(0x3333FF33); mSweepPaint2.setAntiAlias(true); mSweepPaint2.setStyle(Style.STROKE); mSweepPaint2.setStrokeWidth(2f); mBlip = ((BitmapDrawable)getResources().getDrawable(R.drawable.blip)).getBitmap(); } /** * Sets the target to track on the radar * @param latE6 Latitude of the target, multiplied by 1,000,000 * @param lonE6 Longitude of the target, multiplied by 1,000,000 */ public void setTarget(int latE6, int lonE6) { mTargetLat = latE6 / (double) GeoUtils.MILLION; mTargetLon = lonE6 / (double) GeoUtils.MILLION; } /** * Sets the view that we will use to report distance * * @param t The text view used to report distance */ public void setDistanceView(TextView t) { mDistanceView = t; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int center = getWidth() / 2; int radius = center - 8; // Draw the rings final Paint gridPaint = mGridPaint; canvas.drawCircle(center, center, radius, gridPaint); canvas.drawCircle(center, center, radius * 3 / 4, gridPaint); canvas.drawCircle(center, center, radius >> 1, gridPaint); canvas.drawCircle(center, center, radius >> 2, gridPaint); int blipRadius = (int) (mDistanceRatio * radius); final long now = SystemClock.uptimeMillis(); if (mSweepTime > 0 && mHaveLocation) { // Draw the sweep. Radius is determined by how long ago it started long sweepDifference = now - mSweepTime; if (sweepDifference < 512L) { int sweepRadius = (int) (((radius + 6) * sweepDifference) >> 9); canvas.drawCircle(center, center, sweepRadius, mSweepPaint0); canvas.drawCircle(center, center, sweepRadius - 2, mSweepPaint1); canvas.drawCircle(center, center, sweepRadius - 4, mSweepPaint2); // Note when the sweep has passed the blip boolean before = sweepRadius < blipRadius; if (!before && mSweepBefore) { mSweepBefore = false; mBlipTime = now; } } else { mSweepTime = now + 1000; mSweepBefore = true; } postInvalidate(); } // Draw horizontal and vertical lines canvas.drawLine(center, center - (radius >> 2) + 6, center, center - radius - 6, gridPaint); canvas.drawLine(center, center + (radius >> 2) - 6 , center, center + radius + 6, gridPaint); canvas.drawLine(center - (radius >> 2) + 6, center, center - radius - 6, center, gridPaint); canvas.drawLine(center + (radius >> 2) - 6, center, center + radius + 6, center, gridPaint); // Draw X in the center of the screen canvas.drawLine(center - 4, center - 4, center + 4, center + 4, gridPaint); canvas.drawLine(center - 4, center + 4, center + 4, center - 4, gridPaint); if (mHaveLocation) { double bearingToTarget = mBearing - mOrientation; double drawingAngle = Math.toRadians(bearingToTarget) - (Math.PI / 2); float cos = (float) Math.cos(drawingAngle); float sin = (float) Math.sin(drawingAngle); // Draw the text for the rings final String[] distanceScale = mDistanceScale; addText(canvas, distanceScale[0], center, center + (radius >> 2)); addText(canvas, distanceScale[1], center, center + (radius >> 1)); addText(canvas, distanceScale[2], center, center + radius * 3 / 4); addText(canvas, distanceScale[3], center, center + radius); // Draw the blip. Alpha is based on how long ago the sweep crossed the blip long blipDifference = now - mBlipTime; gridPaint.setAlpha(255 - (int)((128 * blipDifference) >> 10)); canvas.drawBitmap(mBlip, center + (cos * blipRadius) - 8 , center + (sin * blipRadius) - 8, gridPaint); gridPaint.setAlpha(255); } } private void addText(Canvas canvas, String str, int x, int y) { mGridPaint.getTextBounds(str, 0, str.length(), mTextBounds); mTextBounds.offset(x - (mTextBounds.width() >> 1), y); mTextBounds.inset(-2, -2); canvas.drawRect(mTextBounds, mErasePaint); canvas.drawText(str, x, y, mGridPaint); } public void onAccuracyChanged(int sensor, int accuracy) { } /** * Called when we get a new value from the compass * * @see android.hardware.SensorListener#onSensorChanged(int, float[]) */ public void onSensorChanged(int sensor, float[] values) { mOrientation = values[0]; postInvalidate(); } /** * Called when a location provider has a new location to report * * @see android.location.LocationListener#onLocationChanged(android.location.Location) */ public void onLocationChanged(Location location) { if (!mHaveLocation) { mHaveLocation = true; } final long now = SystemClock.uptimeMillis(); boolean useLocation = false; final String provider = location.getProvider(); if (LocationManager.GPS_PROVIDER.equals(provider)) { // Use GPS if available mLastGpsFixTime = SystemClock.uptimeMillis(); useLocation = true; } else if (LocationManager.NETWORK_PROVIDER.equals(provider)) { // Use network provider if GPS is getting stale useLocation = now - mLastGpsFixTime > RETAIN_GPS_MILLIS; if (mNetworkLocation == null) { mNetworkLocation = new Location(location); } else { mNetworkLocation.set(location); } mLastGpsFixTime = 0L; } if (useLocation) { mMyLocationLat = location.getLatitude(); mMyLocationLon = location.getLongitude(); mDistance = GeoUtils.distanceKm(mMyLocationLat, mMyLocationLon, mTargetLat, mTargetLon); mBearing = GeoUtils.bearing(mMyLocationLat, mMyLocationLon, mTargetLat, mTargetLon); updateDistance(mDistance); } } public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { } /** * Called when a location provider has changed its availability. * * @see android.location.LocationListener#onStatusChanged(java.lang.String, int, android.os.Bundle) */ public void onStatusChanged(String provider, int status, Bundle extras) { if (LocationManager.GPS_PROVIDER.equals(provider)) { switch (status) { case LocationProvider.AVAILABLE: mGpsAvailable = true; break; case LocationProvider.OUT_OF_SERVICE: case LocationProvider.TEMPORARILY_UNAVAILABLE: mGpsAvailable = false; if (mNetworkLocation != null && mNetworkAvailable) { // Fallback to network location mLastGpsFixTime = 0L; onLocationChanged(mNetworkLocation); } else { handleUnknownLocation(); } break; } } else if (LocationManager.NETWORK_PROVIDER.equals(provider)) { switch (status) { case LocationProvider.AVAILABLE: mNetworkAvailable = true; break; case LocationProvider.OUT_OF_SERVICE: case LocationProvider.TEMPORARILY_UNAVAILABLE: mNetworkAvailable = false; if (!mGpsAvailable) { handleUnknownLocation(); } break; } } } /** * Called when we no longer have a valid lcoation. */ private void handleUnknownLocation() { mHaveLocation = false; mDistanceView.setText(R.string.scanning); } /** * Update state to reflect whether we are using metric or standard units. * * @param useMetric True if the display should use metric units */ public void setUseMetric(boolean useMetric) { mUseMetric = useMetric; mLastScale = -1; if (mHaveLocation) { updateDistance(mDistance); } invalidate(); } /** * Update our state to reflect a new distance to the target. This may require * choosing a new scale for the radar rings. * * @param distanceKm The new distance to the target */ private void updateDistance(double distanceKm) { final double[] scaleChoices; final float[] displayUnitsPerKm; final String[] displayFormats; final String[] scaleFormats; String distanceStr = null; if (mUseMetric) { scaleChoices = mMetricScaleChoices; displayUnitsPerKm = mMetricDisplayUnitsPerKm; displayFormats = mMetricDisplayFormats; scaleFormats = mMetricScaleFormats; } else { scaleChoices = mEnglishScaleChoices; displayUnitsPerKm = mEnglishDisplayUnitsPerKm; displayFormats = mEnglishDisplayFormats; scaleFormats = mEnglishScaleFormats; } int count = scaleChoices.length; for (int i = 0; i < count; i++) { if (distanceKm < scaleChoices[i] || i == (count - 1)) { String format = displayFormats[i]; double distanceDisplay = distanceKm * displayUnitsPerKm[i]; if (mLastScale != i) { mLastScale = i; String scaleFormat = scaleFormats[i]; float scaleDistance = (float) (scaleChoices[i] * displayUnitsPerKm[i]); mDistanceScale[0] = String.format(scaleFormat, (scaleDistance / 4)); mDistanceScale[1] = String.format(scaleFormat, (scaleDistance / 2)); mDistanceScale[2] = String.format(scaleFormat, (scaleDistance * 3 / 4)); mDistanceScale[3] = String.format(scaleFormat, scaleDistance); } mDistanceRatio = (float) (mDistance / scaleChoices[mLastScale]); distanceStr = String.format(format, distanceDisplay); break; } } mDistanceView.setText(distanceStr); } /** * Turn on the sweep animation starting with the next draw */ public void startSweep() { mSweepTime = SystemClock.uptimeMillis(); mSweepBefore = true; } /** * Turn off the sweep animation */ public void stopSweep() { mSweepTime = 0L; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.radar; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.hardware.SensorManager; import android.location.LocationManager; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.widget.TextView; /** * Simple Activity wrapper that hosts a {@link RadarView} * */ public class RadarActivity extends Activity { private static final int LOCATION_UPDATE_INTERVAL_MILLIS = 1000; private static final int MENU_STANDARD = Menu.FIRST + 1; private static final int MENU_METRIC = Menu.FIRST + 2; private static final String RADAR = "radar"; private static final String PREF_METRIC = "metric"; private SensorManager mSensorManager; private RadarView mRadar; private LocationManager mLocationManager; private SharedPreferences mPrefs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.radar); mRadar = (RadarView) findViewById(R.id.radar); mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE); mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); // Metric or standard units? mPrefs = getSharedPreferences(RADAR, MODE_PRIVATE); boolean useMetric = mPrefs.getBoolean(PREF_METRIC, false); mRadar.setUseMetric(useMetric); // Read the target from our intent Intent i = getIntent(); int latE6 = (int)(i.getFloatExtra("latitude", 0) * GeoUtils.MILLION); int lonE6 = (int)(i.getFloatExtra("longitude", 0) * GeoUtils.MILLION); mRadar.setTarget(latE6, lonE6); mRadar.setDistanceView((TextView) findViewById(R.id.distance)); } @Override protected void onResume() { super.onResume(); mSensorManager.registerListener(mRadar, SensorManager.SENSOR_ORIENTATION, SensorManager.SENSOR_DELAY_GAME); // Start animating the radar screen mRadar.startSweep(); // Register for location updates mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_UPDATE_INTERVAL_MILLIS, 1, mRadar); mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_UPDATE_INTERVAL_MILLIS, 1, mRadar); } @Override protected void onPause() { mSensorManager.unregisterListener(mRadar); mLocationManager.removeUpdates(mRadar); // Stop animating the radar screen mRadar.stopSweep(); super.onStop(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_STANDARD, 0, R.string.menu_standard) .setIcon(R.drawable.ic_menu_standard) .setAlphabeticShortcut('A'); menu.add(0, MENU_METRIC, 0, R.string.menu_metric) .setIcon(R.drawable.ic_menu_metric) .setAlphabeticShortcut('C'); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_STANDARD: { setUseMetric(false); return true; } case MENU_METRIC: { setUseMetric(true); return true; } } return super.onOptionsItemSelected(item); } private void setUseMetric(boolean useMetric) { SharedPreferences.Editor e = mPrefs.edit(); e.putBoolean(PREF_METRIC, useMetric); e.commit(); mRadar.setUseMetric(useMetric); } }
Java
/* * 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.panoramio; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; /** * Utilities for loading a bitmap from a URL * */ public class BitmapUtils { private static final String TAG = "Panoramio"; private static final int IO_BUFFER_SIZE = 4 * 1024; /** * Loads a bitmap from the specified url. This can take a while, so it should not * be called from the UI thread. * * @param url The location of the bitmap asset * * @return The bitmap, or null if it could not be loaded */ public static Bitmap loadBitmap(String url) { Bitmap bitmap = null; InputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE); 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) { Log.e(TAG, "Could not load Bitmap from: " + url); } finally { closeStream(in); closeStream(out); } return bitmap; } /** * 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(TAG, "Could not close stream", e); } } } /** * 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); } } }
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.panoramio; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.database.DataSetObserver; import android.graphics.Bitmap; import android.os.Handler; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.ref.WeakReference; import java.net.URI; import java.util.ArrayList; /** * This class is responsible for downloading and parsing the search results for * a particular area. All of the work is done on a separate thread, and progress * is reported back through the DataSetObserver set in * {@link #addObserver(DataSetObserver). State is held in memory by in memory * maintained by a single instance of the ImageManager class. */ public class ImageManager { private static final String TAG = "Panoramio"; /** * Base URL for Panoramio's web API */ private static final String THUMBNAIL_URL = "//www.panoramio.com/map/get_panoramas.php?order=popularity&set=public&from=0&to=20&miny=%f&minx=%f&maxy=%f&maxx=%f&size=thumbnail"; /** * Used to post results back to the UI thread */ private Handler mHandler = new Handler(); /** * Holds the single instance of a ImageManager that is shared by the process. */ private static ImageManager sInstance; /** * Holds the images and related data that have been downloaded */ private ArrayList<PanoramioItem> mImages = new ArrayList<PanoramioItem>(); /** * Observers interested in changes to the current search results */ private ArrayList<WeakReference<DataSetObserver>> mObservers = new ArrayList<WeakReference<DataSetObserver>>(); /** * True if we are in the process of loading */ private boolean mLoading; private Context mContext; /** * Key for an Intent extra. The value is the zoom level selected by the user. */ public static final String ZOOM_EXTRA = "zoom"; /** * Key for an Intent extra. The value is the latitude of the center of the search * area chosen by the user. */ public static final String LATITUDE_E6_EXTRA = "latitudeE6"; /** * Key for an Intent extra. The value is the latitude of the center of the search * area chosen by the user. */ public static final String LONGITUDE_E6_EXTRA = "longitudeE6"; /** * Key for an Intent extra. The value is an item to display */ public static final String PANORAMIO_ITEM_EXTRA = "item"; public static ImageManager getInstance(Context c) { if (sInstance == null) { sInstance = new ImageManager(c.getApplicationContext()); } return sInstance; } private ImageManager(Context c) { mContext = c; } /** * @return True if we are still loading content */ public boolean isLoading() { return mLoading; } /** * Clear all downloaded content */ public void clear() { mImages.clear(); notifyObservers(); } /** * Add an item to and notify observers of the change. * @param item The item to add */ private void add(PanoramioItem item) { mImages.add(item); notifyObservers(); } /** * @return The number of items displayed so far */ public int size() { return mImages.size(); } /** * Gets the item at the specified position */ public PanoramioItem get(int position) { return mImages.get(position); } /** * Adds an observer to be notified when the set of items held by this ImageManager changes. */ public void addObserver(DataSetObserver observer) { WeakReference<DataSetObserver> obs = new WeakReference<DataSetObserver>(observer); mObservers.add(obs); } /** * Load a new set of search results for the specified area. * * @param minLong The minimum longitude for the search area * @param maxLong The maximum longitude for the search area * @param minLat The minimum latitude for the search area * @param maxLat The minimum latitude for the search area */ public void load(float minLong, float maxLong, float minLat, float maxLat) { mLoading = true; new NetworkThread(minLong, maxLong, minLat, maxLat).start(); } /** * Called when something changes in our data set. Cleans up any weak references that * are no longer valid along the way. */ private void notifyObservers() { final ArrayList<WeakReference<DataSetObserver>> observers = mObservers; final int count = observers.size(); for (int i = count - 1; i >= 0; i--) { WeakReference<DataSetObserver> weak = observers.get(i); DataSetObserver obs = weak.get(); if (obs != null) { obs.onChanged(); } else { observers.remove(i); } } } /** * This thread does the actual work of downloading and parsing data. * */ private class NetworkThread extends Thread { private float mMinLong; private float mMaxLong; private float mMinLat; private float mMaxLat; public NetworkThread(float minLong, float maxLong, float minLat, float maxLat) { mMinLong = minLong; mMaxLong = maxLong; mMinLat = minLat; mMaxLat = maxLat; } @Override public void run() { String url = THUMBNAIL_URL; url = String.format(url, mMinLat, mMinLong, mMaxLat, mMaxLong); try { URI uri = new URI("http", url, null); HttpGet get = new HttpGet(uri); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); String str = convertStreamToString(entity.getContent()); JSONObject json = new JSONObject(str); parse(json); } catch (Exception e) { Log.e(TAG, e.toString()); } } private void parse(JSONObject json) { try { JSONArray array = json.getJSONArray("photos"); int count = array.length(); for (int i = 0; i < count; i++) { JSONObject obj = array.getJSONObject(i); long id = obj.getLong("photo_id"); String title = obj.getString("photo_title"); String owner = obj.getString("owner_name"); String thumb = obj.getString("photo_file_url"); String ownerUrl = obj.getString("owner_url"); String photoUrl = obj.getString("photo_url"); double latitude = obj.getDouble("latitude"); double longitude = obj.getDouble("longitude"); Bitmap b = BitmapUtils.loadBitmap(thumb); if (title == null) { title = mContext.getString(R.string.untitled); } final PanoramioItem item = new PanoramioItem(id, thumb, b, (int) (latitude * Panoramio.MILLION), (int) (longitude * Panoramio.MILLION), title, owner, ownerUrl, photoUrl); final boolean done = i == count - 1; mHandler.post(new Runnable() { public void run() { sInstance.mLoading = !done; sInstance.add(item); } }); } } catch (JSONException e) { Log.e(TAG, e.toString()); } } private String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8*1024); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } } }
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.panoramio; import com.google.android.maps.GeoPoint; import android.graphics.Bitmap; import android.os.Parcel; import android.os.Parcelable; /** * Holds one item returned from the Panoramio server. This includes * the bitmap along with other meta info. * */ public class PanoramioItem implements Parcelable { private long mId; private Bitmap mBitmap; private GeoPoint mLocation; private String mTitle; private String mOwner; private String mThumbUrl; private String mOwnerUrl; private String mPhotoUrl; public PanoramioItem(Parcel in) { mId = in.readLong(); mBitmap = Bitmap.CREATOR.createFromParcel(in); mLocation = new GeoPoint(in.readInt(), in.readInt()); mTitle = in.readString(); mOwner = in.readString(); mThumbUrl = in.readString(); mOwnerUrl = in.readString(); mPhotoUrl = in.readString(); } public PanoramioItem(long id, String thumbUrl, Bitmap b, int latitudeE6, int longitudeE6, String title, String owner, String ownerUrl, String photoUrl) { mBitmap = b; mLocation = new GeoPoint(latitudeE6, longitudeE6); mTitle = title; mOwner = owner; mThumbUrl = thumbUrl; mOwnerUrl = ownerUrl; mPhotoUrl = photoUrl; } public long getId() { return mId; } public Bitmap getBitmap() { return mBitmap; } public GeoPoint getLocation() { return mLocation; } public String getTitle() { return mTitle; } public String getOwner() { return mOwner; } public String getThumbUrl() { return mThumbUrl; } public String getOwnerUrl() { return mOwnerUrl; } public String getPhotoUrl() { return mPhotoUrl; } public static final Parcelable.Creator<PanoramioItem> CREATOR = new Parcelable.Creator<PanoramioItem>() { public PanoramioItem createFromParcel(Parcel in) { return new PanoramioItem(in); } public PanoramioItem[] newArray(int size) { return new PanoramioItem[size]; } }; public int describeContents() { return 0; } public void writeToParcel(Parcel parcel, int flags) { parcel.writeLong(mId); mBitmap.writeToParcel(parcel, 0); parcel.writeInt(mLocation.getLatitudeE6()); parcel.writeInt(mLocation.getLongitudeE6()); parcel.writeString(mTitle); parcel.writeString(mOwner); parcel.writeString(mThumbUrl); parcel.writeString(mOwnerUrl); parcel.writeString(mPhotoUrl); } }
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.panoramio; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.database.DataSetObserver; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.widget.ListView; /** * Activity which displays the list of images. */ public class ImageList extends ListActivity { ImageManager mImageManager; private MyDataSetObserver mObserver = new MyDataSetObserver(); /** * The zoom level the user chose when picking the search area */ private int mZoom; /** * The latitude of the center of the search area chosen by the user */ private int mLatitudeE6; /** * The longitude of the center of the search area chosen by the user */ private int mLongitudeE6; /** * Observer used to turn the progress indicator off when the {@link ImageManager} is * done downloading. */ private class MyDataSetObserver extends DataSetObserver { @Override public void onChanged() { if (!mImageManager.isLoading()) { getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, Window.PROGRESS_VISIBILITY_OFF); } } @Override public void onInvalidated() { } } @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(savedInstanceState); mImageManager = ImageManager.getInstance(this); ListView listView = getListView(); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View footer = inflater.inflate(R.layout.list_footer, listView, false); listView.addFooterView(footer, null, false); setListAdapter(new ImageAdapter(this)); // Theme.Light sets a background on our list. listView.setBackgroundDrawable(null); if (mImageManager.isLoading()) { getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, Window.PROGRESS_VISIBILITY_ON); mImageManager.addObserver(mObserver); } // Read the user's search area from the intent Intent i = getIntent(); mZoom = i.getIntExtra(ImageManager.ZOOM_EXTRA, Integer.MIN_VALUE); mLatitudeE6 = i.getIntExtra(ImageManager.LATITUDE_E6_EXTRA, Integer.MIN_VALUE); mLongitudeE6 = i.getIntExtra(ImageManager.LONGITUDE_E6_EXTRA, Integer.MIN_VALUE); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { PanoramioItem item = mImageManager.get(position); // Create an intent to show a particular item. // Pass the user's search area along so the next activity can use it Intent i = new Intent(this, ViewImage.class); i.putExtra(ImageManager.PANORAMIO_ITEM_EXTRA, item); i.putExtra(ImageManager.ZOOM_EXTRA, mZoom); i.putExtra(ImageManager.LATITUDE_E6_EXTRA, mLatitudeE6); i.putExtra(ImageManager.LONGITUDE_E6_EXTRA, mLongitudeE6); startActivity(i); } }
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.panoramio; import com.google.android.maps.GeoPoint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.ImageView; import android.widget.TextView; /** * Activity which displays a single image. */ public class ViewImage extends Activity { private static final String TAG = "Panoramio"; private static final int MENU_RADAR = Menu.FIRST + 1; private static final int MENU_MAP = Menu.FIRST + 2; private static final int MENU_AUTHOR = Menu.FIRST + 3; private static final int MENU_VIEW = Menu.FIRST + 4; private static final int DIALOG_NO_RADAR = 1; PanoramioItem mItem; private Handler mHandler; private ImageView mImage; private TextView mTitle; private TextView mOwner; private View mContent; private int mMapZoom; private int mMapLatitudeE6; private int mMapLongitudeE6; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(savedInstanceState); setContentView(R.layout.view_image); // Remember the user's original search area and zoom level Intent i = getIntent(); mItem = i.getParcelableExtra(ImageManager.PANORAMIO_ITEM_EXTRA); mMapZoom = i.getIntExtra(ImageManager.ZOOM_EXTRA, Integer.MIN_VALUE); mMapLatitudeE6 = i.getIntExtra(ImageManager.LATITUDE_E6_EXTRA, Integer.MIN_VALUE); mMapLongitudeE6 = i.getIntExtra(ImageManager.LONGITUDE_E6_EXTRA, Integer.MIN_VALUE); mHandler = new Handler(); mContent = findViewById(R.id.content); mImage = (ImageView) findViewById(R.id.image); mTitle = (TextView) findViewById(R.id.title); mOwner = (TextView) findViewById(R.id.owner); mContent.setVisibility(View.GONE); getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, Window.PROGRESS_VISIBILITY_ON); new LoadThread().start(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_RADAR, 0, R.string.menu_radar) .setIcon(R.drawable.ic_menu_radar) .setAlphabeticShortcut('R'); menu.add(0, MENU_MAP, 0, R.string.menu_map) .setIcon(R.drawable.ic_menu_map) .setAlphabeticShortcut('M'); menu.add(0, MENU_AUTHOR, 0, R.string.menu_author) .setIcon(R.drawable.ic_menu_author) .setAlphabeticShortcut('A'); menu.add(0, MENU_VIEW, 0, R.string.menu_view) .setIcon(android.R.drawable.ic_menu_view) .setAlphabeticShortcut('V'); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_RADAR: { // Launch the radar activity (if it is installed) Intent i = new Intent("com.google.android.radar.SHOW_RADAR"); GeoPoint location = mItem.getLocation(); i.putExtra("latitude", (float)(location.getLatitudeE6() / 1000000f)); i.putExtra("longitude", (float)(location.getLongitudeE6() / 1000000f)); try { startActivity(i); } catch (ActivityNotFoundException ex) { showDialog(DIALOG_NO_RADAR); } return true; } case MENU_MAP: { // Display our custom map Intent i = new Intent(this, ViewMap.class); i.putExtra(ImageManager.PANORAMIO_ITEM_EXTRA, mItem); i.putExtra(ImageManager.ZOOM_EXTRA, mMapZoom); i.putExtra(ImageManager.LATITUDE_E6_EXTRA, mMapLatitudeE6); i.putExtra(ImageManager.LONGITUDE_E6_EXTRA, mMapLongitudeE6); startActivity(i); return true; } case MENU_AUTHOR: { // Display the author info page in the browser Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(mItem.getOwnerUrl())); startActivity(i); return true; } case MENU_VIEW: { // Display the photo info page in the browser Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(mItem.getPhotoUrl())); startActivity(i); return true; } } return super.onOptionsItemSelected(item); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_NO_RADAR: AlertDialog.Builder builder = new AlertDialog.Builder(this); return builder.setTitle(R.string.no_radar_title) .setMessage(R.string.no_radar) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.ok, null).create(); } return null; } /** * Utility to load a larger version of the image in a separate thread. * */ private class LoadThread extends Thread { public LoadThread() { } @Override public void run() { try { String uri = mItem.getThumbUrl(); uri = uri.replace("thumbnail", "medium"); final Bitmap b = BitmapUtils.loadBitmap(uri); mHandler.post(new Runnable() { public void run() { mImage.setImageBitmap(b); mTitle.setText(mItem.getTitle()); mOwner.setText(mItem.getOwner()); mContent.setVisibility(View.VISIBLE); getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, Window.PROGRESS_VISIBILITY_OFF); } }); } catch (Exception e) { Log.e(TAG, e.toString()); } } } }
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.panoramio; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.android.maps.Overlay; import com.google.android.maps.Projection; import android.content.Intent; import android.graphics.Canvas; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.FrameLayout; import java.util.ArrayList; import java.util.List; /** * Displays a custom map which shows our current location and the location * where the photo was taken. */ public class ViewMap extends MapActivity { private MapView mMapView; private MyLocationOverlay mMyLocationOverlay; ArrayList<PanoramioItem> mItems = null; private PanoramioItem mItem; private Drawable mMarker; private int mMarkerXOffset; private int mMarkerYOffset; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FrameLayout frame = new FrameLayout(this); mMapView = new MapView(this, "MapViewCompassDemo_DummyAPIKey"); frame.addView(mMapView, new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); setContentView(frame); mMyLocationOverlay = new MyLocationOverlay(this, mMapView); mMarker = getResources().getDrawable(R.drawable.map_pin); // Make sure to give mMarker bounds so it will draw in the overlay final int intrinsicWidth = mMarker.getIntrinsicWidth(); final int intrinsicHeight = mMarker.getIntrinsicHeight(); mMarker.setBounds(0, 0, intrinsicWidth, intrinsicHeight); mMarkerXOffset = -(intrinsicWidth / 2); mMarkerYOffset = -intrinsicHeight; // Read the item we are displaying from the intent, along with the // parameters used to set up the map Intent i = getIntent(); mItem = i.getParcelableExtra(ImageManager.PANORAMIO_ITEM_EXTRA); int mapZoom = i.getIntExtra(ImageManager.ZOOM_EXTRA, Integer.MIN_VALUE); int mapLatitudeE6 = i.getIntExtra(ImageManager.LATITUDE_E6_EXTRA, Integer.MIN_VALUE); int mapLongitudeE6 = i.getIntExtra(ImageManager.LONGITUDE_E6_EXTRA, Integer.MIN_VALUE); final List<Overlay> overlays = mMapView.getOverlays(); overlays.add(mMyLocationOverlay); overlays.add(new PanoramioOverlay()); final MapController controller = mMapView.getController(); if (mapZoom != Integer.MIN_VALUE && mapLatitudeE6 != Integer.MIN_VALUE && mapLongitudeE6 != Integer.MIN_VALUE) { controller.setZoom(mapZoom); controller.setCenter(new GeoPoint(mapLatitudeE6, mapLongitudeE6)); } else { controller.setZoom(15); mMyLocationOverlay.runOnFirstFix(new Runnable() { public void run() { controller.animateTo(mMyLocationOverlay.getMyLocation()); } }); } mMapView.setClickable(true); mMapView.setEnabled(true); mMapView.setSatellite(true); addZoomControls(frame); } @Override protected void onResume() { super.onResume(); mMyLocationOverlay.enableMyLocation(); } @Override protected void onStop() { mMyLocationOverlay.disableMyLocation(); super.onStop(); } /** * Get the zoom controls and add them to the bottom of the map */ private void addZoomControls(FrameLayout frame) { View zoomControls = mMapView.getZoomControls(); FrameLayout.LayoutParams p = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM + Gravity.CENTER_HORIZONTAL); frame.addView(zoomControls, p); } @Override protected boolean isRouteDisplayed() { return false; } /** * Custom overlay to display the Panoramio pushpin */ public class PanoramioOverlay extends Overlay { @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { if (!shadow) { Point point = new Point(); Projection p = mapView.getProjection(); p.toPixels(mItem.getLocation(), point); super.draw(canvas, mapView, shadow); drawAt(canvas, mMarker, point.x + mMarkerXOffset, point.y + mMarkerYOffset, shadow); } } } }
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.panoramio; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import android.content.Intent; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.FrameLayout; /** * Activity which lets the user select a search area * */ public class Panoramio extends MapActivity implements OnClickListener { private MapView mMapView; private MyLocationOverlay mMyLocationOverlay; private ImageManager mImageManager; public static final int MILLION = 1000000; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mImageManager = ImageManager.getInstance(this); FrameLayout frame = (FrameLayout) findViewById(R.id.frame); Button goButton = (Button) findViewById(R.id.go); goButton.setOnClickListener(this); // Add the map view to the frame mMapView = new MapView(this, "Panoramio_DummyAPIKey"); frame.addView(mMapView, new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); // Create an overlay to show current location mMyLocationOverlay = new MyLocationOverlay(this, mMapView); mMyLocationOverlay.runOnFirstFix(new Runnable() { public void run() { mMapView.getController().animateTo(mMyLocationOverlay.getMyLocation()); }}); mMapView.getOverlays().add(mMyLocationOverlay); mMapView.getController().setZoom(15); mMapView.setClickable(true); mMapView.setEnabled(true); mMapView.setSatellite(true); addZoomControls(frame); } @Override protected void onResume() { super.onResume(); mMyLocationOverlay.enableMyLocation(); } @Override protected void onStop() { mMyLocationOverlay.disableMyLocation(); super.onStop(); } /** * Add zoom controls to our frame layout */ private void addZoomControls(FrameLayout frame) { // Get the zoom controls and add them to the bottom of the map View zoomControls = mMapView.getZoomControls(); FrameLayout.LayoutParams p = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM + Gravity.CENTER_HORIZONTAL); frame.addView(zoomControls, p); } @Override protected boolean isRouteDisplayed() { return false; } /** * Starts a new search when the user clicks the search button. */ public void onClick(View view) { // Get the search area int latHalfSpan = mMapView.getLatitudeSpan() >> 1; int longHalfSpan = mMapView.getLongitudeSpan() >> 1; // Remember how the map was displayed so we can show it the same way later GeoPoint center = mMapView.getMapCenter(); int zoom = mMapView.getZoomLevel(); int latitudeE6 = center.getLatitudeE6(); int longitudeE6 = center.getLongitudeE6(); Intent i = new Intent(this, ImageList.class); i.putExtra(ImageManager.ZOOM_EXTRA, zoom); i.putExtra(ImageManager.LATITUDE_E6_EXTRA, latitudeE6); i.putExtra(ImageManager.LONGITUDE_E6_EXTRA, longitudeE6); float minLong = ((float) (longitudeE6 - longHalfSpan)) / MILLION; float maxLong = ((float) (longitudeE6 + longHalfSpan)) / MILLION; float minLat = ((float) (latitudeE6 - latHalfSpan)) / MILLION; float maxLat = ((float) (latitudeE6 + latHalfSpan)) / MILLION; mImageManager.clear(); // Start downloading mImageManager.load(minLong, maxLong, minLat, maxLat); // Show results startActivity(i); } }
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.panoramio; import android.content.Context; import android.database.DataSetObserver; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; /** * Adapter used to bind data for the main list of photos */ public class ImageAdapter extends BaseAdapter { /** * Maintains the state of our data */ private ImageManager mImageManager; private Context mContext; private MyDataSetObserver mObserver; /** * Used by the {@link ImageManager} to report changes in the list back to * this adapter. */ private class MyDataSetObserver extends DataSetObserver { @Override public void onChanged() { notifyDataSetChanged(); } @Override public void onInvalidated() { notifyDataSetInvalidated(); } } public ImageAdapter(Context c) { mImageManager = ImageManager.getInstance(c); mContext = c; mObserver = new MyDataSetObserver(); mImageManager.addObserver(mObserver); } /** * Returns the number of images to display * * @see android.widget.Adapter#getCount() */ public int getCount() { return mImageManager.size(); } /** * Returns the image at a specified position * * @see android.widget.Adapter#getItem(int) */ public Object getItem(int position) { return mImageManager.get(position); } /** * Returns the id of an image at a specified position * * @see android.widget.Adapter#getItemId(int) */ public long getItemId(int position) { PanoramioItem s = mImageManager.get(position); return s.getId(); } /** * Returns a view to display the image at a specified position * * @param position The position to display * @param convertView An existing view that we can reuse. May be null. * @param parent The parent view that will eventually hold the view we return. * @return A view to display the image at a specified position */ public View getView(int position, View convertView, ViewGroup parent) { View view; if (convertView == null) { // Make up a new view LayoutInflater inflater = (LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.image_item, null); } else { // Use convertView if it is available view = convertView; } PanoramioItem s = mImageManager.get(position); ImageView i = (ImageView) view.findViewById(R.id.image); i.setImageBitmap(s.getBitmap()); i.setBackgroundResource(R.drawable.picture_frame); TextView t = (TextView) view.findViewById(R.id.title); t.setText(s.getTitle()); t = (TextView) view.findViewById(R.id.owner); t.setText(s.getOwner()); return view; } }
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.android.lolcat; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; /** * Lolcat builder activity. * * Instructions: * (1) Take photo of cat using Camera * (2) Run LolcatActivity * (3) Pick photo * (4) Add caption(s) * (5) Save and share * * See README.txt for a list of currently-missing features and known bugs. */ public class LolcatActivity extends Activity implements View.OnClickListener { private static final String TAG = "LolcatActivity"; // Location on the SD card for saving lolcat images private static final String LOLCAT_SAVE_DIRECTORY = "lolcats/"; // Mime type / format / extension we use (must be self-consistent!) private static final String SAVED_IMAGE_EXTENSION = ".png"; private static final Bitmap.CompressFormat SAVED_IMAGE_COMPRESS_FORMAT = Bitmap.CompressFormat.PNG; private static final String SAVED_IMAGE_MIME_TYPE = "image/png"; // UI Elements private Button mPickButton; private Button mCaptionButton; private Button mSaveButton; private Button mClearCaptionButton; private Button mClearPhotoButton; private LolcatView mLolcatView; private AlertDialog mCaptionDialog; private ProgressDialog mSaveProgressDialog; private AlertDialog mSaveSuccessDialog; private Handler mHandler; private Uri mPhotoUri; private String mSavedImageFilename; private Uri mSavedImageUri; private MediaScannerConnection mMediaScannerConnection; // Request codes used with startActivityForResult() private static final int PHOTO_PICKED = 1; // Dialog IDs private static final int DIALOG_CAPTION = 1; private static final int DIALOG_SAVE_PROGRESS = 2; private static final int DIALOG_SAVE_SUCCESS = 3; // Keys used with onSaveInstanceState() private static final String PHOTO_URI_KEY = "photo_uri"; private static final String SAVED_IMAGE_FILENAME_KEY = "saved_image_filename"; private static final String SAVED_IMAGE_URI_KEY = "saved_image_uri"; private static final String TOP_CAPTION_KEY = "top_caption"; private static final String BOTTOM_CAPTION_KEY = "bottom_caption"; private static final String CAPTION_POSITIONS_KEY = "caption_positions"; @Override protected void onCreate(Bundle icicle) { Log.i(TAG, "onCreate()... icicle = " + icicle); super.onCreate(icicle); setContentView(R.layout.lolcat_activity); // Look up various UI elements mPickButton = (Button) findViewById(R.id.pick_button); mPickButton.setOnClickListener(this); mCaptionButton = (Button) findViewById(R.id.caption_button); mCaptionButton.setOnClickListener(this); mSaveButton = (Button) findViewById(R.id.save_button); mSaveButton.setOnClickListener(this); mClearCaptionButton = (Button) findViewById(R.id.clear_caption_button); // This button doesn't exist in portrait mode. if (mClearCaptionButton != null) mClearCaptionButton.setOnClickListener(this); mClearPhotoButton = (Button) findViewById(R.id.clear_photo_button); mClearPhotoButton.setOnClickListener(this); mLolcatView = (LolcatView) findViewById(R.id.main_image); // Need one of these to call back to the UI thread // (and run AlertDialog.show(), for that matter) mHandler = new Handler(); mMediaScannerConnection = new MediaScannerConnection(this, mMediaScanConnClient); if (icicle != null) { Log.i(TAG, "- reloading state from icicle!"); restoreStateFromIcicle(icicle); } } @Override protected void onResume() { Log.i(TAG, "onResume()..."); super.onResume(); updateButtons(); } @Override protected void onSaveInstanceState(Bundle outState) { Log.i(TAG, "onSaveInstanceState()..."); super.onSaveInstanceState(outState); // State from the Activity: outState.putParcelable(PHOTO_URI_KEY, mPhotoUri); outState.putString(SAVED_IMAGE_FILENAME_KEY, mSavedImageFilename); outState.putParcelable(SAVED_IMAGE_URI_KEY, mSavedImageUri); // State from the LolcatView: // (TODO: Consider making Caption objects, or even the LolcatView // itself, Parcelable? Probably overkill, though...) outState.putString(TOP_CAPTION_KEY, mLolcatView.getTopCaption()); outState.putString(BOTTOM_CAPTION_KEY, mLolcatView.getBottomCaption()); outState.putIntArray(CAPTION_POSITIONS_KEY, mLolcatView.getCaptionPositions()); } /** * Restores the activity state from the specified icicle. * @see onCreate() * @see onSaveInstanceState() */ private void restoreStateFromIcicle(Bundle icicle) { Log.i(TAG, "restoreStateFromIcicle()..."); // State of the Activity: Uri photoUri = icicle.getParcelable(PHOTO_URI_KEY); Log.i(TAG, " - photoUri: " + photoUri); if (photoUri != null) { loadPhoto(photoUri); } mSavedImageFilename = icicle.getString(SAVED_IMAGE_FILENAME_KEY); mSavedImageUri = icicle.getParcelable(SAVED_IMAGE_URI_KEY); // State of the LolcatView: String topCaption = icicle.getString(TOP_CAPTION_KEY); String bottomCaption = icicle.getString(BOTTOM_CAPTION_KEY); int[] captionPositions = icicle.getIntArray(CAPTION_POSITIONS_KEY); Log.i(TAG, " - captions: '" + topCaption + "', '" + bottomCaption + "'"); if (!TextUtils.isEmpty(topCaption) || !TextUtils.isEmpty(bottomCaption)) { mLolcatView.setCaptions(topCaption, bottomCaption); mLolcatView.setCaptionPositions(captionPositions); } } @Override protected void onDestroy() { Log.i(TAG, "onDestroy()..."); super.onDestroy(); clearPhoto(); // Free up some resources, and force a GC } // View.OnClickListener implementation public void onClick(View view) { int id = view.getId(); Log.i(TAG, "onClick(View " + view + ", id " + id + ")..."); switch (id) { case R.id.pick_button: Log.i(TAG, "onClick: pick_button..."); Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); intent.setType("image/*"); // Note: we could have the "crop" UI come up here by // default by doing this: // intent.putExtra("crop", "true"); // (But watch out: if you do that, the Intent that comes // back to onActivityResult() will have the URI (of the // cropped image) in the "action" field, not the "data" // field!) startActivityForResult(intent, PHOTO_PICKED); break; case R.id.caption_button: Log.i(TAG, "onClick: caption_button..."); showCaptionDialog(); break; case R.id.save_button: Log.i(TAG, "onClick: save_button..."); saveImage(); break; case R.id.clear_caption_button: Log.i(TAG, "onClick: clear_caption_button..."); clearCaptions(); updateButtons(); break; case R.id.clear_photo_button: Log.i(TAG, "onClick: clear_photo_button..."); clearPhoto(); // Also does clearCaptions() updateButtons(); break; default: Log.w(TAG, "Click from unexpected source: " + view + ", id " + id); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.i(TAG, "onActivityResult(request " + requestCode + ", result " + resultCode + ", data " + data + ")..."); if (resultCode != RESULT_OK) { Log.i(TAG, "==> result " + resultCode + " from subactivity! Ignoring..."); Toast t = Toast.makeText(this, R.string.lolcat_nothing_picked, Toast.LENGTH_SHORT); t.show(); return; } if (requestCode == PHOTO_PICKED) { // "data" is an Intent containing (presumably) a URI like // "content://media/external/images/media/3". if (data == null) { Log.w(TAG, "Null data, but RESULT_OK, from image picker!"); Toast t = Toast.makeText(this, R.string.lolcat_nothing_picked, Toast.LENGTH_SHORT); t.show(); return; } if (data.getData() == null) { Log.w(TAG, "'data' intent from image picker contained no data!"); Toast t = Toast.makeText(this, R.string.lolcat_nothing_picked, Toast.LENGTH_SHORT); t.show(); return; } loadPhoto(data.getData()); updateButtons(); } } /** * Updates the enabled/disabled state of the onscreen buttons. */ private void updateButtons() { Log.i(TAG, "updateButtons()..."); // mPickButton is always enabled. // Do we have a valid photo and/or caption(s) yet? Drawable d = mLolcatView.getDrawable(); // Log.i(TAG, "===> current mLolcatView drawable: " + d); boolean validPhoto = (d != null); boolean validCaption = mLolcatView.hasValidCaption(); mCaptionButton.setText(validCaption ? R.string.lolcat_change_captions : R.string.lolcat_add_captions); mCaptionButton.setEnabled(validPhoto); mSaveButton.setEnabled(validPhoto && validCaption); if (mClearCaptionButton != null) { mClearCaptionButton.setEnabled(validPhoto && validCaption); } mClearPhotoButton.setEnabled(validPhoto); } /** * Clears out any already-entered captions for this lolcat. */ private void clearCaptions() { mLolcatView.clearCaptions(); // Clear the text fields in the caption dialog too. if (mCaptionDialog != null) { EditText topText = (EditText) mCaptionDialog.findViewById(R.id.top_edittext); topText.setText(""); EditText bottomText = (EditText) mCaptionDialog.findViewById(R.id.bottom_edittext); bottomText.setText(""); topText.requestFocus(); } // This also invalidates any image we've previously written to the // SD card... mSavedImageFilename = null; mSavedImageUri = null; } /** * Completely resets the UI to its initial state, with no photo * loaded, and no captions. */ private void clearPhoto() { mLolcatView.clear(); mPhotoUri = null; mSavedImageFilename = null; mSavedImageUri = null; clearCaptions(); // Force a gc (to be sure to reclaim the memory used by our // potentially huge bitmap): System.gc(); } /** * Loads the image with the specified Uri into the UI. */ private void loadPhoto(Uri uri) { Log.i(TAG, "loadPhoto: uri = " + uri); clearPhoto(); // Be sure to release the previous bitmap // before creating another one mPhotoUri = uri; // A new photo always starts out uncaptioned. clearCaptions(); // Load the selected photo into our ImageView. mLolcatView.loadFromUri(mPhotoUri); } private void showCaptionDialog() { // If the dialog already exists, always reset focus to the top // item each time it comes up. if (mCaptionDialog != null) { EditText topText = (EditText) mCaptionDialog.findViewById(R.id.top_edittext); topText.requestFocus(); } showDialog(DIALOG_CAPTION); } private void showSaveSuccessDialog() { // If the dialog already exists, update the body text based on the // current values of mSavedImageFilename and mSavedImageUri // (otherwise the dialog will still have the body text from when // it was first created!) if (mSaveSuccessDialog != null) { updateSaveSuccessDialogBody(); } showDialog(DIALOG_SAVE_SUCCESS); } private void updateSaveSuccessDialogBody() { if (mSaveSuccessDialog == null) { throw new IllegalStateException( "updateSaveSuccessDialogBody: mSaveSuccessDialog hasn't been created yet"); } String dialogBody = String.format( getResources().getString(R.string.lolcat_save_succeeded_dialog_body_format), mSavedImageFilename, mSavedImageUri); mSaveSuccessDialog.setMessage(dialogBody); } @Override protected Dialog onCreateDialog(int id) { Log.i(TAG, "onCreateDialog(id " + id + ")..."); // This is only run once (per dialog), the very first time // a given dialog needs to be shown. switch (id) { case DIALOG_CAPTION: LayoutInflater factory = LayoutInflater.from(this); final View textEntryView = factory.inflate(R.layout.lolcat_caption_dialog, null); mCaptionDialog = new AlertDialog.Builder(this) .setTitle(R.string.lolcat_caption_dialog_title) .setIcon(0) .setView(textEntryView) .setPositiveButton( R.string.lolcat_caption_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Caption dialog: OK..."); updateCaptionsFromDialog(); } }) .setNegativeButton( R.string.lolcat_caption_dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Caption dialog: CANCEL..."); // Nothing to do here (for now at least) } }) .create(); return mCaptionDialog; case DIALOG_SAVE_PROGRESS: mSaveProgressDialog = new ProgressDialog(this); mSaveProgressDialog.setMessage(getResources().getString(R.string.lolcat_saving)); mSaveProgressDialog.setIndeterminate(true); mSaveProgressDialog.setCancelable(false); return mSaveProgressDialog; case DIALOG_SAVE_SUCCESS: mSaveSuccessDialog = new AlertDialog.Builder(this) .setTitle(R.string.lolcat_save_succeeded_dialog_title) .setIcon(0) .setPositiveButton( R.string.lolcat_save_succeeded_dialog_view, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Save dialog: View..."); viewSavedImage(); } }) .setNeutralButton( R.string.lolcat_save_succeeded_dialog_share, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Save dialog: Share..."); shareSavedImage(); } }) .setNegativeButton( R.string.lolcat_save_succeeded_dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Save dialog: CANCEL..."); // Nothing to do here... } }) .create(); updateSaveSuccessDialogBody(); return mSaveSuccessDialog; default: Log.w(TAG, "Request for unexpected dialog id: " + id); break; } return null; } private void updateCaptionsFromDialog() { Log.i(TAG, "updateCaptionsFromDialog()..."); if (mCaptionDialog == null) { Log.w(TAG, "updateCaptionsFromDialog: null mCaptionDialog!"); return; } // Get the two caption strings: EditText topText = (EditText) mCaptionDialog.findViewById(R.id.top_edittext); Log.i(TAG, "- Top editText: " + topText); String topString = topText.getText().toString(); Log.i(TAG, " - String: '" + topString + "'"); EditText bottomText = (EditText) mCaptionDialog.findViewById(R.id.bottom_edittext); Log.i(TAG, "- Bottom editText: " + bottomText); String bottomString = bottomText.getText().toString(); Log.i(TAG, " - String: '" + bottomString + "'"); mLolcatView.setCaptions(topString, bottomString); updateButtons(); } /** * Kicks off the process of saving the LolcatView's working Bitmap to * the SD card, in preparation for viewing it later and/or sharing it. */ private void saveImage() { Log.i(TAG, "saveImage()..."); // First of all, bring up a progress dialog. showDialog(DIALOG_SAVE_PROGRESS); // We now need to save the bitmap to the SD card, and then ask the // MediaScanner to scan it. Do the actual work of all this in a // helper thread, since it's fairly slow (and will occasionally // ANR if we do it here in the UI thread.) Thread t = new Thread() { public void run() { Log.i(TAG, "Running worker thread..."); saveImageInternal(); } }; t.start(); // Next steps: // - saveImageInternal() // - onMediaScannerConnected() // - onScanCompleted } /** * Saves the LolcatView's working Bitmap to the SD card, in * preparation for viewing it later and/or sharing it. * * The bitmap will be saved as a new file in the directory * LOLCAT_SAVE_DIRECTORY, with an automatically-generated filename * based on the current time. It also connects to the * MediaScanner service, since we'll need to scan that new file (in * order to get a Uri we can then VIEW or share.) * * This method is run in a worker thread; @see saveImage(). */ private void saveImageInternal() { Log.i(TAG, "saveImageInternal()..."); // TODO: Currently we save the bitmap to a file on the sdcard, // then ask the MediaScanner to scan it (which gives us a Uri we // can then do an ACTION_VIEW on.) But rather than doing these // separate steps, maybe there's some easy way (given an // OutputStream) to directly talk to the MediaProvider // (i.e. com.android.provider.MediaStore) and say "here's an // image, please save it somwhere and return the URI to me"... // Save the bitmap to a file on the sdcard. // (Based on similar code in MusicUtils.java.) // TODO: Make this filename more human-readable? Maybe "Lolcat-YYYY-MM-DD-HHMMSS.png"? String filename = Environment.getExternalStorageDirectory() + "/" + LOLCAT_SAVE_DIRECTORY + String.valueOf(System.currentTimeMillis() + SAVED_IMAGE_EXTENSION); Log.i(TAG, "- filename: '" + filename + "'"); if (ensureFileExists(filename)) { try { OutputStream outstream = new FileOutputStream(filename); Bitmap bitmap = mLolcatView.getWorkingBitmap(); boolean success = bitmap.compress(SAVED_IMAGE_COMPRESS_FORMAT, 100, outstream); Log.i(TAG, "- success code from Bitmap.compress: " + success); outstream.close(); if (success) { Log.i(TAG, "- Saved! filename = " + filename); mSavedImageFilename = filename; // Ok, now we need to get the MediaScanner to scan the // file we just wrote. Step 1 is to get our // MediaScannerConnection object to connect to the // MediaScanner service. mMediaScannerConnection.connect(); // See onMediaScannerConnected() for the next step } else { Log.w(TAG, "Bitmap.compress failed: bitmap " + bitmap + ", filename '" + filename + "'"); onSaveFailed(R.string.lolcat_save_failed); } } catch (FileNotFoundException e) { Log.w(TAG, "error creating file", e); onSaveFailed(R.string.lolcat_save_failed); } catch (IOException e) { Log.w(TAG, "error creating file", e); onSaveFailed(R.string.lolcat_save_failed); } } else { Log.w(TAG, "ensureFileExists failed for filename '" + filename + "'"); onSaveFailed(R.string.lolcat_save_failed); } } // // MediaScanner-related code // /** * android.media.MediaScannerConnection.MediaScannerConnectionClient implementation. */ private MediaScannerConnection.MediaScannerConnectionClient mMediaScanConnClient = new MediaScannerConnection.MediaScannerConnectionClient() { /** * Called when a connection to the MediaScanner service has been established. */ public void onMediaScannerConnected() { Log.i(TAG, "MediaScannerConnectionClient.onMediaScannerConnected..."); // The next step happens in the UI thread: mHandler.post(new Runnable() { public void run() { LolcatActivity.this.onMediaScannerConnected(); } }); } /** * Called when the media scanner has finished scanning a file. * @param path the path to the file that has been scanned. * @param uri the Uri for the file if the scanning operation succeeded * and the file was added to the media database, or null if scanning failed. */ public void onScanCompleted(final String path, final Uri uri) { Log.i(TAG, "MediaScannerConnectionClient.onScanCompleted: path " + path + ", uri " + uri); // Just run the "real" onScanCompleted() method in the UI thread: mHandler.post(new Runnable() { public void run() { LolcatActivity.this.onScanCompleted(path, uri); } }); } }; /** * This method is called when our MediaScannerConnection successfully * connects to the MediaScanner service. At that point we fire off a * request to scan the lolcat image we just saved. * * This needs to run in the UI thread, so it's called from * mMediaScanConnClient's onMediaScannerConnected() method via our Handler. */ private void onMediaScannerConnected() { Log.i(TAG, "onMediaScannerConnected()..."); // Update the message in the progress dialog... mSaveProgressDialog.setMessage(getResources().getString(R.string.lolcat_scanning)); // Fire off a request to the MediaScanner service to scan this // file; we'll get notified when the scan completes. Log.i(TAG, "- Requesting scan for file: " + mSavedImageFilename); mMediaScannerConnection.scanFile(mSavedImageFilename, null /* mimeType */); // Next step: mMediaScanConnClient will get an onScanCompleted() callback, // which calls our own onScanCompleted() method via our Handler. } /** * Updates the UI after the media scanner finishes the scanFile() * request we issued from onMediaScannerConnected(). * * This needs to run in the UI thread, so it's called from * mMediaScanConnClient's onScanCompleted() method via our Handler. */ private void onScanCompleted(String path, final Uri uri) { Log.i(TAG, "onScanCompleted: path " + path + ", uri " + uri); mMediaScannerConnection.disconnect(); if (uri == null) { Log.w(TAG, "onScanCompleted: scan failed."); mSavedImageUri = null; onSaveFailed(R.string.lolcat_scan_failed); return; } // Success! dismissDialog(DIALOG_SAVE_PROGRESS); // We can now access the saved lolcat image using the specified Uri. mSavedImageUri = uri; // Bring up a success dialog, giving the user the option to go to // the pictures app (so you can share the image). showSaveSuccessDialog(); } // // Other misc utility methods // /** * Ensure that the specified file exists on the SD card, creating it * if necessary. * * Copied from MediaProvider / MusicUtils. * * @return true if the file already exists, or we * successfully created it. */ private static boolean ensureFileExists(String path) { File file = new File(path); if (file.exists()) { return true; } else { // we will not attempt to create the first directory in the path // (for example, do not create /sdcard if the SD card is not mounted) int secondSlash = path.indexOf('/', 1); if (secondSlash < 1) return false; String directoryPath = path.substring(0, secondSlash); File directory = new File(directoryPath); if (!directory.exists()) return false; file.getParentFile().mkdirs(); try { return file.createNewFile(); } catch (IOException ioe) { Log.w(TAG, "File creation failed", ioe); } return false; } } /** * Updates the UI after a failure anywhere in the bitmap saving / scanning * sequence. */ private void onSaveFailed(int errorMessageResId) { dismissDialog(DIALOG_SAVE_PROGRESS); Toast.makeText(this, errorMessageResId, Toast.LENGTH_SHORT).show(); } /** * Goes to the Pictures app for the specified URI. */ private void viewSavedImage(Uri uri) { Log.i(TAG, "viewSavedImage(" + uri + ")..."); if (uri == null) { Log.w(TAG, "viewSavedImage: null uri!"); return; } Intent intent = new Intent(Intent.ACTION_VIEW, uri); Log.i(TAG, "- running startActivity... Intent = " + intent); startActivity(intent); } private void viewSavedImage() { viewSavedImage(mSavedImageUri); } /** * Shares the image with the specified URI. */ private void shareSavedImage(Uri uri) { Log.i(TAG, "shareSavedImage(" + uri + ")..."); if (uri == null) { Log.w(TAG, "shareSavedImage: null uri!"); return; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType(SAVED_IMAGE_MIME_TYPE); intent.putExtra(Intent.EXTRA_STREAM, uri); try { startActivity( Intent.createChooser( intent, getResources().getString(R.string.lolcat_sendImage_label))); } catch (android.content.ActivityNotFoundException ex) { Log.w(TAG, "shareSavedImage: startActivity failed", ex); Toast.makeText(this, R.string.lolcat_share_failed, Toast.LENGTH_SHORT).show(); } } private void shareSavedImage() { shareSavedImage(mSavedImageUri); } }
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.android.lolcat; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.widget.ImageView; /** * Lolcat-specific subclass of ImageView, which manages the various * scaled-down Bitmaps and knows how to render and manipulate the * image captions. */ public class LolcatView extends ImageView { private static final String TAG = "LolcatView"; // Standard lolcat size is 500x375. (But to preserve the original // image's aspect ratio, we rescale so that the larger dimension ends // up being 500 pixels.) private static final float SCALED_IMAGE_MAX_DIMENSION = 500f; // Other standard lolcat image parameters private static final int FONT_SIZE = 44; private Bitmap mScaledBitmap; // The photo picked by the user, scaled-down private Bitmap mWorkingBitmap; // The Bitmap we render the caption text into // Current state of the captions. // TODO: This array currently has a hardcoded length of 2 (for "top" // and "bottom" captions), but eventually should support as many // captions as the user wants to add. private final Caption[] mCaptions = new Caption[] { new Caption(), new Caption() }; // State used while dragging a caption around private boolean mDragging; private int mDragCaptionIndex; // index of the caption (in mCaptions[]) that's being dragged private int mTouchDownX, mTouchDownY; private final Rect mInitialDragBox = new Rect(); private final Rect mCurrentDragBox = new Rect(); private final RectF mCurrentDragBoxF = new RectF(); // used in onDraw() private final RectF mTransformedDragBoxF = new RectF(); // used in onDraw() private final Rect mTmpRect = new Rect(); public LolcatView(Context context) { super(context); } public LolcatView(Context context, AttributeSet attrs) { super(context, attrs); } public LolcatView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public Bitmap getWorkingBitmap() { return mWorkingBitmap; } public String getTopCaption() { return mCaptions[0].caption; } public String getBottomCaption() { return mCaptions[1].caption; } /** * @return true if the user has set caption(s) for this LolcatView. */ public boolean hasValidCaption() { return !TextUtils.isEmpty(mCaptions[0].caption) || !TextUtils.isEmpty(mCaptions[1].caption); } public void clear() { mScaledBitmap = null; mWorkingBitmap = null; setImageDrawable(null); // TODO: Anything else we need to do here to release resources // associated with this object, like maybe the Bitmap that got // created by the previous setImageURI() call? } public void loadFromUri(Uri uri) { // For now, directly load the specified Uri. setImageURI(uri); // TODO: Rather than calling setImageURI() with the URI of // the (full-size) photo, it would be better to turn the URI into // a scaled-down Bitmap right here, and load *that* into ourself. // I'd do that basically the same way that ImageView.setImageURI does it: // [ . . . ] // android.graphics.BitmapFactory.nativeDecodeStream(Native Method) // android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:304) // android.graphics.drawable.Drawable.createFromStream(Drawable.java:635) // android.widget.ImageView.resolveUri(ImageView.java:477) // android.widget.ImageView.setImageURI(ImageView.java:281) // [ . . . ] // But for now let's let ImageView do the work: we call setImageURI (above) // and immediately pull out a Bitmap (below). // Stash away a scaled-down bitmap. // TODO: is it safe to assume this will always be a BitmapDrawable? BitmapDrawable drawable = (BitmapDrawable) getDrawable(); Log.i(TAG, "===> current drawable: " + drawable); Bitmap fullSizeBitmap = drawable.getBitmap(); Log.i(TAG, "===> fullSizeBitmap: " + fullSizeBitmap + " dimensions: " + fullSizeBitmap.getWidth() + " x " + fullSizeBitmap.getHeight()); Bitmap.Config config = fullSizeBitmap.getConfig(); Log.i(TAG, " - config = " + config); // Standard lolcat size is 500x375. But we don't want to distort // the image if it isn't 4x3, so let's just set the larger // dimension to 500 pixels and preserve the source aspect ratio. float origWidth = fullSizeBitmap.getWidth(); float origHeight = fullSizeBitmap.getHeight(); float aspect = origWidth / origHeight; Log.i(TAG, " - aspect = " + aspect + "(" + origWidth + " x " + origHeight + ")"); float scaleFactor = ((aspect > 1.0) ? origWidth : origHeight) / SCALED_IMAGE_MAX_DIMENSION; int scaledWidth = Math.round(origWidth / scaleFactor); int scaledHeight = Math.round(origHeight / scaleFactor); mScaledBitmap = Bitmap.createScaledBitmap(fullSizeBitmap, scaledWidth, scaledHeight, true /* filter */); Log.i(TAG, " ===> mScaledBitmap: " + mScaledBitmap + " dimensions: " + mScaledBitmap.getWidth() + " x " + mScaledBitmap.getHeight()); Log.i(TAG, " isMutable = " + mScaledBitmap.isMutable()); } /** * Sets the captions for this LolcatView. */ public void setCaptions(String topCaption, String bottomCaption) { Log.i(TAG, "setCaptions: '" + topCaption + "', '" + bottomCaption + "'"); if (topCaption == null) topCaption = ""; if (bottomCaption == null) bottomCaption = ""; mCaptions[0].caption = topCaption; mCaptions[1].caption = bottomCaption; // If the user clears a caption, reset its position (so that it'll // come back in the default position if the user re-adds it.) if (TextUtils.isEmpty(mCaptions[0].caption)) { Log.i(TAG, "- invalidating position of caption 0..."); mCaptions[0].positionValid = false; } if (TextUtils.isEmpty(mCaptions[1].caption)) { Log.i(TAG, "- invalidating position of caption 1..."); mCaptions[1].positionValid = false; } // And *any* time the captions change, blow away the cached // caption bounding boxes to make sure we'll recompute them in // renderCaptions(). mCaptions[0].captionBoundingBox = null; mCaptions[1].captionBoundingBox = null; renderCaptions(mCaptions); } /** * Clears the captions for this LolcatView. */ public void clearCaptions() { setCaptions("", ""); } /** * Renders this LolcatView's current image captions into our * underlying ImageView. * * We start with a scaled-down version of the photo originally chosed * by the user (mScaledBitmap), make a mutable copy (mWorkingBitmap), * render the specified strings into the bitmap, and show the * resulting image onscreen. */ public void renderCaptions(Caption[] captions) { // TODO: handle an arbitrary array of strings, rather than // assuming "top" and "bottom" captions. String topString = captions[0].caption; boolean topStringValid = !TextUtils.isEmpty(topString); String bottomString = captions[1].caption; boolean bottomStringValid = !TextUtils.isEmpty(bottomString); Log.i(TAG, "renderCaptions: '" + topString + "', '" + bottomString + "'"); if (mScaledBitmap == null) return; // Make a fresh (mutable) copy of the scaled-down photo Bitmap, // and render the desired text into it. Bitmap.Config config = mScaledBitmap.getConfig(); Log.i(TAG, " - mScaledBitmap config = " + config); mWorkingBitmap = mScaledBitmap.copy(config, true /* isMutable */); Log.i(TAG, " ===> mWorkingBitmap: " + mWorkingBitmap + " dimensions: " + mWorkingBitmap.getWidth() + " x " + mWorkingBitmap.getHeight()); Log.i(TAG, " isMutable = " + mWorkingBitmap.isMutable()); Canvas canvas = new Canvas(mWorkingBitmap); Log.i(TAG, "- Canvas: " + canvas + " dimensions: " + canvas.getWidth() + " x " + canvas.getHeight()); Paint textPaint = new Paint(); textPaint.setAntiAlias(true); textPaint.setTextSize(FONT_SIZE); textPaint.setColor(0xFFFFFFFF); Log.i(TAG, "- Paint: " + textPaint); Typeface face = textPaint.getTypeface(); Log.i(TAG, "- default typeface: " + face); // The most standard font for lolcat captions is Impact. (Arial // Black is also common.) Unfortunately we don't have either of // these on the device by default; the closest we can do is // DroidSans-Bold: face = Typeface.DEFAULT_BOLD; Log.i(TAG, "- new face: " + face); textPaint.setTypeface(face); // Look up the positions of the captions, or if this is our very // first time rendering them, initialize the positions to default // values. final int edgeBorder = 20; final int fontHeight = textPaint.getFontMetricsInt(null); Log.i(TAG, "- fontHeight: " + fontHeight); Log.i(TAG, "- Caption positioning:"); int topX = 0; int topY = 0; if (topStringValid) { if (mCaptions[0].positionValid) { topX = mCaptions[0].xpos; topY = mCaptions[0].ypos; Log.i(TAG, " - TOP: already had a valid position: " + topX + ", " + topY); } else { // Start off with the "top" caption at the upper-left: topX = edgeBorder; topY = edgeBorder + (fontHeight * 3 / 4); mCaptions[0].setPosition(topX, topY); Log.i(TAG, " - TOP: initializing to default position: " + topX + ", " + topY); } } int bottomX = 0; int bottomY = 0; if (bottomStringValid) { if (mCaptions[1].positionValid) { bottomX = mCaptions[1].xpos; bottomY = mCaptions[1].ypos; Log.i(TAG, " - Bottom: already had a valid position: " + bottomX + ", " + bottomY); } else { // Start off with the "bottom" caption at the lower-right: final int bottomTextWidth = (int) textPaint.measureText(bottomString); Log.i(TAG, "- bottomTextWidth (" + bottomString + "): " + bottomTextWidth); bottomX = canvas.getWidth() - edgeBorder - bottomTextWidth; bottomY = canvas.getHeight() - edgeBorder; mCaptions[1].setPosition(bottomX, bottomY); Log.i(TAG, " - BOTTOM: initializing to default position: " + bottomX + ", " + bottomY); } } // Finally, render the text. // Standard lolcat captions are drawn in white with a heavy black // outline (i.e. white fill, black stroke). Our Canvas APIs can't // do this exactly, though. // We *could* get something decent-looking using a regular // drop-shadow, like this: // textPaint.setShadowLayer(3.0f, 3, 3, 0xff000000); // but instead let's simulate the "outline" style by drawing the // text 4 separate times, with the shadow in a different direction // each time. // (TODO: This is a hack, and still doesn't look as good // as a real "white fill, black stroke" style.) final float shadowRadius = 2.0f; final int shadowOffset = 2; final int shadowColor = 0xff000000; // TODO: Right now we use offsets of 2,2 / -2,2 / 2,-2 / -2,-2 . // But 2,0 / 0,2 / -2,0 / 0,-2 might look better. textPaint.setShadowLayer(shadowRadius, shadowOffset, shadowOffset, shadowColor); if (topStringValid) canvas.drawText(topString, topX, topY, textPaint); if (bottomStringValid) canvas.drawText(bottomString, bottomX, bottomY, textPaint); // textPaint.setShadowLayer(shadowRadius, -shadowOffset, shadowOffset, shadowColor); if (topStringValid) canvas.drawText(topString, topX, topY, textPaint); if (bottomStringValid) canvas.drawText(bottomString, bottomX, bottomY, textPaint); // textPaint.setShadowLayer(shadowRadius, shadowOffset, -shadowOffset, shadowColor); if (topStringValid) canvas.drawText(topString, topX, topY, textPaint); if (bottomStringValid) canvas.drawText(bottomString, bottomX, bottomY, textPaint); // textPaint.setShadowLayer(shadowRadius, -shadowOffset, -shadowOffset, shadowColor); if (topStringValid) canvas.drawText(topString, topX, topY, textPaint); if (bottomStringValid) canvas.drawText(bottomString, bottomX, bottomY, textPaint); // Stash away bounding boxes for the captions if this // is our first time rendering them. // Watch out: the x/y position we use for drawing the text is // actually the *lower* left corner of the bounding box... int textWidth, textHeight; if (topStringValid && mCaptions[0].captionBoundingBox == null) { Log.i(TAG, "- Computing initial bounding box for top caption..."); textPaint.getTextBounds(topString, 0, topString.length(), mTmpRect); textWidth = mTmpRect.width(); textHeight = mTmpRect.height(); Log.i(TAG, "- text dimensions: " + textWidth + " x " + textHeight); mCaptions[0].captionBoundingBox = new Rect(topX, topY - textHeight, topX + textWidth, topY); Log.i(TAG, "- RESULTING RECT: " + mCaptions[0].captionBoundingBox); } if (bottomStringValid && mCaptions[1].captionBoundingBox == null) { Log.i(TAG, "- Computing initial bounding box for bottom caption..."); textPaint.getTextBounds(bottomString, 0, bottomString.length(), mTmpRect); textWidth = mTmpRect.width(); textHeight = mTmpRect.height(); Log.i(TAG, "- text dimensions: " + textWidth + " x " + textHeight); mCaptions[1].captionBoundingBox = new Rect(bottomX, bottomY - textHeight, bottomX + textWidth, bottomY); Log.i(TAG, "- RESULTING RECT: " + mCaptions[1].captionBoundingBox); } // Finally, display the new Bitmap to the user: setImageBitmap(mWorkingBitmap); } @Override protected void onDraw(Canvas canvas) { Log.i(TAG, "onDraw: " + canvas); super.onDraw(canvas); if (mDragging) { Log.i(TAG, "- dragging! Drawing box at " + mCurrentDragBox); // mCurrentDragBox is in the coordinate system of our bitmap; // need to convert it into the coordinate system of the // overall LolcatView. // // To transform between coordinate systems we need to apply the // transformation described by the ImageView's matrix *and* also // account for our left and top padding. Matrix m = getImageMatrix(); mCurrentDragBoxF.set(mCurrentDragBox); m.mapRect(mTransformedDragBoxF, mCurrentDragBoxF); mTransformedDragBoxF.offset(getPaddingLeft(), getPaddingTop()); Paint p = new Paint(); p.setColor(0xFFFFFFFF); p.setStyle(Paint.Style.STROKE); p.setStrokeWidth(2f); Log.i(TAG, "- Paint: " + p); canvas.drawRect(mTransformedDragBoxF, p); } } @Override public boolean onTouchEvent(MotionEvent ev) { Log.i(TAG, "onTouchEvent: " + ev); // Watch out: ev.getX() and ev.getY() are in the // coordinate system of the entire LolcatView, although // all the positions and rects we use here (like // mCaptions[].captionBoundingBox) are relative to the bitmap // that's drawn inside the LolcatView. // // To transform between coordinate systems we need to apply the // transformation described by the ImageView's matrix *and* also // account for our left and top padding. Matrix m = getImageMatrix(); Matrix invertedMatrix = new Matrix(); m.invert(invertedMatrix); float[] pointArray = new float[] { ev.getX() - getPaddingLeft(), ev.getY() - getPaddingTop() }; Log.i(TAG, " - BEFORE: pointArray = " + pointArray[0] + ", " + pointArray[1]); // Transform the X/Y position of the DOWN event back into bitmap coords invertedMatrix.mapPoints(pointArray); Log.i(TAG, " - AFTER: pointArray = " + pointArray[0] + ", " + pointArray[1]); int eventX = (int) pointArray[0]; int eventY = (int) pointArray[1]; int action = ev.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: if (mDragging) { Log.w(TAG, "Got an ACTION_DOWN, but we were already dragging!"); mDragging = false; // and continue as if we weren't already dragging... } if (!hasValidCaption()) { Log.w(TAG, "No caption(s) yet; ignoring this ACTION_DOWN event."); return true; } // See if this DOWN event hit one of the caption bounding // boxes. If so, start dragging! for (int i = 0; i < mCaptions.length; i++) { Rect boundingBox = mCaptions[i].captionBoundingBox; Log.i(TAG, " - boundingBox #" + i + ": " + boundingBox + "..."); if (boundingBox != null) { // Expand the bounding box by a fudge factor to make it // easier to hit (since touch accuracy is pretty poor on a // real device, and the captions are fairly small...) mTmpRect.set(boundingBox); final int touchPositionSlop = 40; // pixels mTmpRect.inset(-touchPositionSlop, -touchPositionSlop); Log.i(TAG, " - Checking expanded bounding box #" + i + ": " + mTmpRect + "..."); if (mTmpRect.contains(eventX, eventY)) { Log.i(TAG, " - Hit! " + mCaptions[i]); mDragging = true; mDragCaptionIndex = i; break; } } } if (!mDragging) { Log.i(TAG, "- ACTION_DOWN event didn't hit any captions; ignoring."); return true; } mTouchDownX = eventX; mTouchDownY = eventY; mInitialDragBox.set(mCaptions[mDragCaptionIndex].captionBoundingBox); mCurrentDragBox.set(mCaptions[mDragCaptionIndex].captionBoundingBox); invalidate(); return true; case MotionEvent.ACTION_MOVE: if (!mDragging) { return true; } int displacementX = eventX - mTouchDownX; int displacementY = eventY - mTouchDownY; mCurrentDragBox.set(mInitialDragBox); mCurrentDragBox.offset(displacementX, displacementY); invalidate(); return true; case MotionEvent.ACTION_UP: if (!mDragging) { return true; } mDragging = false; // Reposition the selected caption! Log.i(TAG, "- Done dragging! Repositioning caption #" + mDragCaptionIndex + ": " + mCaptions[mDragCaptionIndex]); int offsetX = eventX - mTouchDownX; int offsetY = eventY - mTouchDownY; Log.i(TAG, " - OFFSET: " + offsetX + ", " + offsetY); // Reposition the the caption we just dragged, and blow // away the cached bounding box to make sure it'll get // recomputed in renderCaptions(). mCaptions[mDragCaptionIndex].xpos += offsetX; mCaptions[mDragCaptionIndex].ypos += offsetY; mCaptions[mDragCaptionIndex].captionBoundingBox = null; Log.i(TAG, " - Updated caption: " + mCaptions[mDragCaptionIndex]); // Finally, refresh the screen. renderCaptions(mCaptions); return true; // This case isn't expected to happen. case MotionEvent.ACTION_CANCEL: if (!mDragging) { return true; } mDragging = false; // Refresh the screen. renderCaptions(mCaptions); return true; default: return super.onTouchEvent(ev); } } /** * Returns an array containing the xpos/ypos of each Caption in our * array of captions. (This method and setCaptionPositions() are used * by LolcatActivity to save and restore the activity state across * orientation changes.) */ public int[] getCaptionPositions() { // TODO: mCaptions currently has a hardcoded length of 2 (for // "top" and "bottom" captions). int[] captionPositions = new int[4]; if (mCaptions[0].positionValid) { captionPositions[0] = mCaptions[0].xpos; captionPositions[1] = mCaptions[0].ypos; } else { captionPositions[0] = -1; captionPositions[1] = -1; } if (mCaptions[1].positionValid) { captionPositions[2] = mCaptions[1].xpos; captionPositions[3] = mCaptions[1].ypos; } else { captionPositions[2] = -1; captionPositions[3] = -1; } Log.i(TAG, "getCaptionPositions: returning " + captionPositions); return captionPositions; } /** * Sets the xpos and ypos values of each Caption in our array based on * the specified values. (This method and getCaptionPositions() are * used by LolcatActivity to save and restore the activity state * across orientation changes.) */ public void setCaptionPositions(int[] captionPositions) { // TODO: mCaptions currently has a hardcoded length of 2 (for // "top" and "bottom" captions). Log.i(TAG, "setCaptionPositions(" + captionPositions + ")..."); if (captionPositions[0] < 0) { mCaptions[0].positionValid = false; Log.i(TAG, "- TOP caption: no valid position"); } else { mCaptions[0].setPosition(captionPositions[0], captionPositions[1]); Log.i(TAG, "- TOP caption: got valid position: " + mCaptions[0].xpos + ", " + mCaptions[0].ypos); } if (captionPositions[2] < 0) { mCaptions[1].positionValid = false; Log.i(TAG, "- BOTTOM caption: no valid position"); } else { mCaptions[1].setPosition(captionPositions[2], captionPositions[3]); Log.i(TAG, "- BOTTOM caption: got valid position: " + mCaptions[1].xpos + ", " + mCaptions[1].ypos); } // Finally, refresh the screen. renderCaptions(mCaptions); } /** * Structure used to hold the entire state of a single caption. */ class Caption { public String caption; public Rect captionBoundingBox; // updated by renderCaptions() public int xpos, ypos; public boolean positionValid; public void setPosition(int x, int y) { positionValid = true; xpos = x; ypos = y; // Also blow away the cached bounding box, to make sure it'll // get recomputed in renderCaptions(). captionBoundingBox = null; } @Override public String toString() { return "Caption['" + caption + "'; bbox " + captionBoundingBox + "; pos " + xpos + ", " + ypos + "; posValid = " + positionValid + "]"; } } }
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.wikinotes; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentUris; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.database.Cursor; import android.net.Uri; import android.os.Environment; import com.google.android.wikinotes.db.WikiNote; /** * A helper class that implements operations required by Activities in the * system. Notably, this includes launching the Activities for edit and * delete. */ public class WikiActivityHelper { public static final int ACTIVITY_EDIT = 1; public static final int ACTIVITY_DELETE = 2; public static final int ACTIVITY_LIST = 3; public static final int ACTIVITY_SEARCH = 4; private Activity mContext; /** * Preferred constructor. * * @param context * the Activity to be used for things like calling * startActivity */ public WikiActivityHelper(Activity context) { mContext = context; } /** * @see #WikiActivityHelper(Activity) */ // intentionally private; tell IDEs not to warn us about it @SuppressWarnings("unused") private WikiActivityHelper() { } /** * If a list of notes is requested, fire the WikiNotes list Content URI * and let the WikiNotesList activity handle it. */ public void listNotes() { Intent i = new Intent(Intent.ACTION_VIEW, WikiNote.Notes.ALL_NOTES_URI); mContext.startActivity(i); } /** * If requested, go back to the start page wikinote by requesting an * intent with the default start page URI */ public void goHome() { Uri startPageURL = Uri .withAppendedPath(WikiNote.Notes.ALL_NOTES_URI, mContext .getResources().getString(R.string.start_page)); Intent startPage = new Intent(Intent.ACTION_VIEW, startPageURL); mContext.startActivity(startPage); } /** * Create an intent to start the WikiNoteEditor using the current title * and body information (if any). */ public void editNote(String mNoteName, Cursor cursor) { // This intent could use the android.intent.action.EDIT for a wiki // note // to invoke, but instead I wanted to demonstrate the mechanism for // invoking // an intent on a known class within the same application directly. // Note // also that the title and body of the note to edit are passed in // using // the extras bundle. Intent i = new Intent(mContext, WikiNoteEditor.class); i.putExtra(WikiNote.Notes.TITLE, mNoteName); String body; if (cursor != null) { body = cursor.getString(cursor .getColumnIndexOrThrow(WikiNote.Notes.BODY)); } else { body = ""; } i.putExtra(WikiNote.Notes.BODY, body); mContext.startActivityForResult(i, ACTIVITY_EDIT); } /** * If requested, delete the current note. The user is prompted to confirm * this operation with a dialog, and if they choose to go ahead with the * deletion, the current activity is finish()ed once the data has been * removed, so that android naturally backtracks to the previous activity. */ public void deleteNote(final Cursor cursor) { new AlertDialog.Builder(mContext) .setTitle( mContext.getResources() .getString(R.string.delete_title)) .setMessage(R.string.delete_message) .setPositiveButton(R.string.yes_button, new OnClickListener() { public void onClick(DialogInterface dialog, int arg1) { Uri noteUri = ContentUris .withAppendedId(WikiNote.Notes.ALL_NOTES_URI, cursor .getInt(0)); mContext.getContentResolver().delete(noteUri, null, null); mContext.setResult(Activity.RESULT_OK); mContext.finish(); } }).setNegativeButton(R.string.no_button, null).show(); } /** * Equivalent to showOutcomeDialog(titleId, msg, false). * * @see #showOutcomeDialog(int, String, boolean) * @param titleId * the resource ID of the title of the dialog window * @param msg * the message to display */ private void showOutcomeDialog(int titleId, String msg) { showOutcomeDialog(titleId, msg, false); } /** * Creates and displays a Dialog with the indicated title and body. If * kill is true, the Dialog calls finish() on the hosting Activity and * restarts it with an identical Intent. This effectively restarts or * refreshes the Activity, so that it can reload whatever data it was * displaying. * * @param titleId * the resource ID of the title of the dialog window * @param msg * the message to display */ private void showOutcomeDialog(int titleId, String msg, final boolean kill) { new AlertDialog.Builder(mContext).setCancelable(false) .setTitle(mContext.getResources().getString(titleId)) .setMessage(msg) .setPositiveButton(R.string.export_dismiss_button, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { if (kill) { // restart the Activity w/ same // Intent Intent intent = mContext .getIntent(); mContext.finish(); mContext.startActivity(intent); } } }).create().show(); } /** * Exports notes to the SD card. Displays Dialogs as appropriate (using * the Activity provided in the constructor as a Context) to inform the * user as to what is going on. */ public void exportNotes() { // first see if an SD card is even present; abort if not if (!Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState())) { showOutcomeDialog(R.string.export_failure_title, mContext .getResources().getString(R.string.export_failure_missing_sd)); return; } // do a query for all records Cursor c = mContext.managedQuery(WikiNote.Notes.ALL_NOTES_URI, WikiNote.WIKI_EXPORT_PROJECTION, null, null, WikiNote.Notes.DEFAULT_SORT_ORDER); // iterate over all Notes, building up an XML StringBuffer along the // way boolean dataAvailable = c.moveToFirst(); StringBuffer sb = new StringBuffer(); String title, body, created, modified; int cnt = 0; sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<wiki-notes>"); while (dataAvailable) { title = c.getString(c.getColumnIndexOrThrow("title")); body = c.getString(c.getColumnIndexOrThrow("body")); modified = c.getString(c.getColumnIndexOrThrow("modified")); created = c.getString(c.getColumnIndexOrThrow("created")); // do a quick sanity check to make sure the note is worth saving if (!"".equals(title) && !"".equals(body) && title != null && body != null) { sb.append("\n").append("<note>\n\t<title><![CDATA[") .append(title).append("]]></title>\n\t<body><![CDATA["); sb.append(body).append("]]></body>\n\t<created>") .append(created).append("</created>\n\t"); sb.append("<modified>").append(modified) .append("</modified>\n</note>"); cnt++; } dataAvailable = c.moveToNext(); } sb.append("\n</wiki-notes>\n"); // open a file on the SD card under some useful name, and write out // XML FileWriter fw = null; File f = null; try { f = new File(Environment.getExternalStorageDirectory() + "/" + EXPORT_DIR); f.mkdirs(); // EXPORT_FILENAME includes current date+time, for user benefit String fileName = String.format(EXPORT_FILENAME, Calendar .getInstance()); f = new File(Environment.getExternalStorageDirectory() + "/" + EXPORT_DIR + "/" + fileName); if (!f.createNewFile()) { showOutcomeDialog(R.string.export_failure_title, mContext .getResources() .getString(R.string.export_failure_io_error)); return; } fw = new FileWriter(f); fw.write(sb.toString()); } catch (IOException e) { showOutcomeDialog(R.string.export_failure_title, mContext .getResources().getString(R.string.export_failure_io_error)); return; } finally { if (fw != null) { try { fw.close(); } catch (IOException ex) { } } } if (f == null) { showOutcomeDialog(R.string.export_failure_title, mContext .getResources().getString(R.string.export_failure_io_error)); return; } // Victory! Tell the user and display the filename just written. showOutcomeDialog(R.string.export_success_title, String .format(mContext.getResources() .getString(R.string.export_success), cnt, f.getName())); } /** * Imports records from SD card. Note that this is a destructive * operation: all existing records are destroyed. Displays confirmation * and outcome Dialogs before erasing data and after loading data. * * Note that this is the method that actually does the work; * {@link #importNotes()} is the method that should be called to kick * things off. * * @see #importNotes() */ public void doImport() { // first see if an SD card is even present; abort if not if (!Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState())) { showOutcomeDialog(R.string.import_failure_title, mContext .getResources().getString(R.string.export_failure_missing_sd)); return; } int cnt = 0; FileReader fr = null; ArrayList<StringBuffer[]> records = new ArrayList<StringBuffer[]>(); try { // first, find the file to load fr = new FileReader(new File(Environment .getExternalStorageDirectory() + "/" + IMPORT_FILENAME)); // don't destroy data until AFTER we find a file to import! mContext.getContentResolver() .delete(WikiNote.Notes.ALL_NOTES_URI, null, null); // next, parse that sucker XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(false); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(fr); int eventType = xpp.getEventType(); StringBuffer[] cur = new StringBuffer[4]; int curIdx = -1; while (eventType != XmlPullParser.END_DOCUMENT) { // save the previous note data-holder when we end a <note> tag if (eventType == XmlPullParser.END_TAG && "note".equals(xpp.getName())) { if (cur[0] != null && cur[1] != null && !"".equals(cur[0]) && !"".equals(cur[1])) { records.add(cur); } cur = new StringBuffer[4]; curIdx = -1; } else if (eventType == XmlPullParser.START_TAG && "title".equals(xpp.getName())) { curIdx = 0; } else if (eventType == XmlPullParser.START_TAG && "body".equals(xpp.getName())) { curIdx = 1; } else if (eventType == XmlPullParser.START_TAG && "created".equals(xpp.getName())) { curIdx = 2; } else if (eventType == XmlPullParser.START_TAG && "modified".equals(xpp.getName())) { curIdx = 3; } else if (eventType == XmlPullParser.TEXT && curIdx > -1) { if (cur[curIdx] == null) { cur[curIdx] = new StringBuffer(); } cur[curIdx].append(xpp.getText()); } eventType = xpp.next(); } // we stored data in a stringbuffer so we can skip empty records; // now process the successful records & save to Provider for (StringBuffer[] record : records) { Uri uri = Uri.withAppendedPath(WikiNote.Notes.ALL_NOTES_URI, record[0].toString()); ContentValues values = new ContentValues(); values.put("title", record[0].toString().trim()); values.put("body", record[1].toString().trim()); values.put("created", Long.parseLong(record[2].toString() .trim())); values.put("modified", Long.parseLong(record[3].toString() .trim())); if (mContext.getContentResolver().insert(uri, values) != null) { cnt++; } } } catch (FileNotFoundException e) { showOutcomeDialog(R.string.import_failure_title, mContext .getResources().getString(R.string.import_failure_nofile)); return; } catch (XmlPullParserException e) { showOutcomeDialog(R.string.import_failure_title, mContext .getResources().getString(R.string.import_failure_corrupt)); return; } catch (IOException e) { showOutcomeDialog(R.string.import_failure_title, mContext .getResources().getString(R.string.import_failure_io)); return; } finally { if (fr != null) { try { fr.close(); } catch (IOException e) { } } } // Victory! Inform the user. showOutcomeDialog(R.string.import_success_title, String .format(mContext.getResources() .getString(R.string.import_success), cnt), true); } /** * Starts a note import. Essentially this method just displays a Dialog * requesting confirmation from the user for the destructive operation. If * the user confirms, {@link #doImport()} is called. * * @see #doImport() */ public void importNotes() { new AlertDialog.Builder(mContext).setCancelable(true) .setTitle( mContext.getResources() .getString(R.string.import_confirm_title)) .setMessage(R.string.import_confirm_body) .setPositiveButton(R.string.import_confirm_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { doImport(); } }) .setNegativeButton(R.string.import_cancel_button, null).create() .show(); } /** * Launches the email system client to send a mail with the current * message. */ public void mailNote(final Cursor cursor) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("message/rfc822"); intent.putExtra(Intent.EXTRA_SUBJECT, cursor.getString(cursor .getColumnIndexOrThrow("title"))); String body = String.format(mContext.getResources() .getString(R.string.email_leader), cursor.getString(cursor .getColumnIndexOrThrow("body"))); intent.putExtra(Intent.EXTRA_TEXT, body); mContext.startActivity(Intent.createChooser(intent, "Title:")); } /* Some constants for filename structures. Could conceivably go into * strings.xml, but these don't need to be internationalized, so... */ private static final String EXPORT_DIR = "WikiNotes"; private static final String EXPORT_FILENAME = "WikiNotes_%1$tY-%1$tm-%1$td_%1$tH-%1$tM-%1$tS.xml"; private static final String IMPORT_FILENAME = "WikiNotes-import.xml"; }
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.wikinotes.db; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import java.util.HashMap; /** * The Wikinotes Content Provider is the guts of the wikinotes application. It * handles Content URLs to list all wiki notes, retrieve a note by name, or * return a list of matching notes based on text in the body or the title of * the note. It also handles all set up of the database, and reports back MIME * types for the individual notes or lists of notes to help Android route the * data to activities that can display that data (in this case either the * WikiNotes activity itself, or the WikiNotesList activity to list multiple * notes). */ public class WikiNotesProvider extends ContentProvider { private DatabaseHelper dbHelper; private static final String TAG = "WikiNotesProvider"; private static final String DATABASE_NAME = "wikinotes.db"; private static final int DATABASE_VERSION = 2; private static HashMap<String, String> NOTES_LIST_PROJECTION_MAP; private static final int NOTES = 1; private static final int NOTE_NAME = 2; private static final int NOTE_SEARCH = 3; private static final UriMatcher URI_MATCHER; /** * This inner DatabaseHelper class defines methods to create and upgrade * the database from previous versions. */ private static class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE wikinotes (_id INTEGER PRIMARY KEY," + "title TEXT COLLATE LOCALIZED NOT NULL," + "body TEXT," + "created INTEGER," + "modified INTEGER" + ");"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS wikinotes"); onCreate(db); } } @Override public boolean onCreate() { // On the creation of the content provider, open the database, // the Database helper will create a new version of the database // if needed through the functionality in SQLiteOpenHelper dbHelper = new DatabaseHelper(getContext()); return true; } /** * Figure out which query to run based on the URL requested and any other * parameters provided. */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sort) { // Query the database using the arguments provided SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); String[] whereArgs = null; // What type of query are we going to use - the URL_MATCHER // defined at the bottom of this class is used to pattern-match // the URL and select the right query from the switch statement switch (URI_MATCHER.match(uri)) { case NOTES: // this match lists all notes qb.setTables("wikinotes"); qb.setProjectionMap(NOTES_LIST_PROJECTION_MAP); break; case NOTE_SEARCH: // this match searches for a text match in the body of notes qb.setTables("wikinotes"); qb.setProjectionMap(NOTES_LIST_PROJECTION_MAP); qb.appendWhere("body like ? or title like ?"); whereArgs = new String[2]; whereArgs[0] = whereArgs[1] = "%" + uri.getLastPathSegment() + "%"; break; case NOTE_NAME: // this match searches for an exact match for a specific note name qb.setTables("wikinotes"); qb.appendWhere("title=?"); whereArgs = new String[] { uri.getLastPathSegment() }; break; default: // anything else is considered and illegal request throw new IllegalArgumentException("Unknown URL " + uri); } // If no sort order is specified use the default String orderBy; if (TextUtils.isEmpty(sort)) { orderBy = WikiNote.Notes.DEFAULT_SORT_ORDER; } else { orderBy = sort; } // Run the query and return the results as a Cursor SQLiteDatabase mDb = dbHelper.getReadableDatabase(); Cursor c = qb.query(mDb, projection, null, whereArgs, null, null, orderBy); c.setNotificationUri(getContext().getContentResolver(), uri); return c; } /** * For a given URL, return a MIME type for the data that will be returned * from that URL. This will help Android decide what to do with the data * it gets back. */ @Override public String getType(Uri uri) { switch (URI_MATCHER.match(uri)) { case NOTES: case NOTE_SEARCH: // for a notes list, or search results, return a mimetype // indicating // a directory of wikinotes return "vnd.android.cursor.dir/vnd.google.wikinote"; case NOTE_NAME: // for a specific note name, return a mimetype indicating a single // item representing a wikinote return "vnd.android.cursor.item/vnd.google.wikinote"; default: // any other kind of URL is illegal throw new IllegalArgumentException("Unknown URL " + uri); } } /** * For a URL and a list of initial values, insert a row using those values * into the database. */ @Override public Uri insert(Uri uri, ContentValues initialValues) { long rowID; ContentValues values; if (initialValues != null) { values = new ContentValues(initialValues); } else { values = new ContentValues(); } // We can only insert a note, no other URLs make sense here if (URI_MATCHER.match(uri) != NOTE_NAME) { throw new IllegalArgumentException("Unknown URL " + uri); } // Update the modified time of the record Long now = Long.valueOf(System.currentTimeMillis()); // Make sure that the fields are all set if (values.containsKey(WikiNote.Notes.CREATED_DATE) == false) { values.put(WikiNote.Notes.CREATED_DATE, now); } if (values.containsKey(WikiNote.Notes.MODIFIED_DATE) == false) { values.put(WikiNote.Notes.MODIFIED_DATE, now); } if (values.containsKey(WikiNote.Notes.TITLE) == false) { values.put(WikiNote.Notes.TITLE, uri.getLastPathSegment()); } if (values.containsKey(WikiNote.Notes.BODY) == false) { values.put(WikiNote.Notes.BODY, ""); } SQLiteDatabase db = dbHelper.getWritableDatabase(); rowID = db.insert("wikinotes", "body", values); if (rowID > 0) { Uri newUri = Uri.withAppendedPath(WikiNote.Notes.ALL_NOTES_URI, uri.getLastPathSegment()); getContext().getContentResolver().notifyChange(newUri, null); return newUri; } throw new SQLException("Failed to insert row into " + uri); } /** * Delete rows matching the where clause and args for the supplied URL. * The URL can be either the all notes URL (in which case all notes * matching the where clause will be deleted), or the note name, in which * case it will delete the note with the exactly matching title. Any of * the other URLs will be rejected as invalid. For deleting notes by title * we use ReST style arguments from the URI and don't support where clause * and args. */ @Override public int delete(Uri uri, String where, String[] whereArgs) { /* This is kind of dangerous: it deletes all records with a single Intent. It might make sense to make this ContentProvider non-public, since this is kind of over-powerful and the provider isn't generally intended to be public. But for now it's still public. */ if (WikiNote.Notes.ALL_NOTES_URI.equals(uri)) { return dbHelper.getWritableDatabase().delete("wikinotes", null, null); } int count; SQLiteDatabase db = dbHelper.getWritableDatabase(); switch (URI_MATCHER.match(uri)) { case NOTES: count = db.delete("wikinotes", where, whereArgs); break; case NOTE_NAME: if (!TextUtils.isEmpty(where) || (whereArgs != null)) { throw new UnsupportedOperationException( "Cannot update note using where clause"); } String noteId = uri.getPathSegments().get(1); count = db.delete("wikinotes", "_id=?", new String[] { noteId }); break; default: throw new IllegalArgumentException("Unknown URL " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } /** * The update method, which will allow either a mass update using a where * clause, or an update targeted to a specific note name (the latter will * be more common). Other matched URLs will be rejected as invalid. For * updating notes by title we use ReST style arguments from the URI and do * not support using the where clause or args. */ @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { int count; SQLiteDatabase db = dbHelper.getWritableDatabase(); switch (URI_MATCHER.match(uri)) { case NOTES: count = db.update("wikinotes", values, where, whereArgs); break; case NOTE_NAME: values.put(WikiNote.Notes.MODIFIED_DATE, System .currentTimeMillis()); count = db.update("wikinotes", values, where, whereArgs); break; default: throw new IllegalArgumentException("Unknown URL " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } /* * This static block sets up the pattern matches for the various URIs that * this content provider can handle. It also sets up the default projection * block (which defines what columns are returned from the database for the * results of a query). */ static { URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); URI_MATCHER.addURI(WikiNote.WIKINOTES_AUTHORITY, "wikinotes", NOTES); URI_MATCHER.addURI(WikiNote.WIKINOTES_AUTHORITY, "wikinotes/*", NOTE_NAME); URI_MATCHER.addURI(WikiNote.WIKINOTES_AUTHORITY, "wiki/search/*", NOTE_SEARCH); NOTES_LIST_PROJECTION_MAP = new HashMap<String, String>(); NOTES_LIST_PROJECTION_MAP.put(WikiNote.Notes._ID, "_id"); NOTES_LIST_PROJECTION_MAP.put(WikiNote.Notes.TITLE, "title"); NOTES_LIST_PROJECTION_MAP.put(WikiNote.Notes.BODY, "body"); NOTES_LIST_PROJECTION_MAP.put(WikiNote.Notes.CREATED_DATE, "created"); NOTES_LIST_PROJECTION_MAP.put(WikiNote.Notes.MODIFIED_DATE, "modified"); } }
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.wikinotes.db; import android.net.Uri; import android.provider.BaseColumns; /** * This class defines columns and URIs used in the wikinotes application */ public class WikiNote { /** * Notes table */ public static final class Notes implements BaseColumns { /** * The content:// style URI for this table - this to see all notes or * append a note name to see just the matching note. */ public static final Uri ALL_NOTES_URI = Uri .parse("content://com.google.android.wikinotes.db.wikinotes/wikinotes"); /** * This URI can be used to search the bodies of notes for an appended * search term. */ public static final Uri SEARCH_URI = Uri .parse("content://com.google.android.wikinotes.db.wikinotes/wiki/search"); /** * The default sort order for this table - most recently modified first */ public static final String DEFAULT_SORT_ORDER = "modified DESC"; /** * The title of the note * <P> * Type: TEXT * </P> */ public static final String TITLE = "title"; /** * The note body * <P> * Type: TEXT * </P> */ public static final String BODY = "body"; /** * The timestamp for when the note was created * <P> * Type: INTEGER (long) * </P> */ public static final String CREATED_DATE = "created"; /** * The timestamp for when the note was last modified * <P> * Type: INTEGER (long) * </P> */ public static final String MODIFIED_DATE = "modified"; } /** * Convenience definition for the projection we will use to retrieve columns * from the wikinotes */ public static final String[] WIKI_NOTES_PROJECTION = {Notes._ID, Notes.TITLE, Notes.BODY, Notes.MODIFIED_DATE}; public static final String[] WIKI_EXPORT_PROJECTION = {Notes.TITLE, Notes.BODY, Notes.CREATED_DATE, Notes.MODIFIED_DATE}; /** * The root authority for the WikiNotesProvider */ public static final String WIKINOTES_AUTHORITY = "com.google.android.wikinotes.db.wikinotes"; }
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.wikinotes; import android.app.ListActivity; import android.app.SearchManager; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import com.google.android.wikinotes.db.WikiNote; /** * Activity to list wikinotes. By default, the notes are listed in the order * of most recently modified to least recently modified. This activity can * handle requests to either show all notes, or the results of a title or body * search performed by the content provider. */ public class WikiNotesList extends ListActivity { /** * A key to store/retrieve the search criteria in a bundle */ public static final String SEARCH_CRITERIA_KEY = "SearchCriteria"; /** * The projection to use (columns to retrieve) for a query of wikinotes */ public static final String[] PROJECTION = { WikiNote.Notes._ID, WikiNote.Notes.TITLE, WikiNote.Notes.MODIFIED_DATE }; private Cursor mCursor; private WikiActivityHelper mHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); Uri uri = null; String query = null; // locate a query string; prefer a fresh search Intent over saved // state if (Intent.ACTION_SEARCH.equals(intent.getAction())) { query = intent.getStringExtra(SearchManager.QUERY); } else if (savedInstanceState != null) { query = savedInstanceState.getString(SearchManager.QUERY); } if (query != null && query.length() > 0) { uri = Uri.withAppendedPath(WikiNote.Notes.SEARCH_URI, Uri .encode(query)); } if (uri == null) { // somehow we got called w/o a query so fall back to a reasonable // default (all notes) uri = WikiNote.Notes.ALL_NOTES_URI; } // Do the query Cursor c = managedQuery(uri, PROJECTION, null, null, WikiNote.Notes.DEFAULT_SORT_ORDER); mCursor = c; mHelper = new WikiActivityHelper(this); // Bind the results of the search into the list ListAdapter adapter = new SimpleCursorAdapter( this, android.R.layout.simple_list_item_1, mCursor, new String[] { WikiNote.Notes.TITLE }, new int[] { android.R.id.text1 }); setListAdapter(adapter); // use the menu shortcut keys as default key bindings for the entire // activity setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); } /** * Override the onListItemClick to open the wiki note to view when it is * selected from the list. */ @Override protected void onListItemClick(ListView list, View view, int position, long id) { Cursor c = mCursor; c.moveToPosition(position); String title = c.getString(c .getColumnIndexOrThrow(WikiNote.Notes.TITLE)); // Create the URI of the note we want to view based on the title Uri uri = Uri.withAppendedPath(WikiNote.Notes.ALL_NOTES_URI, title); Intent i = new Intent(Intent.ACTION_VIEW, uri); startActivity(i); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, WikiNotes.HOME_ID, 0, R.string.menu_start) .setShortcut('4', 'h').setIcon(R.drawable.icon_start); menu.add(0, WikiNotes.LIST_ID, 0, R.string.menu_recent) .setShortcut('3', 'r').setIcon(R.drawable.icon_recent); menu.add(0, WikiNotes.ABOUT_ID, 0, R.string.menu_about) .setShortcut('5', 'a').setIcon(android.R.drawable.ic_dialog_info); menu.add(0, WikiNotes.EXPORT_ID, 0, R.string.menu_export) .setShortcut('6', 'x').setIcon(android.R.drawable.ic_dialog_info); menu.add(0, WikiNotes.IMPORT_ID, 0, R.string.menu_import) .setShortcut('7', 'm').setIcon(android.R.drawable.ic_dialog_info); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case WikiNotes.HOME_ID: mHelper.goHome(); return true; case WikiNotes.LIST_ID: mHelper.listNotes(); return true; case WikiNotes.ABOUT_ID: Eula.showEula(this); return true; case WikiNotes.EXPORT_ID: mHelper.exportNotes(); return true; case WikiNotes.IMPORT_ID: mHelper.importNotes(); return true; default: return 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.android.wikinotes; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import com.google.android.wikinotes.db.WikiNote; /** * Wikinote editor activity. This is a very simple activity that allows the user * to edit a wikinote using a text editor and confirm or cancel the changes. The * title and body for the wikinote to edit are passed in using the extras bundle * and the onFreeze() method provisions for those values to be stored in the * icicle on a lifecycle event, so that the user retains control over whether * the changes are committed to the database. */ public class WikiNoteEditor extends Activity { protected static final String ACTIVITY_RESULT = "com.google.android.wikinotes.EDIT"; private EditText mNoteEdit; private String mWikiNoteTitle; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.wiki_note_edit); mNoteEdit = (EditText) findViewById(R.id.noteEdit); // Check to see if the icicle has body and title values to restore String wikiNoteText = icicle == null ? null : icicle.getString(WikiNote.Notes.BODY); String wikiNoteTitle = icicle == null ? null : icicle.getString(WikiNote.Notes.TITLE); // If not, check to see if the extras bundle has these values passed in if (wikiNoteTitle == null) { Bundle extras = getIntent().getExtras(); wikiNoteText = extras == null ? null : extras .getString(WikiNote.Notes.BODY); wikiNoteTitle = extras == null ? null : extras .getString(WikiNote.Notes.TITLE); } // If we have no title information, this is an invalid intent request if (TextUtils.isEmpty(wikiNoteTitle)) { // no note title - bail setResult(RESULT_CANCELED); finish(); return; } mWikiNoteTitle = wikiNoteTitle; // but if the body is null, just set it to empty - first edit of this // note wikiNoteText = wikiNoteText == null ? "" : wikiNoteText; // set the title so we know which note we are editing setTitle(getString(R.string.wiki_editing, wikiNoteTitle)); // set the note body to edit mNoteEdit.setText(wikiNoteText); // set listeners for the confirm and cancel buttons ((Button) findViewById(R.id.confirmButton)) .setOnClickListener(new OnClickListener() { public void onClick(View view) { Intent i = new Intent(); i.putExtra(ACTIVITY_RESULT, mNoteEdit.getText() .toString()); setResult(RESULT_OK, i); finish(); } }); ((Button) findViewById(R.id.cancelButton)) .setOnClickListener(new OnClickListener() { public void onClick(View view) { setResult(RESULT_CANCELED); finish(); } }); if (!getSharedPreferences(Eula.PREFERENCES_EULA, Activity.MODE_PRIVATE) .getBoolean(Eula.PREFERENCE_EULA_ACCEPTED, false)) { Eula.showEula(this); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(WikiNote.Notes.TITLE, mWikiNoteTitle); outState.putString(WikiNote.Notes.BODY, mNoteEdit.getText().toString()); } }
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.wikinotes; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.SharedPreferences; /** * 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 { public static final String PREFERENCE_EULA_ACCEPTED = "eula.accepted"; public 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); final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.about_title); builder.setCancelable(false); builder.setPositiveButton(R.string.about_dismiss_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { preferences.edit().putBoolean(PREFERENCE_EULA_ACCEPTED, true).commit(); } }); builder.setMessage(R.string.about_body); builder.create().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.android.wikinotes; import java.util.regex.Pattern; import android.app.Activity; import android.content.ContentUris; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.text.util.Linkify; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import com.google.android.wikinotes.db.WikiNote; /** * The WikiNotes activity is the default handler for displaying individual * wiki notes. It takes the wiki note name to view from the intent data URL * and defaults to a page name defined in R.strings.start_page if no page name * is given. The lifecycle events store the current content URL being viewed. * It uses Linkify to turn wiki words in the body of the wiki note into * clickable links which in turn call back into the WikiNotes activity from * the Android operating system. If a URL is passed to the WikiNotes activity * for a page that does not yet exist, the WikiNoteEditor activity is * automatically started to place the user into edit mode for a new wiki note * with the given name. */ public class WikiNotes extends Activity { /** * The view URL which is prepended to a matching wikiword in order to fire * the WikiNotes activity again through Linkify */ private static final String KEY_URL = "wikiNotesURL"; public static final int EDIT_ID = Menu.FIRST; public static final int HOME_ID = Menu.FIRST + 1; public static final int LIST_ID = Menu.FIRST + 3; public static final int DELETE_ID = Menu.FIRST + 4; public static final int ABOUT_ID = Menu.FIRST + 5; public static final int EXPORT_ID = Menu.FIRST + 6; public static final int IMPORT_ID = Menu.FIRST + 7; public static final int EMAIL_ID = Menu.FIRST + 8; private TextView mNoteView; Cursor mCursor; private Uri mURI; String mNoteName; private static final Pattern WIKI_WORD_MATCHER; private WikiActivityHelper mHelper; static { // Compile the regular expression pattern that will be used to // match WikiWords in the body of the note WIKI_WORD_MATCHER = Pattern .compile("\\b[A-Z]+[a-z0-9]+[A-Z][A-Za-z0-9]+\\b"); } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mNoteView = (TextView) findViewById(R.id.noteview); // get the URL we are being asked to view Uri uri = getIntent().getData(); if ((uri == null) && (icicle != null)) { // perhaps we have the URI in the icicle instead? uri = Uri.parse(icicle.getString(KEY_URL)); } // do we have a correct URI including the note name? if ((uri == null) || (uri.getPathSegments().size() < 2)) { // if not, build one using the default StartPage name uri = Uri.withAppendedPath(WikiNote.Notes.ALL_NOTES_URI, getResources() .getString(R.string.start_page)); } // can we find a matching note? Cursor cursor = managedQuery(uri, WikiNote.WIKI_NOTES_PROJECTION, null, null, null); boolean newNote = false; if ((cursor == null) || (cursor.getCount() == 0)) { // no matching wikinote, so create it uri = getContentResolver().insert(uri, null); if (uri == null) { Log.e("WikiNotes", "Failed to insert new wikinote into " + getIntent().getData()); finish(); return; } // make sure that the new note was created successfully, and // select // it cursor = managedQuery(uri, WikiNote.WIKI_NOTES_PROJECTION, null, null, null); if ((cursor == null) || (cursor.getCount() == 0)) { Log.e("WikiNotes", "Failed to open new wikinote: " + getIntent().getData()); finish(); return; } newNote = true; } mURI = uri; mCursor = cursor; cursor.moveToFirst(); mHelper = new WikiActivityHelper(this); // get the note name String noteName = cursor.getString(cursor .getColumnIndexOrThrow(WikiNote.Notes.TITLE)); mNoteName = noteName; // set the title to the name of the page setTitle(getResources().getString(R.string.wiki_title, noteName)); // If a new note was created, jump straight into editing it if (newNote) { mHelper.editNote(noteName, null); } else if (!getSharedPreferences(Eula.PREFERENCES_EULA, Activity.MODE_PRIVATE) .getBoolean(Eula.PREFERENCE_EULA_ACCEPTED, false)) { Eula.showEula(this); } // Set the menu shortcut keys to be default keys for the activity as // well setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Put the URL currently being viewed into the icicle outState.putString(KEY_URL, mURI.toString()); } @Override protected void onResume() { super.onResume(); Cursor c = mCursor; if (c.getCount() < 1) { // if the note can't be found, don't try to load it -- bail out // (probably means it got deleted while we were frozen; // thx to joe.bowbeer for the find) finish(); return; } c.requery(); c.moveToFirst(); showWikiNote(c .getString(c.getColumnIndexOrThrow(WikiNote.Notes.BODY))); } /** * Show the wiki note in the text edit view with both the default Linkify * options and the regular expression for WikiWords matched and turned * into live links. * * @param body * The plain text to linkify and put into the edit view. */ private void showWikiNote(CharSequence body) { TextView noteView = mNoteView; noteView.setText(body); // Add default links first - phone numbers, URLs, etc. Linkify.addLinks(noteView, Linkify.ALL); // Now add in the custom linkify match for WikiWords Linkify.addLinks(noteView, WIKI_WORD_MATCHER, WikiNote.Notes.ALL_NOTES_URI.toString() + "/"); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, EDIT_ID, 0, R.string.menu_edit).setShortcut('1', 'e') .setIcon(R.drawable.icon_delete); menu.add(0, HOME_ID, 0, R.string.menu_start).setShortcut('4', 'h') .setIcon(R.drawable.icon_start); menu.add(0, LIST_ID, 0, R.string.menu_recent).setShortcut('3', 'r') .setIcon(R.drawable.icon_recent); menu.add(0, DELETE_ID, 0, R.string.menu_delete).setShortcut('2', 'd') .setIcon(R.drawable.icon_delete); menu.add(0, ABOUT_ID, 0, R.string.menu_about).setShortcut('5', 'a') .setIcon(android.R.drawable.ic_dialog_info); menu.add(0, EXPORT_ID, 0, R.string.menu_export).setShortcut('7', 'x') .setIcon(android.R.drawable.ic_dialog_info); menu.add(0, IMPORT_ID, 0, R.string.menu_import).setShortcut('8', 'm') .setIcon(android.R.drawable.ic_dialog_info); menu.add(0, EMAIL_ID, 0, R.string.menu_email).setShortcut('6', 'm') .setIcon(android.R.drawable.ic_dialog_info); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case EDIT_ID: mHelper.editNote(mNoteName, mCursor); return true; case HOME_ID: mHelper.goHome(); return true; case DELETE_ID: mHelper.deleteNote(mCursor); return true; case LIST_ID: mHelper.listNotes(); return true; case WikiNotes.ABOUT_ID: Eula.showEula(this); return true; case WikiNotes.EXPORT_ID: mHelper.exportNotes(); return true; case WikiNotes.IMPORT_ID: mHelper.importNotes(); return true; case WikiNotes.EMAIL_ID: mHelper.mailNote(mCursor); return true; default: return false; } } /** * If the note was edited and not canceled, commit the update to the * database and then refresh the current view of the linkified note. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent result) { super.onActivityResult(requestCode, resultCode, result); if ((requestCode == WikiActivityHelper.ACTIVITY_EDIT) && (resultCode == RESULT_OK)) { // edit was confirmed - store the update Cursor c = mCursor; c.requery(); c.moveToFirst(); Uri noteUri = ContentUris .withAppendedId(WikiNote.Notes.ALL_NOTES_URI, c.getInt(0)); ContentValues values = new ContentValues(); values.put(WikiNote.Notes.BODY, result .getStringExtra(WikiNoteEditor.ACTIVITY_RESULT)); values.put(WikiNote.Notes.MODIFIED_DATE, System .currentTimeMillis()); getContentResolver().update(noteUri, values, "_id = " + c.getInt(0), null); showWikiNote(c.getString(c .getColumnIndexOrThrow(WikiNote.Notes.BODY))); } } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.clc.bt; import java.util.Arrays; import java.util.List; /** * Model of a "ball" object used by the demo app. */ public class Demo_Ball { public enum BOUNCE_TYPE { TOPLEFT, TOP, TOPRIGHT, LEFT, RIGHT, BOTTOMLEFT, BOTTOM, BOTTOMRIGHT } private final float radius = 20; private final float pxPerM = 2; // Let 2 pixels represent 1 meter private final float reboundEnergyFactor = 0.6f; // Amount of energy returned // when rebounding private float xPos = 160; private float yPos = 240; private float xMax = 320; private float yMax = 410; private float xAcceleration = 0; private float yAcceleration = 0; private float xVelocity = 0; private float yVelocity = 0; private float reboundXPos = 0; private float reboundYPos = 0; private float reboundXVelocity = 0; private float reboundYVelocity = 0; private long lastUpdate; private boolean onScreen; public Demo_Ball(boolean visible) { onScreen = visible; lastUpdate = System.currentTimeMillis(); } public Demo_Ball(boolean visible, int screenSizeX, int screenSizeY) { onScreen = visible; lastUpdate = System.currentTimeMillis(); xMax = screenSizeX; yMax = screenSizeY; } public float getRadius() { return radius; } public float getXVelocity() { return xVelocity; } public float getX() { if (!onScreen) { return -1; } return xPos; } public float getY() { if (!onScreen) { return -1; } return yPos; } public void putOnScreen(float x, float y, float ax, float ay, float vx, float vy, int startingSide) { xPos = x; yPos = y; xVelocity = vx; yVelocity = vy; xAcceleration = ax; yAcceleration = ay; lastUpdate = System.currentTimeMillis(); if (startingSide == Demo_Multiscreen.RIGHT) { xPos = xMax - radius - 2; } else if (startingSide == Demo_Multiscreen.LEFT) { xPos = radius + 2; } else if (startingSide == Demo_Multiscreen.UP) { yPos = radius + 2; } else if (startingSide == Demo_Multiscreen.DOWN) { yPos = yMax - radius - 2; } else if (startingSide == AirHockey.FLIPTOP) { yPos = radius + 2; xPos = xMax - x; if (xPos < 0){ xPos = 0; } yVelocity = -vy; yAcceleration = -ay; } onScreen = true; } public void setAcceleration(float ax, float ay) { if (!onScreen) { return; } xAcceleration = ax; yAcceleration = ay; } public boolean isOnScreen(){ return onScreen; } public int update() { if (!onScreen) { return 0; } long currentTime = System.currentTimeMillis(); long elapsed = currentTime - lastUpdate; lastUpdate = currentTime; xVelocity += ((elapsed * xAcceleration) / 1000) * pxPerM; yVelocity += ((elapsed * yAcceleration) / 1000) * pxPerM; xPos += ((xVelocity * elapsed) / 1000) * pxPerM; yPos += ((yVelocity * elapsed) / 1000) * pxPerM; // Handle rebounding if (yPos - radius < 0) { reboundXPos = xPos; reboundYPos = radius; reboundXVelocity = xVelocity; reboundYVelocity = -yVelocity * reboundEnergyFactor; onScreen = false; return Demo_Multiscreen.UP; } else if (yPos + radius > yMax) { reboundXPos = xPos; reboundYPos = yMax - radius; reboundXVelocity = xVelocity; reboundYVelocity = -yVelocity * reboundEnergyFactor; onScreen = false; return Demo_Multiscreen.DOWN; } if (xPos - radius < 0) { reboundXPos = radius; reboundYPos = yPos; reboundXVelocity = -xVelocity * reboundEnergyFactor; reboundYVelocity = yVelocity; onScreen = false; return Demo_Multiscreen.LEFT; } else if (xPos + radius > xMax) { reboundXPos = xMax - radius; reboundYPos = yPos; reboundXVelocity = -xVelocity * reboundEnergyFactor; reboundYVelocity = yVelocity; onScreen = false; return Demo_Multiscreen.RIGHT; } return Demo_Multiscreen.CENTER; } public void doRebound() { xPos = reboundXPos; yPos = reboundYPos; xVelocity = reboundXVelocity; yVelocity = reboundYVelocity; onScreen = true; } public String getState() { String state = ""; state = xPos + "|" + yPos + "|" + xAcceleration + "|" + yAcceleration + "|" + xVelocity + "|" + yVelocity; return state; } public void restoreState(String state) { List<String> stateInfo = Arrays.asList(state.split("\\|")); putOnScreen(Float.parseFloat(stateInfo.get(0)), Float.parseFloat(stateInfo.get(1)), Float .parseFloat(stateInfo.get(2)), Float.parseFloat(stateInfo.get(3)), Float .parseFloat(stateInfo.get(4)), Float.parseFloat(stateInfo.get(5)), Integer .parseInt(stateInfo.get(6))); } public void doBounce(BOUNCE_TYPE bounceType, float vX, float vY){ switch (bounceType){ case TOPLEFT: if (xVelocity > 0){ xVelocity = -xVelocity * reboundEnergyFactor; } if (yVelocity > 0){ yVelocity = -yVelocity * reboundEnergyFactor; } break; case TOP: if (yVelocity > 0){ yVelocity = -yVelocity * reboundEnergyFactor; } break; case TOPRIGHT: if (xVelocity < 0){ xVelocity = -xVelocity * reboundEnergyFactor; } if (yVelocity > 0){ yVelocity = -yVelocity * reboundEnergyFactor; } break; case LEFT: if (xVelocity > 0){ xVelocity = -xVelocity * reboundEnergyFactor; } break; case RIGHT: if (xVelocity < 0){ xVelocity = -xVelocity * reboundEnergyFactor; } break; case BOTTOMLEFT: if (xVelocity > 0){ xVelocity = -xVelocity * reboundEnergyFactor; } if (yVelocity < 0){ yVelocity = -yVelocity * reboundEnergyFactor; } break; case BOTTOM: if (yVelocity < 0){ yVelocity = -yVelocity * reboundEnergyFactor; } break; case BOTTOMRIGHT: if (xVelocity < 0){ xVelocity = -xVelocity * reboundEnergyFactor; } if (yVelocity < 0){ yVelocity = -yVelocity * reboundEnergyFactor; } break; } xVelocity = xVelocity + (vX * 500); yVelocity = yVelocity + (vY * 150); } }
Java
package net.clc.bt; import net.clc.bt.Connection.OnConnectionLostListener; import net.clc.bt.Connection.OnConnectionServiceReadyListener; import net.clc.bt.Connection.OnIncomingConnectionListener; import net.clc.bt.Connection.OnMaxConnectionsReachedListener; import net.clc.bt.Connection.OnMessageReceivedListener; import net.clc.bt.Demo_Ball.BOUNCE_TYPE; import android.app.Activity; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.SoundPool; import android.os.Bundle; import android.util.Log; import android.view.Display; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.WindowManager; import android.view.SurfaceHolder.Callback; import android.view.WindowManager.BadTokenException; import android.widget.Toast; import java.util.ArrayList; public class AirHockey extends Activity implements Callback { public static final String TAG = "AirHockey"; private static final int SERVER_LIST_RESULT_CODE = 42; public static final int UP = 3; public static final int DOWN = 4; public static final int FLIPTOP = 5; private AirHockey self; private int mType; // 0 = server, 1 = client private SurfaceView mSurface; private SurfaceHolder mHolder; private Paint bgPaint; private Paint goalPaint; private Paint ballPaint; private Paint paddlePaint; private PhysicsLoop pLoop; private ArrayList<Point> mPaddlePoints; private ArrayList<Long> mPaddleTimes; private int mPaddlePointWindowSize = 5; private int mPaddleRadius = 55; private Bitmap mPaddleBmp; private Demo_Ball mBall; private int mBallRadius = 40; private Connection mConnection; private String rivalDevice = ""; private SoundPool mSoundPool; private int tockSound = 0; private MediaPlayer mPlayer; private int hostScore = 0; private int clientScore = 0; private OnMessageReceivedListener dataReceivedListener = new OnMessageReceivedListener() { public void OnMessageReceived(String device, String message) { if (message.indexOf("SCORE") == 0) { String[] scoreMessageSplit = message.split(":"); hostScore = Integer.parseInt(scoreMessageSplit[1]); clientScore = Integer.parseInt(scoreMessageSplit[2]); showScore(); } else { mBall.restoreState(message); } } }; private OnMaxConnectionsReachedListener maxConnectionsListener = new OnMaxConnectionsReachedListener() { public void OnMaxConnectionsReached() { } }; private OnIncomingConnectionListener connectedListener = new OnIncomingConnectionListener() { public void OnIncomingConnection(String device) { rivalDevice = device; WindowManager w = getWindowManager(); Display d = w.getDefaultDisplay(); int width = d.getWidth(); int height = d.getHeight(); mBall = new Demo_Ball(true, width, height - 60); mBall.putOnScreen(width / 2, (height / 2 + (int) (height * .05)), 0, 0, 0, 0, 0); } }; private OnConnectionLostListener disconnectedListener = new OnConnectionLostListener() { public void OnConnectionLost(String device) { class displayConnectionLostAlert implements Runnable { public void run() { Builder connectionLostAlert = new Builder(self); connectionLostAlert.setTitle("Connection lost"); connectionLostAlert .setMessage("Your connection with the other player has been lost."); connectionLostAlert.setPositiveButton("Ok", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); connectionLostAlert.setCancelable(false); try { connectionLostAlert.show(); } catch (BadTokenException e){ // Something really bad happened here; // seems like the Activity itself went away before // the runnable finished. // Bail out gracefully here and do nothing. } } } self.runOnUiThread(new displayConnectionLostAlert()); } }; private OnConnectionServiceReadyListener serviceReadyListener = new OnConnectionServiceReadyListener() { public void OnConnectionServiceReady() { if (mType == 0) { mConnection.startServer(1, connectedListener, maxConnectionsListener, dataReceivedListener, disconnectedListener); self.setTitle("Air Hockey: " + mConnection.getName() + "-" + mConnection.getAddress()); } else { WindowManager w = getWindowManager(); Display d = w.getDefaultDisplay(); int width = d.getWidth(); int height = d.getHeight(); mBall = new Demo_Ball(false, width, height - 60); Intent serverListIntent = new Intent(self, ServerListActivity.class); startActivityForResult(serverListIntent, SERVER_LIST_RESULT_CODE); } } }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); self = this; mPaddleBmp = BitmapFactory.decodeResource(getResources(), R.drawable.paddlelarge); mPaddlePoints = new ArrayList<Point>(); mPaddleTimes = new ArrayList<Long>(); Intent startingIntent = getIntent(); mType = startingIntent.getIntExtra("TYPE", 0); setContentView(R.layout.main); mSurface = (SurfaceView) findViewById(R.id.surface); mHolder = mSurface.getHolder(); bgPaint = new Paint(); bgPaint.setColor(Color.BLACK); goalPaint = new Paint(); goalPaint.setColor(Color.RED); ballPaint = new Paint(); ballPaint.setColor(Color.GREEN); ballPaint.setAntiAlias(true); paddlePaint = new Paint(); paddlePaint.setColor(Color.BLUE); paddlePaint.setAntiAlias(true); mPlayer = MediaPlayer.create(this, R.raw.collision); mConnection = new Connection(this, serviceReadyListener); mHolder.addCallback(self); } @Override protected void onDestroy() { if (mConnection != null) { mConnection.shutdown(); } if (mPlayer != null) { mPlayer.release(); } super.onDestroy(); } public void surfaceCreated(SurfaceHolder holder) { pLoop = new PhysicsLoop(); pLoop.start(); } private void draw() { Canvas canvas = null; try { canvas = mHolder.lockCanvas(); if (canvas != null) { doDraw(canvas); } } finally { if (canvas != null) { mHolder.unlockCanvasAndPost(canvas); } } } private void doDraw(Canvas c) { c.drawRect(0, 0, c.getWidth(), c.getHeight(), bgPaint); c.drawRect(0, c.getHeight() - (int) (c.getHeight() * 0.02), c.getWidth(), c.getHeight(), goalPaint); if (mPaddleTimes.size() > 0) { Point p = mPaddlePoints.get(mPaddlePoints.size() - 1); // Debug circle // Point debugPaddleCircle = getPaddleCenter(); // c.drawCircle(debugPaddleCircle.x, debugPaddleCircle.y, // mPaddleRadius, ballPaint); if (p != null) { c.drawBitmap(mPaddleBmp, p.x - 60, p.y - 200, new Paint()); } } if ((mBall == null) || !mBall.isOnScreen()) { return; } float x = mBall.getX(); float y = mBall.getY(); if ((x != -1) && (y != -1)) { float xv = mBall.getXVelocity(); Bitmap bmp = BitmapFactory .decodeResource(this.getResources(), R.drawable.android_right); if (xv < 0) { bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.android_left); } // Debug circle Point debugBallCircle = getBallCenter(); // c.drawCircle(debugBallCircle.x, debugBallCircle.y, mBallRadius, // ballPaint); c.drawBitmap(bmp, x - 17, y - 23, new Paint()); } } public void surfaceDestroyed(SurfaceHolder holder) { try { pLoop.safeStop(); } finally { pLoop = null; } } private class PhysicsLoop extends Thread { private volatile boolean running = true; @Override public void run() { while (running) { try { Thread.sleep(5); draw(); if (mBall != null) { handleCollision(); int position = mBall.update(); mBall.setAcceleration(0, 0); if (position != 0) { if ((position == UP) && (rivalDevice.length() > 1)) { mConnection.sendMessage(rivalDevice, mBall.getState() + "|" + FLIPTOP); } else if (position == DOWN) { if (mType == 0) { clientScore = clientScore + 1; } else { hostScore = hostScore + 1; } mConnection.sendMessage(rivalDevice, "SCORE:" + hostScore + ":" + clientScore); showScore(); WindowManager w = getWindowManager(); Display d = w.getDefaultDisplay(); int width = d.getWidth(); int height = d.getHeight(); mBall.putOnScreen(width / 2, (height / 2 + (int) (height * .05)), 0, 0, 0, 0, 0); } else { mBall.doRebound(); } } } } catch (InterruptedException ie) { running = false; } } } public void safeStop() { running = false; interrupt(); } } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if ((resultCode == Activity.RESULT_OK) && (requestCode == SERVER_LIST_RESULT_CODE)) { String device = data.getStringExtra(ServerListActivity.EXTRA_SELECTED_ADDRESS); int connectionStatus = mConnection.connect(device, dataReceivedListener, disconnectedListener); if (connectionStatus != Connection.SUCCESS) { Toast.makeText(self, "Unable to connect; please try again.", 1).show(); } else { rivalDevice = device; } return; } } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { Point p = new Point((int) event.getX(), (int) event.getY()); mPaddlePoints.add(p); mPaddleTimes.add(System.currentTimeMillis()); } else if (event.getAction() == MotionEvent.ACTION_MOVE) { Point p = new Point((int) event.getX(), (int) event.getY()); mPaddlePoints.add(p); mPaddleTimes.add(System.currentTimeMillis()); if (mPaddleTimes.size() > mPaddlePointWindowSize) { mPaddleTimes.remove(0); mPaddlePoints.remove(0); } } else { mPaddleTimes = new ArrayList<Long>(); mPaddlePoints = new ArrayList<Point>(); } return false; } // TODO: Scale this for G1 sized screens public Point getBallCenter() { if (mBall == null) { return new Point(-1, -1); } int x = (int) mBall.getX(); int y = (int) mBall.getY(); return new Point(x + 10, y + 12); } // TODO: Scale this for G1 sized screens public Point getPaddleCenter() { if (mPaddleTimes.size() > 0) { Point p = mPaddlePoints.get(mPaddlePoints.size() - 1); int x = p.x + 10; int y = p.y - 130; return new Point(x, y); } else { return new Point(-1, -1); } } private void showScore() { class showScoreRunnable implements Runnable { public void run() { String scoreString = ""; if (mType == 0) { scoreString = hostScore + " - " + clientScore; } else { scoreString = clientScore + " - " + hostScore; } Toast.makeText(self, scoreString, 0).show(); } } self.runOnUiThread(new showScoreRunnable()); } private void handleCollision() { // TODO: Handle multiball case if (mBall == null) { return; } if (mPaddleTimes.size() < 1) { return; } Point ballCenter = getBallCenter(); Point paddleCenter = getPaddleCenter(); final int dy = ballCenter.y - paddleCenter.y; final int dx = ballCenter.x - paddleCenter.x; final float distance = dy * dy + dx * dx; if (distance < ((2 * mBallRadius) * (2 * mPaddleRadius))) { // Get paddle velocity float vX = 0; float vY = 0; Point endPoint = new Point(-1, -1); Point startPoint = new Point(-1, -1); long timeDiff = 0; try { endPoint = mPaddlePoints.get(mPaddlePoints.size() - 1); startPoint = mPaddlePoints.get(0); timeDiff = mPaddleTimes.get(mPaddleTimes.size() - 1) - mPaddleTimes.get(0); } catch (IndexOutOfBoundsException e) { // Paddle points were removed at the last moment return; } if (timeDiff > 0) { vX = ((float) (endPoint.x - startPoint.x)) / timeDiff; vY = ((float) (endPoint.y - startPoint.y)) / timeDiff; } // Determine the bounce type BOUNCE_TYPE bounceType = BOUNCE_TYPE.TOP; if ((ballCenter.x < (paddleCenter.x - mPaddleRadius / 2)) && (ballCenter.y < (paddleCenter.y - mPaddleRadius / 2))) { bounceType = BOUNCE_TYPE.TOPLEFT; } else if ((ballCenter.x > (paddleCenter.x + mPaddleRadius / 2)) && (ballCenter.y < (paddleCenter.y - mPaddleRadius / 2))) { bounceType = BOUNCE_TYPE.TOPRIGHT; } else if ((ballCenter.x < (paddleCenter.x - mPaddleRadius / 2)) && (ballCenter.y > (paddleCenter.y + mPaddleRadius / 2))) { bounceType = BOUNCE_TYPE.BOTTOMLEFT; } else if ((ballCenter.x > (paddleCenter.x + mPaddleRadius / 2)) && (ballCenter.y > (paddleCenter.y + mPaddleRadius / 2))) { bounceType = BOUNCE_TYPE.BOTTOMRIGHT; } else if ((ballCenter.x < paddleCenter.x) && (ballCenter.y > (paddleCenter.y - mPaddleRadius / 2)) && (ballCenter.y < (paddleCenter.y + mPaddleRadius / 2))) { bounceType = BOUNCE_TYPE.LEFT; } else if ((ballCenter.x > paddleCenter.x) && (ballCenter.y > (paddleCenter.y - mPaddleRadius / 2)) && (ballCenter.y < (paddleCenter.y + mPaddleRadius / 2))) { bounceType = BOUNCE_TYPE.RIGHT; } else if ((ballCenter.x > (paddleCenter.x - mPaddleRadius / 2)) && (ballCenter.x < (paddleCenter.x + mPaddleRadius / 2)) && (ballCenter.y > paddleCenter.y)) { bounceType = BOUNCE_TYPE.RIGHT; } mBall.doBounce(bounceType, vX, vY); if (!mPlayer.isPlaying()) { mPlayer.release(); mPlayer = MediaPlayer.create(this, R.raw.collision); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mPlayer.start(); } } } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.clc.bt; import net.clc.bt.IConnection; import net.clc.bt.IConnectionCallback; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; /** * API for the Bluetooth Click, Link, Compete library. This library simplifies * the process of establishing Bluetooth connections and sending data in a way * that is geared towards multi-player games. */ public class Connection { public static final String TAG = "net.clc.bt.Connection"; public static final int SUCCESS = 0; public static final int FAILURE = 1; public static final int MAX_SUPPORTED = 7; public interface OnConnectionServiceReadyListener { public void OnConnectionServiceReady(); } public interface OnIncomingConnectionListener { public void OnIncomingConnection(String device); } public interface OnMaxConnectionsReachedListener { public void OnMaxConnectionsReached(); } public interface OnMessageReceivedListener { public void OnMessageReceived(String device, String message); } public interface OnConnectionLostListener { public void OnConnectionLost(String device); } private OnConnectionServiceReadyListener mOnConnectionServiceReadyListener; private OnIncomingConnectionListener mOnIncomingConnectionListener; private OnMaxConnectionsReachedListener mOnMaxConnectionsReachedListener; private OnMessageReceivedListener mOnMessageReceivedListener; private OnConnectionLostListener mOnConnectionLostListener; private ServiceConnection mServiceConnection; private Context mContext; private String mPackageName = ""; private boolean mStarted = false; private final Object mStartLock = new Object(); private IConnection mIconnection; private IConnectionCallback mIccb = new IConnectionCallback.Stub() { public void incomingConnection(String device) throws RemoteException { if (mOnIncomingConnectionListener != null) { mOnIncomingConnectionListener.OnIncomingConnection(device); } } public void connectionLost(String device) throws RemoteException { if (mOnConnectionLostListener != null) { mOnConnectionLostListener.OnConnectionLost(device); } } public void maxConnectionsReached() throws RemoteException { if (mOnMaxConnectionsReachedListener != null) { mOnMaxConnectionsReachedListener.OnMaxConnectionsReached(); } } public void messageReceived(String device, String message) throws RemoteException { if (mOnMessageReceivedListener != null) { mOnMessageReceivedListener.OnMessageReceived(device, message); } } }; // TODO: Add a check to autodownload this service from Market if the user // does not have it already. public Connection(Context ctx, OnConnectionServiceReadyListener ocsrListener) { mOnConnectionServiceReadyListener = ocsrListener; mContext = ctx; mPackageName = ctx.getPackageName(); mServiceConnection = new ServiceConnection() { public void onServiceConnected(ComponentName name, IBinder service) { synchronized (mStartLock) { mIconnection = IConnection.Stub.asInterface(service); mStarted = true; if (mOnConnectionServiceReadyListener != null) { mOnConnectionServiceReadyListener.OnConnectionServiceReady(); } } } public void onServiceDisconnected(ComponentName name) { synchronized (mStartLock) { try { mStarted = false; mIconnection.unregisterCallback(mPackageName); mIconnection.shutdown(mPackageName); } catch (RemoteException e) { Log.e(TAG, "RemoteException in onServiceDisconnected", e); } mIconnection = null; } } }; Intent intent = new Intent("com.google.intent.action.BT_ClickLinkCompete_SERVICE"); intent.addCategory("com.google.intent.category.BT_ClickLinkCompete"); mContext.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE); } public int startServer(final int maxConnections, OnIncomingConnectionListener oicListener, OnMaxConnectionsReachedListener omcrListener, OnMessageReceivedListener omrListener, OnConnectionLostListener oclListener) { if (!mStarted) { return Connection.FAILURE; } if (maxConnections > MAX_SUPPORTED) { Log.e(TAG, "The maximum number of allowed connections is " + MAX_SUPPORTED); return Connection.FAILURE; } mOnIncomingConnectionListener = oicListener; mOnMaxConnectionsReachedListener = omcrListener; mOnMessageReceivedListener = omrListener; mOnConnectionLostListener = oclListener; try { int result = mIconnection.startServer(mPackageName, maxConnections); mIconnection.registerCallback(mPackageName, mIccb); return result; } catch (RemoteException e) { Log.e(TAG, "RemoteException in startServer", e); } return Connection.FAILURE; } public int connect(String device, OnMessageReceivedListener omrListener, OnConnectionLostListener oclListener) { if (!mStarted) { return Connection.FAILURE; } mOnMessageReceivedListener = omrListener; mOnConnectionLostListener = oclListener; try { int result = mIconnection.connect(mPackageName, device); mIconnection.registerCallback(mPackageName, mIccb); return result; } catch (RemoteException e) { Log.e(TAG, "RemoteException in connect", e); } return Connection.FAILURE; } public int sendMessage(String device, String message) { if (!mStarted) { return Connection.FAILURE; } try { return mIconnection.sendMessage(mPackageName, device, message); } catch (RemoteException e) { Log.e(TAG, "RemoteException in sendMessage", e); } return Connection.FAILURE; } public int broadcastMessage(String message) { if (!mStarted) { return Connection.FAILURE; } try { return mIconnection.broadcastMessage(mPackageName, message); } catch (RemoteException e) { Log.e(TAG, "RemoteException in broadcastMessage", e); } return Connection.FAILURE; } public String getConnections() { if (!mStarted) { return ""; } try { return mIconnection.getConnections(mPackageName); } catch (RemoteException e) { Log.e(TAG, "RemoteException in getConnections", e); } return ""; } public int getVersion() { if (!mStarted) { return Connection.FAILURE; } try { return mIconnection.getVersion(); } catch (RemoteException e) { Log.e(TAG, "RemoteException in getVersion", e); } return Connection.FAILURE; } public String getAddress() { if (!mStarted) { return ""; } try { return mIconnection.getAddress(); } catch (RemoteException e) { Log.e(TAG, "RemoteException in getAddress", e); } return ""; } public String getName() { if (!mStarted) { return ""; } try { return mIconnection.getName(); } catch (RemoteException e) { Log.e(TAG, "RemoteException in getVersion", e); } return ""; } public void shutdown() { try { mStarted = false; if (mIconnection != null) { mIconnection.shutdown(mPackageName); } mContext.unbindService(mServiceConnection); } catch (RemoteException e) { Log.e(TAG, "RemoteException in shutdown", e); } } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.clc.bt; import android.app.Activity; import android.app.ListActivity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Parcelable; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; /** * A simple list activity that displays Bluetooth devices that are in * discoverable mode. This can be used as a gamelobby where players can see * available servers and pick the one they wish to connect to. */ public class ServerListActivity extends ListActivity { public static String EXTRA_SELECTED_ADDRESS = "btaddress"; private BluetoothAdapter myBt; private ServerListActivity self; private ArrayAdapter<String> arrayAdapter; private BroadcastReceiver myReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Parcelable btParcel = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); BluetoothDevice btDevice = (BluetoothDevice) btParcel; arrayAdapter.add(btDevice.getName() + " - " + btDevice.getAddress()); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); self = this; arrayAdapter = new ArrayAdapter<String>(self, R.layout.text); ListView lv = self.getListView(); lv.setAdapter(arrayAdapter); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { myBt.cancelDiscovery(); // Cancel BT discovery explicitly so // that connections can go through String btDeviceInfo = ((TextView) arg1).getText().toString(); String btHardwareAddress = btDeviceInfo.substring(btDeviceInfo.length() - 17); Intent i = new Intent(); i.putExtra(EXTRA_SELECTED_ADDRESS, btHardwareAddress); self.setResult(Activity.RESULT_OK, i); finish(); } }); myBt = BluetoothAdapter.getDefaultAdapter(); myBt.startDiscovery(); self.setResult(Activity.RESULT_CANCELED); } @Override protected void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(myReceiver, filter); } @Override protected void onPause() { super.onPause(); this.unregisterReceiver(myReceiver); } @Override protected void onDestroy() { super.onDestroy(); if (myBt != null) { myBt.cancelDiscovery(); // Ensure that we don't leave discovery // running by accident } } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.clc.bt; import net.clc.bt.IConnection; import net.clc.bt.IConnectionCallback; import android.app.Service; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothServerSocket; import android.bluetooth.BluetoothSocket; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.UUID; /** * Service for simplifying the process of establishing Bluetooth connections and * sending data in a way that is geared towards multi-player games. */ public class ConnectionService extends Service { public static final String TAG = "net.clc.bt.ConnectionService"; private ArrayList<UUID> mUuid; private ConnectionService mSelf; private String mApp; // Assume only one app can use this at a time; may // change this later private IConnectionCallback mCallback; private ArrayList<String> mBtDeviceAddresses; private HashMap<String, BluetoothSocket> mBtSockets; private HashMap<String, Thread> mBtStreamWatcherThreads; private BluetoothAdapter mBtAdapter; public ConnectionService() { mSelf = this; mBtAdapter = BluetoothAdapter.getDefaultAdapter(); mApp = ""; mBtSockets = new HashMap<String, BluetoothSocket>(); mBtDeviceAddresses = new ArrayList<String>(); mBtStreamWatcherThreads = new HashMap<String, Thread>(); mUuid = new ArrayList<UUID>(); // Allow up to 7 devices to connect to the server mUuid.add(UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666")); mUuid.add(UUID.fromString("503c7430-bc23-11de-8a39-0800200c9a66")); mUuid.add(UUID.fromString("503c7431-bc23-11de-8a39-0800200c9a66")); mUuid.add(UUID.fromString("503c7432-bc23-11de-8a39-0800200c9a66")); mUuid.add(UUID.fromString("503c7433-bc23-11de-8a39-0800200c9a66")); mUuid.add(UUID.fromString("503c7434-bc23-11de-8a39-0800200c9a66")); mUuid.add(UUID.fromString("503c7435-bc23-11de-8a39-0800200c9a66")); } @Override public IBinder onBind(Intent arg0) { return mBinder; } private class BtStreamWatcher implements Runnable { private String address; public BtStreamWatcher(String deviceAddress) { address = deviceAddress; } public void run() { int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; BluetoothSocket bSock = mBtSockets.get(address); try { InputStream instream = bSock.getInputStream(); int bytesRead = -1; String message = ""; while (true) { message = ""; bytesRead = instream.read(buffer); if (bytesRead != -1) { while ((bytesRead == bufferSize) && (buffer[bufferSize - 1] != 0)) { message = message + new String(buffer, 0, bytesRead); bytesRead = instream.read(buffer); } message = message + new String(buffer, 0, bytesRead - 1); // Remove // the // stop // marker mCallback.messageReceived(address, message); } } } catch (IOException e) { Log.i(TAG, "IOException in BtStreamWatcher - probably caused by normal disconnection", e); } catch (RemoteException e) { Log.e(TAG, "RemoteException in BtStreamWatcher while reading data", e); } // Getting out of the while loop means the connection is dead. try { mBtDeviceAddresses.remove(address); mBtSockets.remove(address); mBtStreamWatcherThreads.remove(address); mCallback.connectionLost(address); } catch (RemoteException e) { Log.e(TAG, "RemoteException in BtStreamWatcher while disconnecting", e); } } } private class ConnectionWaiter implements Runnable { private String srcApp; private int maxConnections; public ConnectionWaiter(String theApp, int connections) { srcApp = theApp; maxConnections = connections; } public void run() { try { for (int i = 0; i < Connection.MAX_SUPPORTED && maxConnections > 0; i++) { BluetoothServerSocket myServerSocket = mBtAdapter .listenUsingRfcommWithServiceRecord(srcApp, mUuid.get(i)); BluetoothSocket myBSock = myServerSocket.accept(); myServerSocket.close(); // Close the socket now that the // connection has been made. String address = myBSock.getRemoteDevice().getAddress(); mBtSockets.put(address, myBSock); mBtDeviceAddresses.add(address); Thread mBtStreamWatcherThread = new Thread(new BtStreamWatcher(address)); mBtStreamWatcherThread.start(); mBtStreamWatcherThreads.put(address, mBtStreamWatcherThread); maxConnections = maxConnections - 1; if (mCallback != null) { mCallback.incomingConnection(address); } } if (mCallback != null) { mCallback.maxConnectionsReached(); } } catch (IOException e) { Log.i(TAG, "IOException in ConnectionService:ConnectionWaiter", e); } catch (RemoteException e) { Log.e(TAG, "RemoteException in ConnectionService:ConnectionWaiter", e); } } } private BluetoothSocket getConnectedSocket(BluetoothDevice myBtServer, UUID uuidToTry) { BluetoothSocket myBSock; try { myBSock = myBtServer.createRfcommSocketToServiceRecord(uuidToTry); myBSock.connect(); return myBSock; } catch (IOException e) { Log.i(TAG, "IOException in getConnectedSocket", e); } return null; } private final IConnection.Stub mBinder = new IConnection.Stub() { public int startServer(String srcApp, int maxConnections) throws RemoteException { if (mApp.length() > 0) { return Connection.FAILURE; } mApp = srcApp; (new Thread(new ConnectionWaiter(srcApp, maxConnections))).start(); Intent i = new Intent(); i.setClass(mSelf, StartDiscoverableModeActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i); return Connection.SUCCESS; } public int connect(String srcApp, String device) throws RemoteException { if (mApp.length() > 0) { return Connection.FAILURE; } mApp = srcApp; BluetoothDevice myBtServer = mBtAdapter.getRemoteDevice(device); BluetoothSocket myBSock = null; for (int i = 0; i < Connection.MAX_SUPPORTED && myBSock == null; i++) { for (int j = 0; j < 3 && myBSock == null; j++) { myBSock = getConnectedSocket(myBtServer, mUuid.get(i)); if (myBSock == null) { try { Thread.sleep(200); } catch (InterruptedException e) { Log.e(TAG, "InterruptedException in connect", e); } } } } if (myBSock == null) { return Connection.FAILURE; } mBtSockets.put(device, myBSock); mBtDeviceAddresses.add(device); Thread mBtStreamWatcherThread = new Thread(new BtStreamWatcher(device)); mBtStreamWatcherThread.start(); mBtStreamWatcherThreads.put(device, mBtStreamWatcherThread); return Connection.SUCCESS; } public int broadcastMessage(String srcApp, String message) throws RemoteException { if (!mApp.equals(srcApp)) { return Connection.FAILURE; } for (int i = 0; i < mBtDeviceAddresses.size(); i++) { sendMessage(srcApp, mBtDeviceAddresses.get(i), message); } return Connection.SUCCESS; } public String getConnections(String srcApp) throws RemoteException { if (!mApp.equals(srcApp)) { return ""; } String connections = ""; for (int i = 0; i < mBtDeviceAddresses.size(); i++) { connections = connections + mBtDeviceAddresses.get(i) + ","; } return connections; } public int getVersion() throws RemoteException { try { PackageManager pm = mSelf.getPackageManager(); PackageInfo pInfo = pm.getPackageInfo(mSelf.getPackageName(), 0); return pInfo.versionCode; } catch (NameNotFoundException e) { Log.e(TAG, "NameNotFoundException in getVersion", e); } return 0; } public int registerCallback(String srcApp, IConnectionCallback cb) throws RemoteException { if (!mApp.equals(srcApp)) { return Connection.FAILURE; } mCallback = cb; return Connection.SUCCESS; } public int sendMessage(String srcApp, String destination, String message) throws RemoteException { if (!mApp.equals(srcApp)) { return Connection.FAILURE; } try { BluetoothSocket myBsock = mBtSockets.get(destination); if (myBsock != null) { OutputStream outStream = myBsock.getOutputStream(); byte[] stringAsBytes = (message + " ").getBytes(); stringAsBytes[stringAsBytes.length - 1] = 0; // Add a stop // marker outStream.write(stringAsBytes); return Connection.SUCCESS; } } catch (IOException e) { Log.i(TAG, "IOException in sendMessage - Dest:" + destination + ", Msg:" + message, e); } return Connection.FAILURE; } public void shutdown(String srcApp) throws RemoteException { try { for (int i = 0; i < mBtDeviceAddresses.size(); i++) { BluetoothSocket myBsock = mBtSockets.get(mBtDeviceAddresses.get(i)); myBsock.close(); } mBtSockets = new HashMap<String, BluetoothSocket>(); mBtStreamWatcherThreads = new HashMap<String, Thread>(); mBtDeviceAddresses = new ArrayList<String>(); mApp = ""; } catch (IOException e) { Log.i(TAG, "IOException in shutdown", e); } } public int unregisterCallback(String srcApp) throws RemoteException { if (!mApp.equals(srcApp)) { return Connection.FAILURE; } mCallback = null; return Connection.SUCCESS; } public String getAddress() throws RemoteException { return mBtAdapter.getAddress(); } public String getName() throws RemoteException { return mBtAdapter.getName(); } }; }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.clc.bt; import android.app.Activity; import android.app.AlertDialog.Builder; import android.bluetooth.BluetoothAdapter; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import android.widget.Toast; /** * A simple activity that displays a prompt telling users to enable discoverable * mode for Bluetooth. */ public class StartDiscoverableModeActivity extends Activity { public static final int REQUEST_DISCOVERABLE_CODE = 42; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent i = new Intent(); i.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); startActivityForResult(i, REQUEST_DISCOVERABLE_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_DISCOVERABLE_CODE) { // Bluetooth Discoverable Mode does not return the standard // Activity result codes. // Instead, the result code is the duration (seconds) of // discoverability or a negative number if the user answered "NO". if (resultCode < 0) { showWarning(); } else { Toast.makeText(this, "Discoverable mode enabled.", 1).show(); finish(); } } } private void showWarning() { Builder warningDialog = new Builder(this); final Activity self = this; warningDialog.setTitle(R.string.DISCOVERABLE_MODE_NOT_ENABLED); warningDialog.setMessage(R.string.WARNING_MESSAGE); warningDialog.setPositiveButton("Yes", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(); i.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); startActivityForResult(i, REQUEST_DISCOVERABLE_CODE); } }); warningDialog.setNegativeButton("No", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Toast.makeText(self, "Discoverable mode NOT enabled.", 1).show(); finish(); } }); warningDialog.setCancelable(false); warningDialog.show(); } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.clc.bt; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; /** * A simple configuration screen that displays the user's current Bluetooth * information along with buttons for entering the Bluetooth settings menu and * for starting a demo app. This is work in progress and only the demo app * buttons are currently available. */ public class ConfigActivity extends Activity { private ConfigActivity self; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); self = this; setContentView(R.layout.config); Button startServer = (Button) findViewById(R.id.start_hockey_server); startServer.setOnClickListener(new OnClickListener() { public void onClick(View v) { //Intent serverIntent = new Intent(self, Demo_Multiscreen.class); Intent serverIntent = new Intent(self, AirHockey.class); serverIntent.putExtra("TYPE", 0); startActivity(serverIntent); } }); Button startClient = (Button) findViewById(R.id.start_hockey_client); startClient.setOnClickListener(new OnClickListener() { public void onClick(View v) { //Intent clientIntent = new Intent(self, Demo_Multiscreen.class); Intent clientIntent = new Intent(self, AirHockey.class); clientIntent.putExtra("TYPE", 1); startActivity(clientIntent); } }); Button startMultiScreenServer = (Button) findViewById(R.id.start_demo_server); startMultiScreenServer.setOnClickListener(new OnClickListener() { public void onClick(View v) { //Intent serverIntent = new Intent(self, Demo_Multiscreen.class); Intent serverIntent = new Intent(self, Demo_Multiscreen.class); serverIntent.putExtra("TYPE", 0); startActivity(serverIntent); } }); Button startMultiScreenClient = (Button) findViewById(R.id.start_demo_client); startMultiScreenClient.setOnClickListener(new OnClickListener() { public void onClick(View v) { //Intent clientIntent = new Intent(self, Demo_Multiscreen.class); Intent clientIntent = new Intent(self, Demo_Multiscreen.class); clientIntent.putExtra("TYPE", 1); startActivity(clientIntent); } }); Button startVideoServer = (Button) findViewById(R.id.start_video_server); startVideoServer.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent serverIntent = new Intent(self, MultiScreenVideo.class); serverIntent.putExtra("isMaster", true); startActivity(serverIntent); } }); Button startVideoClient = (Button) findViewById(R.id.start_video_client); startVideoClient.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent clientIntent = new Intent(self, MultiScreenVideo.class); clientIntent.putExtra("isMaster", false); startActivity(clientIntent); } }); Button gotoWeb = (Button) findViewById(R.id.goto_website); gotoWeb.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent i = new Intent(); i.setAction("android.intent.action.VIEW"); i.addCategory("android.intent.category.BROWSABLE"); Uri uri = Uri.parse("http://apps-for-android.googlecode.com/svn/trunk/BTClickLinkCompete/docs/index.html"); i.setData(uri); self.startActivity(i); } }); } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.clc.bt; import net.clc.bt.Connection.OnConnectionLostListener; import net.clc.bt.Connection.OnConnectionServiceReadyListener; import net.clc.bt.Connection.OnIncomingConnectionListener; import net.clc.bt.Connection.OnMaxConnectionsReachedListener; import net.clc.bt.Connection.OnMessageReceivedListener; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.SurfaceHolder.Callback; import android.widget.Toast; /** * Demo application that allows multiple Androids to be linked together as if * they were one large screen. The center screen is the server, and it can link * to 4 other devices: right, left, up, and down. */ public class Demo_Multiscreen extends Activity implements Callback { public static final String TAG = "Demo_Multiscreen"; public static final int CENTER = 0; public static final int RIGHT = 1; public static final int LEFT = 2; public static final int UP = 3; public static final int DOWN = 4; private static final int SERVER_LIST_RESULT_CODE = 42; private Demo_Multiscreen self; private long lastTouchedTime = 0; private int mType; // 0 = server, 1 = client private int mPosition; // The device that has the ball private SurfaceView mSurface; private SurfaceHolder mHolder; private Demo_Ball mBall; private Paint bgPaint; private Paint ballPaint; private Connection mConnection; private String rightDevice = ""; private String leftDevice = ""; private String upDevice = ""; private String downDevice = ""; private OnMessageReceivedListener dataReceivedListener = new OnMessageReceivedListener() { public void OnMessageReceived(String device, String message) { if (message.startsWith("ASSIGNMENT:")) { if (message.equals("ASSIGNMENT:RIGHT")) { leftDevice = device; } else if (message.equals("ASSIGNMENT:LEFT")) { rightDevice = device; } else if (message.equals("ASSIGNMENT:UP")) { downDevice = device; } else if (message.equals("ASSIGNMENT:DOWN")) { upDevice = device; } } else { mPosition = CENTER; mBall.restoreState(message); } } }; private OnMaxConnectionsReachedListener maxConnectionsListener = new OnMaxConnectionsReachedListener() { public void OnMaxConnectionsReached() { Log.e(TAG, "Max connections reached!"); } }; private OnIncomingConnectionListener connectedListener = new OnIncomingConnectionListener() { public void OnIncomingConnection(String device) { if (rightDevice.length() < 1) { mConnection.sendMessage(device, "ASSIGNMENT:RIGHT"); rightDevice = device; } else if (leftDevice.length() < 1) { mConnection.sendMessage(device, "ASSIGNMENT:LEFT"); leftDevice = device; } else if (upDevice.length() < 1) { mConnection.sendMessage(device, "ASSIGNMENT:UP"); upDevice = device; } else if (downDevice.length() < 1) { mConnection.sendMessage(device, "ASSIGNMENT:DOWN"); downDevice = device; } } }; private OnConnectionLostListener disconnectedListener = new OnConnectionLostListener() { public void OnConnectionLost(String device) { if (rightDevice.equals(device)) { rightDevice = ""; if (mPosition == RIGHT) { mBall = new Demo_Ball(true); } } else if (leftDevice.equals(device)) { leftDevice = ""; if (mPosition == LEFT) { mBall = new Demo_Ball(true); } } else if (upDevice.equals(device)) { upDevice = ""; if (mPosition == UP) { mBall = new Demo_Ball(true); } } else if (downDevice.equals(device)) { downDevice = ""; if (mPosition == DOWN) { mBall = new Demo_Ball(true); } } } }; private OnConnectionServiceReadyListener serviceReadyListener = new OnConnectionServiceReadyListener() { public void OnConnectionServiceReady() { if (mType == 0) { mBall = new Demo_Ball(true); mConnection.startServer(4, connectedListener, maxConnectionsListener, dataReceivedListener, disconnectedListener); self.setTitle("MultiScreen: " + mConnection.getName() + "-" + mConnection.getAddress()); } else { mBall = new Demo_Ball(false); Intent serverListIntent = new Intent(self, ServerListActivity.class); startActivityForResult(serverListIntent, SERVER_LIST_RESULT_CODE); } } }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); self = this; Intent startingIntent = getIntent(); mType = startingIntent.getIntExtra("TYPE", 0); setContentView(R.layout.main); mSurface = (SurfaceView) findViewById(R.id.surface); mHolder = mSurface.getHolder(); bgPaint = new Paint(); bgPaint.setColor(Color.BLACK); ballPaint = new Paint(); ballPaint.setColor(Color.GREEN); ballPaint.setAntiAlias(true); mConnection = new Connection(this, serviceReadyListener); mHolder.addCallback(self); } private PhysicsLoop pLoop; @Override protected void onDestroy() { if (mConnection != null) { mConnection.shutdown(); } super.onDestroy(); } public void surfaceCreated(SurfaceHolder holder) { pLoop = new PhysicsLoop(); pLoop.start(); } private void draw() { Canvas canvas = null; try { canvas = mHolder.lockCanvas(); if (canvas != null) { doDraw(canvas); } } finally { if (canvas != null) { mHolder.unlockCanvasAndPost(canvas); } } } private void doDraw(Canvas c) { c.drawRect(0, 0, c.getWidth(), c.getHeight(), bgPaint); if (mBall == null) { return; } float x = mBall.getX(); float y = mBall.getY(); if ((x != -1) && (y != -1)) { float xv = mBall.getXVelocity(); Bitmap bmp = BitmapFactory .decodeResource(this.getResources(), R.drawable.android_right); if (xv < 0) { bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.android_left); } c.drawBitmap(bmp, x - 17, y - 23, new Paint()); } } public void surfaceDestroyed(SurfaceHolder holder) { try { pLoop.safeStop(); } finally { pLoop = null; } } private class PhysicsLoop extends Thread { private volatile boolean running = true; @Override public void run() { while (running) { try { Thread.sleep(5); draw(); if (mBall != null) { int position = mBall.update(); mBall.setAcceleration(0, 0); if (position == RIGHT) { if ((rightDevice.length() > 1) && (mConnection.sendMessage(rightDevice, mBall.getState() + "|" + LEFT) == Connection.SUCCESS)) { mPosition = RIGHT; } else { mBall.doRebound(); } } else if (position == LEFT) { if ((leftDevice.length() > 1) && (mConnection.sendMessage(leftDevice, mBall.getState() + "|" + RIGHT) == Connection.SUCCESS)) { mPosition = LEFT; } else { mBall.doRebound(); } } else if (position == UP) { if ((upDevice.length() > 1) && (mConnection.sendMessage(upDevice, mBall.getState() + "|" + DOWN) == Connection.SUCCESS)) { mPosition = UP; } else { mBall.doRebound(); } } else if (position == DOWN) { if ((downDevice.length() > 1) && (mConnection.sendMessage(downDevice, mBall.getState() + "|" + UP) == Connection.SUCCESS)) { mPosition = DOWN; } else { mBall.doRebound(); } } } } catch (InterruptedException ie) { running = false; } } } public void safeStop() { running = false; interrupt(); } } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if ((resultCode == Activity.RESULT_OK) && (requestCode == SERVER_LIST_RESULT_CODE)) { String device = data.getStringExtra(ServerListActivity.EXTRA_SELECTED_ADDRESS); int connectionStatus = mConnection.connect(device, dataReceivedListener, disconnectedListener); if (connectionStatus != Connection.SUCCESS) { Toast.makeText(self, "Unable to connect; please try again.", 1).show(); } return; } } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { lastTouchedTime = System.currentTimeMillis(); } else if (event.getAction() == MotionEvent.ACTION_UP) { float startX = event.getHistoricalX(0); float startY = event.getHistoricalY(0); float endX = event.getX(); float endY = event.getY(); long timeMs = (System.currentTimeMillis() - lastTouchedTime); float time = timeMs / 1000.0f; float aX = 2 * (endX - startX) / (time * time * 5); float aY = 2 * (endY - startY) / (time * time * 5); // Log.e("Physics debug", startX + " : " + startY + " : " + endX + // " : " + endY + " : " + time + " : " + aX + " : " + aY); float dampeningFudgeFactor = (float) 0.3; if (mBall != null) { mBall.setAcceleration(aX * dampeningFudgeFactor, aY * dampeningFudgeFactor); } return true; } return false; } }
Java
package net.clc.bt; import net.clc.bt.Connection.OnConnectionLostListener; import net.clc.bt.Connection.OnConnectionServiceReadyListener; import net.clc.bt.Connection.OnIncomingConnectionListener; import net.clc.bt.Connection.OnMaxConnectionsReachedListener; import net.clc.bt.Connection.OnMessageReceivedListener; import android.app.Activity; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Point; import android.media.MediaPlayer; import android.os.Bundle; import android.util.Log; import android.view.Display; import android.view.Gravity; import android.view.SurfaceView; import android.view.WindowManager; import android.view.WindowManager.BadTokenException; import android.widget.LinearLayout; import android.widget.Toast; import android.widget.VideoView; import java.util.ArrayList; public class MultiScreenVideo extends Activity { private class MultiScreenVideoView extends VideoView { public static final int POSITION_LEFT = 0; public static final int POSITION_RIGHT = 1; private int pos; public MultiScreenVideoView(Context context, int position) { super(context); pos = position; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { widthMeasureSpec = MeasureSpec.makeMeasureSpec(960, MeasureSpec.EXACTLY); heightMeasureSpec = MeasureSpec.makeMeasureSpec(640, MeasureSpec.EXACTLY); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } private boolean canSend = true; private class PositionSyncerThread implements Runnable { public void run() { while (mVideo != null) { if (canSend) { canSend = false; mConnection.sendMessage(connectedDevice, "SYNC:" + mVideo.getCurrentPosition()); } try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } private static final int SERVER_LIST_RESULT_CODE = 42; private MultiScreenVideo self; private MultiScreenVideoView mVideo; private Connection mConnection; private String connectedDevice = ""; private boolean isMaster = false; private int lastSynced = 0; private OnMessageReceivedListener dataReceivedListener = new OnMessageReceivedListener() { public void OnMessageReceived(String device, String message) { if (message.indexOf("SYNC") == 0) { try { String[] syncMessageSplit = message.split(":"); int diff = Integer.parseInt(syncMessageSplit[1]) - mVideo.getCurrentPosition(); Log.e("master - slave diff", Integer.parseInt(syncMessageSplit[1]) - mVideo.getCurrentPosition() + ""); if ((Math.abs(diff) > 100) && (mVideo.getCurrentPosition() - lastSynced > 1000)) { mVideo.seekTo(mVideo.getCurrentPosition() + diff + 300); lastSynced = mVideo.getCurrentPosition() + diff + 300; } } catch (IllegalStateException e) { // Do nothing; this can happen as you are quitting the app // mid video } mConnection.sendMessage(connectedDevice, "ACK"); } else if (message.indexOf("START") == 0) { Log.e("received start", "0"); mVideo.start(); } else if (message.indexOf("ACK") == 0) { canSend = true; } } }; private OnMaxConnectionsReachedListener maxConnectionsListener = new OnMaxConnectionsReachedListener() { public void OnMaxConnectionsReached() { } }; private OnIncomingConnectionListener connectedListener = new OnIncomingConnectionListener() { public void OnIncomingConnection(String device) { connectedDevice = device; if (isMaster) { Log.e("device connected", connectedDevice); mConnection.sendMessage(connectedDevice, "START"); new Thread(new PositionSyncerThread()).start(); try { Thread.sleep(400); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } mVideo.start(); } } }; private OnConnectionLostListener disconnectedListener = new OnConnectionLostListener() { public void OnConnectionLost(String device) { class displayConnectionLostAlert implements Runnable { public void run() { Builder connectionLostAlert = new Builder(self); connectionLostAlert.setTitle("Connection lost"); connectionLostAlert .setMessage("Your connection with the other Android has been lost."); connectionLostAlert.setPositiveButton("Ok", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); connectionLostAlert.setCancelable(false); try { connectionLostAlert.show(); } catch (BadTokenException e) { // Something really bad happened here; // seems like the Activity itself went away before // the runnable finished. // Bail out gracefully here and do nothing. } } } self.runOnUiThread(new displayConnectionLostAlert()); } }; private OnConnectionServiceReadyListener serviceReadyListener = new OnConnectionServiceReadyListener() { public void OnConnectionServiceReady() { if (isMaster) { mConnection.startServer(1, connectedListener, maxConnectionsListener, dataReceivedListener, disconnectedListener); self.setTitle("MultiScreen Video: " + mConnection.getName() + "-" + mConnection.getAddress()); } else { Intent serverListIntent = new Intent(self, ServerListActivity.class); startActivityForResult(serverListIntent, SERVER_LIST_RESULT_CODE); } } }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); self = this; Intent startingIntent = getIntent(); isMaster = startingIntent.getBooleanExtra("isMaster", false); int pos = MultiScreenVideoView.POSITION_LEFT; if (!isMaster) { pos = MultiScreenVideoView.POSITION_RIGHT; } mVideo = new MultiScreenVideoView(this, pos); mVideo.setVideoPath("/sdcard/android.mp4"); LinearLayout mLinearLayout = new LinearLayout(this); if (!isMaster) { mLinearLayout.setOrientation(LinearLayout.HORIZONTAL); mLinearLayout.setGravity(Gravity.RIGHT); mLinearLayout.setPadding(0, 0, 120, 0); } mLinearLayout.addView(mVideo); setContentView(mLinearLayout); mConnection = new Connection(this, serviceReadyListener); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if ((resultCode == Activity.RESULT_OK) && (requestCode == SERVER_LIST_RESULT_CODE)) { String device = data.getStringExtra(ServerListActivity.EXTRA_SELECTED_ADDRESS); int connectionStatus = mConnection.connect(device, dataReceivedListener, disconnectedListener); if (connectionStatus != Connection.SUCCESS) { Toast.makeText(self, "Unable to connect; please try again.", 1).show(); } else { connectedDevice = device; } return; } } @Override protected void onDestroy() { super.onDestroy(); if (mConnection != null) { mConnection.shutdown(); } } }
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.divideandconquer; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.lang.ref.WeakReference; /** * A ball region is a rectangular region that contains bouncing * balls, and possibly one animating line. In its {@link #update(long)} method, * it will update all of its balls, the moving line. It detects collisions * between the balls and the moving line, and when the line is complete, handles * splitting off a new region. */ public class BallRegion extends Shape2d { private float mLeft; private float mRight; private float mTop; private float mBottom; private List<Ball> mBalls; private AnimatingLine mAnimatingLine; private boolean mShrinkingToFit = false; private long mLastUpdate = 0; private static final float PIXELS_PER_SECOND = 25.0f; private static final float SHRINK_TO_FIT_AREA_THRESH = 10000.0f; private static final float SHRINK_TO_FIT_AREA_THRESH_ONE_BALL = 20000.0f; private static final float SHRINK_TO_FIT_AREA = 1000f; private static final float MIN_EDGE = 30f; private boolean mDoneShrinking = false; private WeakReference<BallEngine.BallEventCallBack> mCallBack; /* * @param left The minimum x component * @param right The maximum x component * @param top The minimum y component * @param bottom The maximum y component * @param balls the balls of the region */ public BallRegion(long now, float left, float right, float top, float bottom, ArrayList<Ball> balls) { mLastUpdate = now; mLeft = left; mRight = right; mTop = top; mBottom = bottom; mBalls = balls; final int numBalls = mBalls.size(); for (int i = 0; i < numBalls; i++) { final Ball ball = mBalls.get(i); ball.setRegion(this); } checkShrinkToFit(); } public void setCallBack(BallEngine.BallEventCallBack callBack) { this.mCallBack = new WeakReference<BallEngine.BallEventCallBack>(callBack); } private void checkShrinkToFit() { final float area = getArea(); if (area < SHRINK_TO_FIT_AREA_THRESH) { mShrinkingToFit = true; } else if (area < SHRINK_TO_FIT_AREA_THRESH_ONE_BALL && mBalls.size() == 1) { mShrinkingToFit = true; } } public float getLeft() { return mLeft; } public float getRight() { return mRight; } public float getTop() { return mTop; } public float getBottom() { return mBottom; } public List<Ball> getBalls() { return mBalls; } public AnimatingLine getAnimatingLine() { return mAnimatingLine; } public boolean consumeDoneShrinking() { if (mDoneShrinking) { mDoneShrinking = false; return true; } return false; } public void setNow(long now) { mLastUpdate = now; // update the balls final int numBalls = mBalls.size(); for (int i = 0; i < numBalls; i++) { final Ball ball = mBalls.get(i); ball.setNow(now); } if (mAnimatingLine != null) { mAnimatingLine.setNow(now); } } /** * Update the balls an (if it exists) the animating line in this region. * @param now in millis * @return A new region if a split has occured because the animating line * finished. */ public BallRegion update(long now) { // update the animating line final boolean newRegion = (mAnimatingLine != null && mAnimatingLine.update(now)); final int numBalls = mBalls.size(); // move balls, check for collision with animating line for (int i = 0; i < numBalls; i++) { final Ball ball = mBalls.get(i); ball.update(now); if (mAnimatingLine != null && ball.isIntersecting(mAnimatingLine)) { mAnimatingLine = null; if (mCallBack != null) mCallBack.get().onBallHitsLine(now, ball, mAnimatingLine); } } // update ball to ball collisions for (int i = 0; i < numBalls; i++) { final Ball ball = mBalls.get(i); for (int j = i + 1; j < numBalls; j++) { Ball other = mBalls.get(j); if (ball.isCircleOverlapping(other)) { Ball.adjustForCollision(ball, other); break; } } } handleShrinkToFit(now); // no collsion, new region means we need to split out the apropriate // balls into a new region if (newRegion && mAnimatingLine != null) { BallRegion otherRegion = splitRegion( now, mAnimatingLine.getDirection(), mAnimatingLine.getPerpAxisOffset()); mAnimatingLine = null; return otherRegion; } else { return null; } } private void handleShrinkToFit(long now) { // update shrinking to fit if (mShrinkingToFit && mAnimatingLine == null) { if (now == mLastUpdate) return; float delta = (now - mLastUpdate) * PIXELS_PER_SECOND; delta = delta / 1000; if (getHeight() > MIN_EDGE) { mTop += delta; mBottom -= delta; } if (getWidth() > MIN_EDGE) { mLeft += delta; mRight -= delta; } final int numBalls = mBalls.size(); for (int i = 0; i < numBalls; i++) { final Ball ball = mBalls.get(i); ball.setRegion(this); } if (getArea() <= SHRINK_TO_FIT_AREA) { mShrinkingToFit = false; mDoneShrinking = true; } } mLastUpdate = now; } /** * Return whether this region can start a line at a certain point. */ public boolean canStartLineAt(float x, float y) { return !mShrinkingToFit && mAnimatingLine == null && isPointWithin(x, y); } /** * Start a horizontal line at a point. * @param now What 'now' is. * @param x The x coordinate. * @param y The y coordinate. */ public void startHorizontalLine(long now, float x, float y) { if (!canStartLineAt(x, y)) { throw new IllegalArgumentException( "can't start line with point (" + x + "," + y + ")"); } mAnimatingLine = new AnimatingLine(Direction.Horizontal, now, y, x, mLeft, mRight); } /** * Start a vertical line at a point. * @param now What 'now' is. * @param x The x coordinate. * @param y The y coordinate. */ public void startVerticalLine(long now, float x, float y) { if (!canStartLineAt(x, y)) { throw new IllegalArgumentException( "can't start line with point (" + x + "," + y + ")"); } mAnimatingLine = new AnimatingLine(Direction.Vertical, now, x, y, mTop, mBottom); } /** * Splits this region at a certain offset, shrinking this one down and returning * the other region that makes up the rest. * @param direction The direction of the line. * @param perpAxisOffset The offset of the perpendicular axis of the line. * @return A new region containing a portion of the balls. */ private BallRegion splitRegion(long now, Direction direction, float perpAxisOffset) { ArrayList<Ball> splitBalls = new ArrayList<Ball>(); if (direction == Direction.Horizontal) { Iterator<Ball> it = mBalls.iterator(); while (it.hasNext()) { Ball ball = it.next(); if (ball.getY() > perpAxisOffset) { it.remove(); splitBalls.add(ball); } } float oldBottom = mBottom; mBottom = perpAxisOffset; checkShrinkToFit(); final BallRegion region = new BallRegion(now, mLeft, mRight, perpAxisOffset, oldBottom, splitBalls); region.setCallBack(mCallBack.get()); return region; } else { assert(direction == Direction.Vertical); Iterator<Ball> it = mBalls.iterator(); while (it.hasNext()) { Ball ball = it.next(); if (ball.getX() > perpAxisOffset) { it.remove(); splitBalls.add(ball); } } float oldRight = mRight; mRight = perpAxisOffset; checkShrinkToFit(); final BallRegion region = new BallRegion(now, perpAxisOffset, oldRight, mTop, mBottom, splitBalls); region.setCallBack(mCallBack.get()); return region; } } }
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.divideandconquer; /** * A ball has a current location, a trajectory angle, a speed in pixels per * second, and a last update time. It is capable of updating itself based on * its trajectory and speed. * * It also knows its boundaries, and will 'bounce' off them when it reaches them. */ public class Ball extends Shape2d { private long mLastUpdate; private float mX; private float mY; private double mAngle; private final float mPixelsPerSecond; private final float mRadiusPixels; private Shape2d mRegion; private Ball(long now, float pixelsPerSecond, float x, float y, double angle, float radiusPixels) { mLastUpdate = now; mPixelsPerSecond = pixelsPerSecond; mX = x; mY = y; mAngle = angle; mRadiusPixels = radiusPixels; } public float getX() { return mX; } public float getY() { return mY; } public float getLeft() { return mX - mRadiusPixels; } public float getRight() { return mX + mRadiusPixels; } public float getTop() { return mY - mRadiusPixels; } public float getBottom() { return mY + mRadiusPixels; } public float getRadiusPixels() { return mRadiusPixels; } public double getAngle() { return mAngle; } /** * Get the region the ball is contained in. */ public Shape2d getRegion() { return mRegion; } /** * Set the region that the ball is contained in. * @param region The region. */ public void setRegion(Shape2d region) { if (mX < region.getLeft()) { mX = region.getLeft(); bounceOffLeft(); } else if (mX > region.getRight()) { mX = region.getRight(); bounceOffRight(); } if (mY < region.getTop()) { mY = region.getTop(); bounceOffTop(); } else if (mY > region.getBottom()) { mY = region.getBottom(); bounceOffBottom(); } mRegion = region; } public void setNow(long now) { mLastUpdate = now; } public boolean isCircleOverlapping(Ball otherBall) { final float dy = otherBall.mY - mY; final float dx = otherBall.mX - mX; final float distance = dy * dy + dx * dx; return (distance < ((2 * mRadiusPixels) * (2 *mRadiusPixels))) // avoid jittery collisions && !movingAwayFromEachother(this, otherBall); } private boolean movingAwayFromEachother(Ball ballA, Ball ballB) { double collA = Math.atan2(ballB.mY - ballA.mY, ballB.mX - ballA.mX); double collB = Math.atan2(ballA.mY - ballB.mY, ballA.mX - ballB.mX); double ax = Math.cos(ballA.mAngle - collA); double bx = Math.cos(ballB.mAngle - collB); return ax + bx < 0; } public void update(long now) { if (now <= mLastUpdate) return; // bounce when at walls if (mX <= mRegion.getLeft() + mRadiusPixels) { // we're at left wall mX = mRegion.getLeft() + mRadiusPixels; bounceOffLeft(); } else if (mY <= mRegion.getTop() + mRadiusPixels) { // at top wall mY = mRegion.getTop() + mRadiusPixels; bounceOffTop(); } else if (mX >= mRegion.getRight() - mRadiusPixels) { // at right wall mX = mRegion.getRight() - mRadiusPixels; bounceOffRight(); } else if (mY >= mRegion.getBottom() - mRadiusPixels) { // at bottom wall mY = mRegion.getBottom() - mRadiusPixels; bounceOffBottom(); } float delta = (now - mLastUpdate) * mPixelsPerSecond; delta = delta / 1000f; mX += (delta * Math.cos(mAngle)); mY += (delta * Math.sin(mAngle)); mLastUpdate = now; } private void bounceOffBottom() { if (mAngle < 0.5*Math.PI) { // going right mAngle = -mAngle; } else { // going left mAngle += (Math.PI - mAngle) * 2; } } private void bounceOffRight() { if (mAngle > 1.5*Math.PI) { // going up mAngle -= (mAngle - 1.5*Math.PI) * 2; } else { // going down mAngle += (.5*Math.PI - mAngle) * 2; } } private void bounceOffTop() { if (mAngle < 1.5 * Math.PI) { // going left mAngle -= (mAngle - Math.PI) * 2; } else { // going right mAngle += (2*Math.PI - mAngle) * 2; mAngle -= 2*Math.PI; } } private void bounceOffLeft() { if (mAngle < Math.PI) { // going down mAngle -= ((mAngle - (Math.PI / 2)) * 2); } else { // going up mAngle += (((1.5 * Math.PI) - mAngle) * 2); } } /** * Given that ball a and b have collided, adjust their angles to reflect their state * after the collision. * * This method works based on the conservation of energy and momentum in an elastic * collision. Because the balls have equal mass and speed, it ends up being that they * simply swap velocities along the axis of the collision, keeping the velocities tangent * to the collision constant. * * @param ballA The first ball in a collision * @param ballB The second ball in a collision */ public static void adjustForCollision(Ball ballA, Ball ballB) { final double collA = Math.atan2(ballB.mY - ballA.mY, ballB.mX - ballA.mX); final double collB = Math.atan2(ballA.mY - ballB.mY, ballA.mX - ballB.mX); final double ax = Math.cos(ballA.mAngle - collA); final double ay = Math.sin(ballA.mAngle - collA); final double bx = Math.cos(ballB.mAngle - collB); final double by = Math.cos(ballB.mAngle - collB); final double diffA = Math.atan2(ay, -bx); final double diffB = Math.atan2(by, -ax); ballA.mAngle = collA + diffA; ballB.mAngle = collB + diffB; } @Override public String toString() { return String.format( "Ball(x=%f, y=%f, angle=%f)", mX, mY, Math.toDegrees(mAngle)); } /** * A more readable way to create balls than using a 5 param * constructor of all numbers. */ public static class Builder { private long mNow = -1; private float mX = -1; private float mY = -1; private double mAngle = -1; private float mRadiusPixels = -1; private float mPixelsPerSecond = 45f; public Ball create() { if (mNow < 0) { throw new IllegalStateException("must set 'now'"); } if (mX < 0) { throw new IllegalStateException("X must be set"); } if (mY < 0) { throw new IllegalStateException("Y must be stet"); } if (mAngle < 0) { throw new IllegalStateException("angle must be set"); } if (mAngle > 2 * Math.PI) { throw new IllegalStateException("angle must be less that 2Pi"); } if (mRadiusPixels <= 0) { throw new IllegalStateException("radius must be set"); } return new Ball(mNow, mPixelsPerSecond, mX, mY, mAngle, mRadiusPixels); } public Builder setNow(long now) { mNow = now; return this; } public Builder setPixelsPerSecond(float pixelsPerSecond) { mPixelsPerSecond = pixelsPerSecond; return this; } public Builder setX(float x) { mX = x; return this; } public Builder setY(float y) { mY = y; return this; } public Builder setAngle(double angle) { mAngle = angle; return this; } public Builder setRadiusPixels(float pixels) { mRadiusPixels = pixels; return this; } } }
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.divideandconquer; import android.app.Dialog; import android.view.View; import android.content.Context; import android.os.Bundle; public class GameOverDialog extends Dialog implements View.OnClickListener { private View mNewGame; private final NewGameCallback mCallback; private View mQuit; public GameOverDialog(Context context, NewGameCallback callback) { super(context); mCallback = callback; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.game_over); setContentView(R.layout.game_over_dialog); mNewGame = findViewById(R.id.newGame); mNewGame.setOnClickListener(this); mQuit = findViewById(R.id.quit); mQuit.setOnClickListener(this); } /** {@inheritDoc} */ public void onClick(View v) { if (v == mNewGame) { mCallback.onNewGame(); dismiss(); } else if (v == mQuit) { cancel(); } } }
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.divideandconquer; /** * To specify a dividing line, a user hits the screen and drags in a * certain direction. Once the line has been drawn long enough and mostly * in a particular direction (vertical, or horizontal), we can decide we * know what they mean. Otherwise, it is unknown. * * This is also nice because if the user decides they don't want to send * a dividing line, they can just drag their finger back to where they first * touched and let go, cancelling. */ public class DirectionPoint { enum AmbiguousDirection { Vertical, Horizonal, Unknown } private float mX; private float mY; private float endLineX; private float endLineY; public DirectionPoint(float x, float y) { mX = x; mY = y; endLineX = x; endLineY = y; } public void updateEndPoint(float x, float y) { endLineX = x; endLineY = y; } public float getX() { return mX; } public float getY() { return mY; } /** * We know the direction when the line is at leat 20 pixels long, * and the angle is no more than PI / 6 away from a definitive direction. */ public AmbiguousDirection getDirection() { float dx = endLineX - mX; double distance = Math.hypot(dx, endLineY - mY); if (distance < 10) { return AmbiguousDirection.Unknown; } double angle = Math.acos(dx / distance); double thresh = Math.PI / 6; if ((angle < thresh || (angle > (Math.PI - thresh)))) { return AmbiguousDirection.Horizonal; } if ((angle > 2 * thresh) && angle < 4*thresh) { return AmbiguousDirection.Vertical; } return AmbiguousDirection.Unknown; } }
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.divideandconquer; import android.os.Bundle; import android.preference.*; import android.content.Context; import android.content.SharedPreferences; /** * Holds preferences for the game */ public class Preferences extends PreferenceActivity { public static final String KEY_VIBRATE = "key_vibrate"; public static final String KEY_DIFFICULTY = "key_difficulty"; public enum Difficulty { Easy(5), Medium(3), Hard(1); private final int mLivesToStart; Difficulty(int livesToStart) { mLivesToStart = livesToStart; } public int getLivesToStart() { return mLivesToStart; } } public static Difficulty getCurrentDifficulty(Context context) { final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); final String diffic = preferences .getString(KEY_DIFFICULTY, DEFAULT_DIFFICULTY.toString()); return Difficulty.valueOf(diffic); } public static final Difficulty DEFAULT_DIFFICULTY = Difficulty.Medium; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setPreferenceScreen(createPreferenceHierarchy()); } private PreferenceScreen createPreferenceHierarchy() { // Root PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this); // vibrate on/off CheckBoxPreference vibratePref = new CheckBoxPreference(this); vibratePref.setDefaultValue(true); vibratePref.setKey(KEY_VIBRATE); vibratePref.setTitle(R.string.settings_vibrate); vibratePref.setSummary(R.string.settings_vibrate_summary); root.addPreference(vibratePref); // difficulty level ListPreference difficultyPref = new ListPreference(this); difficultyPref.setEntries(new String[] { getString(R.string.settings_five_lives), getString(R.string.settings_three_lives), getString(R.string.settings_one_life)}); difficultyPref.setEntryValues(new String[] { Difficulty.Easy.toString(), Difficulty.Medium.toString(), Difficulty.Hard.toString()}); difficultyPref.setKey(KEY_DIFFICULTY); difficultyPref.setTitle(R.string.settings_difficulty); difficultyPref.setSummary(R.string.settings_difficulty_summary); final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); if (!sharedPrefs.contains(KEY_DIFFICULTY)) { difficultyPref.setValue(DEFAULT_DIFFICULTY.toString()); } root.addPreference(difficultyPref); return root; } }
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.divideandconquer; /** * Either vertical or horizontal. Used by animating lines and * ball regions. */ public enum Direction { Vertical, Horizontal }
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.divideandconquer; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; /** * When the game starts, the user is welcomed with a message, and buttons for * starting a new game, or getting instructions about the game. */ public class WelcomeDialog extends Dialog implements View.OnClickListener { private final NewGameCallback mCallback; private View mNewGame; public WelcomeDialog(Context context, NewGameCallback callback) { super(context); mCallback = callback; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.app_name); setContentView(R.layout.welcome_dialog); mNewGame = findViewById(R.id.newGame); mNewGame.setOnClickListener(this); } /** {@inheritDoc} */ public void onClick(View v) { if (v == mNewGame) { mCallback.onNewGame(); dismiss(); } } }
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.divideandconquer; import android.content.Context; import android.content.res.Resources; import android.graphics.*; import android.graphics.drawable.GradientDrawable; import android.os.Debug; import android.os.SystemClock; import android.util.AttributeSet; import android.util.TypedValue; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import java.util.List; import java.util.ArrayList; /** * Handles the visual display and touch input for the game. */ public class DivideAndConquerView extends View implements BallEngine.BallEventCallBack { static final int BORDER_WIDTH = 10; // this needs to match size of ball drawable static final float BALL_RADIUS = 5f; static final float BALL_SPEED = 80f; // if true, will profile the drawing code during each animating line and export // the result to a file named 'BallsDrawing.trace' on the sd card // this file can be pulled off and profiled with traceview // $ adb pull /sdcard/BallsDrawing.trace . // traceview BallsDrawing.trace private static final boolean PROFILE_DRAWING = false; private boolean mDrawingProfilingStarted = false; private final Paint mPaint; private BallEngine mEngine; private Mode mMode = Mode.Paused; private BallEngineCallBack mCallback; // interface for starting a line private DirectionPoint mDirectionPoint = null; private Bitmap mBallBitmap; private float mBallBitmapRadius; private final Bitmap mExplosion1; private final Bitmap mExplosion2; private final Bitmap mExplosion3; /** * Callback notifying of events related to the ball engine. */ static interface BallEngineCallBack { /** * The engine has its dimensions and is ready to go. * @param ballEngine The ball engine. */ void onEngineReady(BallEngine ballEngine); /** * A ball has hit a moving line. * @param ballEngine The engine. * @param x The x coordinate of the ball. * @param y The y coordinate of the ball. */ void onBallHitsMovingLine(BallEngine ballEngine, float x, float y); /** * A line made it to the edges of its region, splitting off a new region. * @param ballEngine The engine. */ void onAreaChange(BallEngine ballEngine); } /** * @return The ball engine associated with the game. */ public BallEngine getEngine() { return mEngine; } /** * Keeps track of the mode of this view. */ enum Mode { /** * The balls are bouncing around. */ Bouncing, /** * The animation has stopped and the balls won't move around. The user * may not unpause it; this is used to temporarily stop games between * levels, or when the game is over and the activity places a dialog up. */ Paused, /** * Same as {@link #Paused}, but paints the word 'touch to unpause' on * the screen, so the user knows he/she can unpause the game. */ PausedByUser } public DivideAndConquerView(Context context, AttributeSet attrs) { super(context, attrs); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setStrokeWidth(2); mPaint.setColor(Color.BLACK); // so we can see the back key setFocusableInTouchMode(true); drawBackgroundGradient(); mBallBitmap = BitmapFactory.decodeResource( context.getResources(), R.drawable.ball); mBallBitmapRadius = ((float) mBallBitmap.getWidth()) / 2f; mExplosion1 = BitmapFactory.decodeResource( context.getResources(), R.drawable.explosion1); mExplosion2 = BitmapFactory.decodeResource( context.getResources(), R.drawable.explosion2); mExplosion3 = BitmapFactory.decodeResource( context.getResources(), R.drawable.explosion3); } final GradientDrawable mBackgroundGradient = new GradientDrawable( GradientDrawable.Orientation.TOP_BOTTOM, new int[]{Color.RED, Color.YELLOW}); void drawBackgroundGradient() { setBackgroundDrawable(mBackgroundGradient); } /** * Set the callback that will be notified of events related to the ball * engine. * @param callback The callback. */ public void setCallback(BallEngineCallBack callback) { mCallback = callback; } @Override protected void onSizeChanged(int i, int i1, int i2, int i3) { super.onSizeChanged(i, i1, i2, i3); // this should only happen once when the activity is first launched. // we could be smarter about saving / restoring across activity // lifecycles, but for now, this is good enough to handle in game play, // and most cases of navigating away with the home key and coming back. mEngine = new BallEngine( BORDER_WIDTH, getWidth() - BORDER_WIDTH, BORDER_WIDTH, getHeight() - BORDER_WIDTH, BALL_SPEED, BALL_RADIUS); mEngine.setCallBack(this); mCallback.onEngineReady(mEngine); } /** * @return the current mode of operation. */ public Mode getMode() { return mMode; } /** * Set the mode of operation. * @param mode The mode. */ public void setMode(Mode mode) { mMode = mode; if (mMode == Mode.Bouncing && mEngine != null) { // when starting up again, the engine needs to know what 'now' is. final long now = SystemClock.elapsedRealtime(); mEngine.setNow(now); mExplosions.clear(); invalidate(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // the first time the user hits back while the balls are moving, // we'll pause the game. but if they hit back again, we'll do the usual // (exit the activity) if (keyCode == KeyEvent.KEYCODE_BACK && mMode == Mode.Bouncing) { setMode(Mode.PausedByUser); return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onTouchEvent(MotionEvent motionEvent) { if (mMode == Mode.PausedByUser) { // touching unpauses when the game was paused by the user. setMode(Mode.Bouncing); return true; } else if (mMode == Mode.Paused) { return false; } final float x = motionEvent.getX(); final float y = motionEvent.getY(); switch(motionEvent.getAction()) { case MotionEvent.ACTION_DOWN: if (mEngine.canStartLineAt(x, y)) { mDirectionPoint = new DirectionPoint(x, y); } return true; case MotionEvent.ACTION_MOVE: if (mDirectionPoint != null) { mDirectionPoint.updateEndPoint(x, y); } else if (mEngine.canStartLineAt(x, y)) { mDirectionPoint = new DirectionPoint(x, y); } return true; case MotionEvent.ACTION_UP: if (mDirectionPoint != null) { switch (mDirectionPoint.getDirection()) { case Unknown: // do nothing break; case Horizonal: mEngine.startHorizontalLine(SystemClock.elapsedRealtime(), mDirectionPoint.getX(), mDirectionPoint.getY()); if (PROFILE_DRAWING) { if (!mDrawingProfilingStarted) { Debug.startMethodTracing("BallsDrawing"); mDrawingProfilingStarted = true; } } break; case Vertical: mEngine.startVerticalLine(SystemClock.elapsedRealtime(), mDirectionPoint.getX(), mDirectionPoint.getY()); if (PROFILE_DRAWING) { if (!mDrawingProfilingStarted) { Debug.startMethodTracing("BallsDrawing"); mDrawingProfilingStarted = true; } } break; } } mDirectionPoint = null; return true; case MotionEvent.ACTION_CANCEL: mDirectionPoint = null; return true; } return false; } /** {@inheritDoc} */ public void onBallHitsBall(Ball ballA, Ball ballB) { } /** {@inheritDoc} */ public void onBallHitsLine(long when, Ball ball, AnimatingLine animatingLine) { mCallback.onBallHitsMovingLine(mEngine, ball.getX(), ball.getY()); mExplosions.add( new Explosion( when, ball.getX(), ball.getY(), mExplosion1, mExplosion2, mExplosion3)); } static class Explosion { private long mLastUpdate; private long mProgress = 0; private final float mX; private final float mY; private final Bitmap mExplosion1; private final Bitmap mExplosion2; private final Bitmap mExplosion3; private final float mRadius; Explosion(long mLastUpdate, float mX, float mY, Bitmap explosion1, Bitmap explosion2, Bitmap explosion3) { this.mLastUpdate = mLastUpdate; this.mX = mX; this.mY = mY; this.mExplosion1 = explosion1; this.mExplosion2 = explosion2; this.mExplosion3 = explosion3; mRadius = ((float) mExplosion1.getWidth()) / 2f; } public void update(long now) { mProgress += (now - mLastUpdate); mLastUpdate = now; } public void setNow(long now) { mLastUpdate = now; } public void draw(Canvas canvas, Paint paint) { if (mProgress < 80L) { canvas.drawBitmap(mExplosion1, mX - mRadius, mY - mRadius, paint); } else if (mProgress < 160L) { canvas.drawBitmap(mExplosion2, mX - mRadius, mY - mRadius, paint); } else if (mProgress < 400L) { canvas.drawBitmap(mExplosion3, mX - mRadius, mY - mRadius, paint); } } public boolean done() { return mProgress > 700L; } } private ArrayList<Explosion> mExplosions = new ArrayList<Explosion>(); @Override protected void onDraw(Canvas canvas) { boolean newRegion = false; if (mMode == Mode.Bouncing) { // handle the ball engine final long now = SystemClock.elapsedRealtime(); newRegion = mEngine.update(now); if (newRegion) { mCallback.onAreaChange(mEngine); // reset back to full alpha bg color drawBackgroundGradient(); } if (PROFILE_DRAWING) { if (newRegion && mDrawingProfilingStarted) { mDrawingProfilingStarted = false; Debug.stopMethodTracing(); } } // the X-plosions for (int i = 0; i < mExplosions.size(); i++) { final Explosion explosion = mExplosions.get(i); explosion.update(now); } } for (int i = 0; i < mEngine.getRegions().size(); i++) { BallRegion region = mEngine.getRegions().get(i); drawRegion(canvas, region); } for (int i = 0; i < mExplosions.size(); i++) { final Explosion explosion = mExplosions.get(i); explosion.draw(canvas, mPaint); // TODO prune explosions that are done } if (mMode == Mode.PausedByUser) { drawPausedText(canvas); } else if (mMode == Mode.Bouncing) { // keep em' bouncing! invalidate(); } } /** * Pain the text instructing the user how to unpause the game. */ private void drawPausedText(Canvas canvas) { mPaint.setColor(Color.BLACK); mPaint.setAntiAlias(true); mPaint.setTextSize( TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics())); final String unpauseInstructions = getContext().getString(R.string.unpause_instructions); canvas.drawText(unpauseInstructions, getWidth() / 5, getHeight() / 2, mPaint); mPaint.setAntiAlias(false); } private RectF mRectF = new RectF(); /** * Draw a ball region. */ private void drawRegion(Canvas canvas, BallRegion region) { // draw fill rect to offset against background mPaint.setColor(Color.LTGRAY); mRectF.set(region.getLeft(), region.getTop(), region.getRight(), region.getBottom()); canvas.drawRect(mRectF, mPaint); //draw an outline mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(Color.WHITE); canvas.drawRect(mRectF, mPaint); mPaint.setStyle(Paint.Style.FILL); // restore style // draw each ball for (Ball ball : region.getBalls()) { // canvas.drawCircle(ball.getX(), ball.getY(), BALL_RADIUS, mPaint); canvas.drawBitmap( mBallBitmap, ball.getX() - mBallBitmapRadius, ball.getY() - mBallBitmapRadius, mPaint); } // draw the animating line final AnimatingLine al = region.getAnimatingLine(); if (al != null) { drawAnimatingLine(canvas, al); } } private static int scaleToBlack(int component, float percentage) { // return (int) ((1f - percentage*0.4f) * component); return (int) (percentage * 0.6f * (0xFF - component) + component); } /** * Draw an animating line. */ private void drawAnimatingLine(Canvas canvas, AnimatingLine al) { final float perc = al.getPercentageDone(); final int color = Color.RED; mPaint.setColor(Color.argb( 0xFF, scaleToBlack(Color.red(color), perc), scaleToBlack(Color.green(color), perc), scaleToBlack(Color.blue(color), perc) )); switch (al.getDirection()) { case Horizontal: canvas.drawLine( al.getStart(), al.getPerpAxisOffset(), al.getEnd(), al.getPerpAxisOffset(), mPaint); break; case Vertical: canvas.drawLine( al.getPerpAxisOffset(), al.getStart(), al.getPerpAxisOffset(), al.getEnd(), mPaint); break; } } }
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.divideandconquer; /** * Keeps the state for the line that extends in two directions until it hits its boundaries. This is triggered * by the user gesture in a horizontal or vertical direction. */ public class AnimatingLine extends Shape2d { private Direction mDirection; // for vertical lines, the y offset // for horizontal, the x offset float mPerpAxisOffset; float mStart; float mEnd; float mMin; float mMax; private long mLastUpdate = 0; private float mPixelsPerSecond = 101.0f; /** * @param direction The direction of the line * @param now What 'now' is * @param axisStart Where on the perpindicular axis the line is extending from * @param start The point the line is extending from on the parallel axis * @param min The lower bound for the line (i.e the left most point) * @param max The upper bound for the line (i.e the right most point) */ public AnimatingLine( Direction direction, long now, float axisStart, float start, float min, float max) { mDirection = direction; mLastUpdate = now; mPerpAxisOffset = axisStart; mStart = mEnd = start; mMin = min; mMax = max; } public Direction getDirection() { return mDirection; } public float getPerpAxisOffset() { return mPerpAxisOffset; } public float getStart() { return mStart; } public float getEnd() { return mEnd; } public float getMin() { return mMin; } public float getMax() { return mMax; } public float getLeft() { return mDirection == Direction.Horizontal ? mStart : mPerpAxisOffset; } public float getRight() { return mDirection == Direction.Horizontal ? mEnd : mPerpAxisOffset; } public float getTop() { return mDirection == Direction.Vertical ? mStart : mPerpAxisOffset; } public float getBottom() { return mDirection == Direction.Vertical ? mEnd : mPerpAxisOffset; } public float getPercentageDone() { return (mEnd - mStart) / (mMax - mMin); } /** * Extend the line according to the animation. * @return whether the line has reached its end. */ public boolean update(long time) { if (time == mLastUpdate) return false; float delta = (time - mLastUpdate) * mPixelsPerSecond; delta = delta / 1000; mLastUpdate = time; mStart -= delta; mEnd += delta; if (mStart < mMin) mStart = mMin; if (mEnd > mMax) mEnd = mMax; return mStart == mMin && mEnd == mMax; } public void setNow(long now) { mLastUpdate = now; } }
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.divideandconquer; /** * Used by dialogs to tell the activity the user wants a new game. */ public interface NewGameCallback { /** * The user wants to start a new game. */ void onNewGame(); }
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.divideandconquer; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.SystemClock; import android.os.Vibrator; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.view.Gravity; import android.widget.TextView; import android.widget.Toast; import android.graphics.Color; import java.util.Stack; /** * The activity for the game. Listens for callbacks from the game engine, and * response appropriately, such as bringing up a 'game over' dialog when a ball * hits a moving line and there is only one life left. */ public class DivideAndConquerActivity extends Activity implements DivideAndConquerView.BallEngineCallBack, NewGameCallback, DialogInterface.OnCancelListener { private static final int NEW_GAME_NUM_BALLS = 1; private static final double LEVEL_UP_THRESHOLD = 0.8; private static final int COLLISION_VIBRATE_MILLIS = 50; private boolean mVibrateOn; private int mNumBalls = NEW_GAME_NUM_BALLS; private DivideAndConquerView mBallsView; private static final int WELCOME_DIALOG = 20; private static final int GAME_OVER_DIALOG = 21; private WelcomeDialog mWelcomeDialog; private GameOverDialog mGameOverDialog; private TextView mLivesLeft; private TextView mPercentContained; private int mNumLives; private Vibrator mVibrator; private TextView mLevelInfo; private int mNumLivesStart = 5; private Toast mCurrentToast; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Turn off the title bar requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); mBallsView = (DivideAndConquerView) findViewById(R.id.ballsView); mBallsView.setCallback(this); mPercentContained = (TextView) findViewById(R.id.percentContained); mLevelInfo = (TextView) findViewById(R.id.levelInfo); mLivesLeft = (TextView) findViewById(R.id.livesLeft); // we'll vibrate when the ball hits the moving line mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); } /** {@inheritDoc} */ public void onEngineReady(BallEngine ballEngine) { // display 10 balls bouncing around for visual effect ballEngine.reset(SystemClock.elapsedRealtime(), 10); mBallsView.setMode(DivideAndConquerView.Mode.Bouncing); // show the welcome dialog showDialog(WELCOME_DIALOG); } @Override protected Dialog onCreateDialog(int id) { if (id == WELCOME_DIALOG) { mWelcomeDialog = new WelcomeDialog(this, this); mWelcomeDialog.setOnCancelListener(this); return mWelcomeDialog; } else if (id == GAME_OVER_DIALOG) { mGameOverDialog = new GameOverDialog(this, this); mGameOverDialog.setOnCancelListener(this); return mGameOverDialog; } return null; } @Override protected void onPause() { super.onPause(); mBallsView.setMode(DivideAndConquerView.Mode.PausedByUser); } @Override protected void onResume() { super.onResume(); mVibrateOn = PreferenceManager.getDefaultSharedPreferences(this) .getBoolean(Preferences.KEY_VIBRATE, true); mNumLivesStart = Preferences.getCurrentDifficulty(this).getLivesToStart(); } private static final int MENU_NEW_GAME = Menu.FIRST; private static final int MENU_SETTINGS = Menu.FIRST + 1; @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_NEW_GAME, MENU_NEW_GAME, "New Game"); menu.add(0, MENU_SETTINGS, MENU_SETTINGS, "Settings"); return true; } /** * We pause the game while the menu is open; this remembers what it was * so we can restore when the menu closes */ Stack<DivideAndConquerView.Mode> mRestoreMode = new Stack<DivideAndConquerView.Mode>(); @Override public boolean onMenuOpened(int featureId, Menu menu) { saveMode(); mBallsView.setMode(DivideAndConquerView.Mode.Paused); return super.onMenuOpened(featureId, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case MENU_NEW_GAME: cancelToasts(); onNewGame(); break; case MENU_SETTINGS: final Intent intent = new Intent(); intent.setClass(this, Preferences.class); startActivity(intent); break; } mRestoreMode.pop(); // don't want to restore when an action was taken return true; } @Override public void onOptionsMenuClosed(Menu menu) { super.onOptionsMenuClosed(menu); restoreMode(); } private void saveMode() { // don't want to restore to a state where user can't resume game. final DivideAndConquerView.Mode mode = mBallsView.getMode(); final DivideAndConquerView.Mode toRestore = (mode == DivideAndConquerView.Mode.Paused) ? DivideAndConquerView.Mode.PausedByUser : mode; mRestoreMode.push(toRestore); } private void restoreMode() { if (!mRestoreMode.isEmpty()) { mBallsView.setMode(mRestoreMode.pop()); } } /** {@inheritDoc} */ public void onBallHitsMovingLine(final BallEngine ballEngine, float x, float y) { if (--mNumLives == 0) { saveMode(); mBallsView.setMode(DivideAndConquerView.Mode.Paused); // vibrate three times if (mVibrateOn) { mVibrator.vibrate( new long[]{0l, COLLISION_VIBRATE_MILLIS, 50l, COLLISION_VIBRATE_MILLIS, 50l, COLLISION_VIBRATE_MILLIS}, -1); } showDialog(GAME_OVER_DIALOG); } else { if (mVibrateOn) { mVibrator.vibrate(COLLISION_VIBRATE_MILLIS); } updateLivesDisplay(mNumLives); if (mNumLives <= 1) { mBallsView.postDelayed(mOneLifeToastRunnable, 700); } else { mBallsView.postDelayed(mLivesBlinkRedRunnable, 700); } } } private Runnable mOneLifeToastRunnable = new Runnable() { public void run() { showToast("1 life left!"); } }; private Runnable mLivesBlinkRedRunnable = new Runnable() { public void run() { mLivesLeft.setTextColor(Color.RED); mLivesLeft.postDelayed(mLivesTextWhiteRunnable, 2000); } }; /** {@inheritDoc} */ public void onAreaChange(final BallEngine ballEngine) { final float percentageFilled = ballEngine.getPercentageFilled(); updatePercentDisplay(percentageFilled); if (percentageFilled > LEVEL_UP_THRESHOLD) { levelUp(ballEngine); } } /** * Go to the next level * @param ballEngine The ball engine. */ private void levelUp(final BallEngine ballEngine) { mNumBalls++; updatePercentDisplay(0); updateLevelDisplay(mNumBalls); ballEngine.reset(SystemClock.elapsedRealtime(), mNumBalls); mBallsView.setMode(DivideAndConquerView.Mode.Bouncing); if (mNumBalls % 4 == 0) { mNumLives++; updateLivesDisplay(mNumLives); showToast("bonus life!"); } if (mNumBalls == 10) { showToast("Level 10? You ROCK!"); } else if (mNumBalls == 15) { showToast("BALLS TO THE WALL!"); } } private Runnable mLivesTextWhiteRunnable = new Runnable() { public void run() { mLivesLeft.setTextColor(Color.WHITE); } }; private void showToast(String text) { cancelToasts(); mCurrentToast = Toast.makeText(this, text, Toast.LENGTH_SHORT); mCurrentToast.show(); } private void cancelToasts() { if (mCurrentToast != null) { mCurrentToast.cancel(); mCurrentToast = null; } } /** * Update the header that displays how much of the space has been contained. * @param amountFilled The fraction, between 0 and 1, that is filled. */ private void updatePercentDisplay(float amountFilled) { final int prettyPercent = (int) (amountFilled *100); mPercentContained.setText( getString(R.string.percent_contained, prettyPercent)); } /** {@inheritDoc} */ public void onNewGame() { mNumBalls = NEW_GAME_NUM_BALLS; mNumLives = mNumLivesStart; updatePercentDisplay(0); updateLivesDisplay(mNumLives); updateLevelDisplay(mNumBalls); mBallsView.getEngine().reset(SystemClock.elapsedRealtime(), mNumBalls); mBallsView.setMode(DivideAndConquerView.Mode.Bouncing); } /** * Update the header displaying the current level */ private void updateLevelDisplay(int numBalls) { mLevelInfo.setText(getString(R.string.level, numBalls)); } /** * Update the display showing the number of lives left. * @param numLives The number of lives left. */ void updateLivesDisplay(int numLives) { String text = (numLives == 1) ? getString(R.string.one_life_left) : getString(R.string.lives_left, numLives); mLivesLeft.setText(text); } /** {@inheritDoc} */ public void onCancel(DialogInterface dialog) { if (dialog == mWelcomeDialog || dialog == mGameOverDialog) { // user hit back, they're done 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.divideandconquer; import android.util.Log; import android.content.Context; import android.widget.Toast; import java.util.List; import java.util.ArrayList; import java.util.Iterator; /** * Keeps track of the current state of balls bouncing around within a a set of * regions. * * Note: 'now' is the elapsed time in milliseconds since some consistent point in time. * As long as the reference point stays consistent, the engine will be happy, though * typically this is {@link android.os.SystemClock#elapsedRealtime()} */ public class BallEngine { static public interface BallEventCallBack { void onBallHitsBall(Ball ballA, Ball ballB); void onBallHitsLine(long when, Ball ball, AnimatingLine animatingLine); } private final float mMinX; private final float mMaxX; private final float mMinY; private final float mMaxY; private float mBallSpeed; private float mBallRadius; private BallEventCallBack mCallBack; /** * Holds onto new regions during a split */ private List<BallRegion> mNewRegions = new ArrayList<BallRegion>(8); private List<BallRegion> mRegions = new ArrayList<BallRegion>(8); public BallEngine(float minX, float maxX, float minY, float maxY, float ballSpeed, float ballRadius) { mMinX = minX; mMaxX = maxX; mMinY = minY; mMaxY = maxY; mBallSpeed = ballSpeed; mBallRadius = ballRadius; } public void setCallBack(BallEventCallBack mCallBack) { this.mCallBack = mCallBack; } /** * Update the notion of 'now' in milliseconds. This can be usefull * when unpausing for instance. * @param now Milliseconds since some consistent point in time. */ public void setNow(long now) { for (int i = 0; i < mRegions.size(); i++) { final BallRegion region = mRegions.get(i); region.setNow(now); } } /** * Rest the engine back to a single region with a certain number of balls * that will be placed randomly and sent in random directions. * @param now milliseconds since some consistent point in time. * @param numBalls */ public void reset(long now, int numBalls) { mRegions.clear(); ArrayList<Ball> balls = new ArrayList<Ball>(numBalls); for (int i = 0; i < numBalls; i++) { Ball ball = new Ball.Builder() .setNow(now) .setPixelsPerSecond(mBallSpeed) .setAngle(Math.random() * 2 * Math.PI) .setX((float) Math.random() * (mMaxX - mMinX) + mMinX) .setY((float) Math.random() * (mMaxY - mMinY) + mMinY) .setRadiusPixels(mBallRadius) .create(); balls.add(ball); } BallRegion region = new BallRegion(now, mMinX, mMaxX, mMinY, mMaxY, balls); region.setCallBack(mCallBack); mRegions.add(region); } public List<BallRegion> getRegions() { return mRegions; } public float getPercentageFilled() { float total = 0f; for (int i = 0; i < mRegions.size(); i++) { BallRegion region = mRegions.get(i); total += region.getArea(); Log.d("Balls", "total now " + total); } return 1f - (total / getArea()); } /** * @return the area in the region in pixel*pixel */ public float getArea() { return (mMaxX - mMinX) * (mMaxY - mMinY); } /** * Can any of the regions within start a line at this point? * @param x The x coordinate. * @param y The y coordinate * @return Whether a region can start a line. */ public boolean canStartLineAt(float x, float y) { for (BallRegion region : mRegions) { if (region.canStartLineAt(x, y)) { return true; } } return false; } /** * Start a horizontal line at a certain point. * @throws IllegalArgumentException if there is no region that can start a * line at the point. */ public void startHorizontalLine(long now, float x, float y) { for (BallRegion region : mRegions) { if (region.canStartLineAt(x, y)) { region.startHorizontalLine(now, x, y); return; } } throw new IllegalArgumentException("no region can start a new line at " + x + ", " + y + "."); } /** * Start a vertical line at a certain point. * @throws IllegalArgumentException if there is no region that can start a * line at the point. */ public void startVerticalLine(long now, float x, float y) { for (BallRegion region : mRegions) { if (region.canStartLineAt(x, y)) { region.startVerticalLine(now, x, y); return; } } throw new IllegalArgumentException("no region can start a new line at " + x + ", " + y + "."); } /** * @param now The latest notion of 'now' * @return whether any new regions were added by the update. */ public boolean update(long now) { boolean regionChange = false; Iterator<BallRegion> it = mRegions.iterator(); while (it.hasNext()) { final BallRegion region = it.next(); final BallRegion newRegion = region.update(now); if (newRegion != null) { regionChange = true; if (!newRegion.getBalls().isEmpty()) { mNewRegions.add(newRegion); } // current region may not have any balls left if (region.getBalls().isEmpty()) { it.remove(); } } else if (region.consumeDoneShrinking()) { regionChange = true; } } mRegions.addAll(mNewRegions); mNewRegions.clear(); return regionChange; } }
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.divideandconquer; /** * A 2d shape has left, right, top and bottom dimensions. * */ public abstract class Shape2d { public abstract float getLeft(); public abstract float getRight(); public abstract float getTop(); public abstract float getBottom(); /** * @param other Another 2d shape * @return Whether this shape is intersecting with the other. */ public boolean isIntersecting(Shape2d other) { return getLeft() <= other.getRight() && getRight() >= other.getLeft() && getTop() <= other.getBottom() && getBottom() >= other.getTop(); } /** * @param x An x coordinate * @param y A y coordinate * @return Whether the point is within this shape */ public boolean isPointWithin(float x, float y) { return (x > getLeft() && x < getRight() && y > getTop() && y < getBottom()); } public float getArea() { return getHeight() * getWidth(); } public float getHeight() { return getBottom() - getTop(); } public float getWidth () { return getRight() - getLeft(); } }
Java
package com.example.android.rings_extended; import android.app.ListActivity; import android.content.AsyncQueryHandler; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.database.CharArrayBuffer; import android.database.Cursor; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.os.Parcelable; import android.provider.MediaStore; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.ListView; import android.widget.RadioButton; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import java.io.IOException; import java.text.Collator; import java.util.Formatter; import java.util.Locale; /** * Activity allowing the user to select a music track on the device, and * return it to its caller. The music picker user interface is fairly * extensive, providing information about each track like the music * application (title, author, album, duration), as well as the ability to * previous tracks and sort them in different orders. * * <p>This class also illustrates how you can load data from a content * provider asynchronously, providing a good UI while doing so, perform * indexing of the content for use inside of a {@link FastScrollView}, and * perform filtering of the data as the user presses keys. */ public class MusicPicker extends ListActivity implements View.OnClickListener, MediaPlayer.OnCompletionListener { static final boolean DBG = false; static final String TAG = "MusicPicker"; /** Holds the previous state of the list, to restore after the async * query has completed. */ static final String LIST_STATE_KEY = "liststate"; /** Remember whether the list last had focus for restoring its state. */ static final String FOCUS_KEY = "focused"; /** Remember the last ordering mode for restoring state. */ static final String SORT_MODE_KEY = "sortMode"; /** Arbitrary number, doesn't matter since we only do one query type. */ final int MY_QUERY_TOKEN = 42; /** Menu item to sort the music list by track title. */ static final int TRACK_MENU = Menu.FIRST; /** Menu item to sort the music list by album title. */ static final int ALBUM_MENU = Menu.FIRST+1; /** Menu item to sort the music list by artist name. */ static final int ARTIST_MENU = Menu.FIRST+2; /** These are the columns in the music cursor that we are interested in. */ static final String[] CURSOR_COLS = new String[] { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.TITLE_KEY, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ARTIST_ID, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.TRACK }; /** Formatting optimization to avoid creating many temporary objects. */ static StringBuilder sFormatBuilder = new StringBuilder(); /** Formatting optimization to avoid creating many temporary objects. */ static Formatter sFormatter = new Formatter(sFormatBuilder, Locale.getDefault()); /** Formatting optimization to avoid creating many temporary objects. */ static final Object[] sTimeArgs = new Object[5]; /** Uri to the directory of all music being displayed. */ Uri mBaseUri; /** This is the adapter used to display all of the tracks. */ TrackListAdapter mAdapter; /** Our instance of QueryHandler used to perform async background queries. */ QueryHandler mQueryHandler; /** Used to keep track of the last scroll state of the list. */ Parcelable mListState = null; /** Used to keep track of whether the list last had focus. */ boolean mListHasFocus; /** The current cursor on the music that is being displayed. */ Cursor mCursor; /** The actual sort order the user has selected. */ int mSortMode = -1; /** SQL order by string describing the currently selected sort order. */ String mSortOrder; /** Container of the in-screen progress indicator, to be able to hide it * when done loading the initial cursor. */ View mProgressContainer; /** Container of the list view hierarchy, to be able to show it when done * loading the initial cursor. */ View mListContainer; /** Set to true when the list view has been shown for the first time. */ boolean mListShown; /** View holding the okay button. */ View mOkayButton; /** View holding the cancel button. */ View mCancelButton; /** Which track row ID the user has last selected. */ long mSelectedId = -1; /** Completel Uri that the user has last selected. */ Uri mSelectedUri; /** If >= 0, we are currently playing a track for preview, and this is its * row ID. */ long mPlayingId = -1; /** This is used for playing previews of the music files. */ MediaPlayer mMediaPlayer; /** * A special implementation of SimpleCursorAdapter that knows how to bind * our cursor data to our list item structure, and takes care of other * advanced features such as indexing and filtering. */ class TrackListAdapter extends SimpleCursorAdapter implements FastScrollView.SectionIndexer { final ListView mListView; private final StringBuilder mBuilder = new StringBuilder(); private final String mUnknownArtist; private final String mUnknownAlbum; private int mIdIdx; private int mTitleIdx; private int mArtistIdx; private int mAlbumIdx; private int mDurationIdx; private int mAudioIdIdx; private int mTrackIdx; private boolean mLoading = true; private String [] mAlphabet; private int mIndexerSortMode; private boolean mIndexerOutOfDate; private AlphabetIndexer mIndexer; class ViewHolder { TextView line1; TextView line2; TextView duration; RadioButton radio; ImageView play_indicator; CharArrayBuffer buffer1; char [] buffer2; } TrackListAdapter(Context context, ListView listView, int layout, String[] from, int[] to) { super(context, layout, null, from, to); mListView = listView; mUnknownArtist = context.getString(R.string.unknownArtistName); mUnknownAlbum = context.getString(R.string.unknownAlbumName); getAlphabet(context); } /** * The mLoading flag is set while we are performing a background * query, to avoid displaying the "No music" empty view during * this time. */ public void setLoading(boolean loading) { mLoading = loading; } @Override public boolean isEmpty() { if (mLoading) { // We don't want the empty state to show when loading. return false; } else { return super.isEmpty(); } } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View v = super.newView(context, cursor, parent); ViewHolder vh = new ViewHolder(); vh.line1 = (TextView) v.findViewById(R.id.line1); vh.line2 = (TextView) v.findViewById(R.id.line2); vh.duration = (TextView) v.findViewById(R.id.duration); vh.radio = (RadioButton) v.findViewById(R.id.radio); vh.play_indicator = (ImageView) v.findViewById(R.id.play_indicator); vh.buffer1 = new CharArrayBuffer(100); vh.buffer2 = new char[200]; v.setTag(vh); return v; } @Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder vh = (ViewHolder) view.getTag(); cursor.copyStringToBuffer(mTitleIdx, vh.buffer1); vh.line1.setText(vh.buffer1.data, 0, vh.buffer1.sizeCopied); int secs = cursor.getInt(mDurationIdx) / 1000; if (secs == 0) { vh.duration.setText(""); } else { vh.duration.setText(makeTimeString(context, secs)); } final StringBuilder builder = mBuilder; builder.delete(0, builder.length()); String name = cursor.getString(mAlbumIdx); if (name == null || name.equals(MediaStore.UNKNOWN_STRING)) { builder.append(mUnknownAlbum); } else { builder.append(name); } builder.append('\n'); name = cursor.getString(mArtistIdx); if (name == null || name.equals(MediaStore.UNKNOWN_STRING)) { builder.append(mUnknownArtist); } else { builder.append(name); } int len = builder.length(); if (vh.buffer2.length < len) { vh.buffer2 = new char[len]; } builder.getChars(0, len, vh.buffer2, 0); vh.line2.setText(vh.buffer2, 0, len); // Update the checkbox of the item, based on which the user last // selected. Note that doing it this way means we must have the // list view update all of its items when the selected item // changes. final long id = cursor.getLong(mIdIdx); vh.radio.setChecked(id == mSelectedId); if (DBG) Log.v(TAG, "Binding id=" + id + " sel=" + mSelectedId + " playing=" + mPlayingId + " cursor=" + cursor); // Likewise, display the "now playing" icon if this item is // currently being previewed for the user. ImageView iv = vh.play_indicator; if (id == mPlayingId) { iv.setImageResource(R.drawable.now_playing); iv.setVisibility(View.VISIBLE); } else { iv.setVisibility(View.GONE); } } /** * This method is called whenever we receive a new cursor due to * an async query, and must take care of plugging the new one in * to the adapter. */ @Override public void changeCursor(Cursor cursor) { super.changeCursor(cursor); if (DBG) Log.v(TAG, "Setting cursor to: " + cursor + " from: " + MusicPicker.this.mCursor); MusicPicker.this.mCursor = cursor; if (cursor != null) { // Retrieve indices of the various columns we are interested in. mIdIdx = cursor.getColumnIndex(MediaStore.Audio.Media._ID); mTitleIdx = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE); mArtistIdx = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST); mAlbumIdx = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM); mDurationIdx = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION); int audioIdIdx = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID); if (audioIdIdx < 0) { audioIdIdx = cursor.getColumnIndex(MediaStore.Audio.Media._ID); } mAudioIdIdx = audioIdIdx; mTrackIdx = cursor.getColumnIndex(MediaStore.Audio.Media.TRACK); } // The next time the indexer is needed, we will need to rebind it // to this cursor. mIndexerOutOfDate = true; // Ensure that the list is shown (and initial progress indicator // hidden) in case this is the first cursor we have gotten. makeListShown(); } /** * This method is called from a background thread by the list view * when the user has typed a letter that should result in a filtering * of the displayed items. It returns a Cursor, when will then be * handed to changeCursor. */ @Override public Cursor runQueryOnBackgroundThread(CharSequence constraint) { if (DBG) Log.v(TAG, "Getting new cursor..."); return doQuery(true, constraint.toString()); } /** * Build a list of alphabetic characters appropriate for the * current locale. */ private void getAlphabet(Context context) { String alphabetString = context.getResources().getString(R.string.alphabet); mAlphabet = new String[alphabetString.length()]; for (int i = 0; i < mAlphabet.length; i++) { mAlphabet[i] = String.valueOf(alphabetString.charAt(i)); } } public int getPositionForSection(int section) { Cursor cursor = getCursor(); if (cursor == null) { // No cursor, the section doesn't exist so just return 0 return 0; } // If the sort mode has changed, or we haven't yet created an // indexer one, then create a new one that is indexing the // appropriate column based on the sort mode. if (mIndexerSortMode != mSortMode || mIndexer == null) { mIndexerSortMode = mSortMode; int idx = mTitleIdx; switch (mIndexerSortMode) { case ARTIST_MENU: idx = mArtistIdx; break; case ALBUM_MENU: idx = mAlbumIdx; break; } mIndexer = new AlphabetIndexer(cursor, idx, mAlphabet); // If we have a valid indexer, but the cursor has changed since // its last use, then point it to the current cursor. } else if (mIndexerOutOfDate) { mIndexer.setCursor(cursor); } mIndexerOutOfDate = false; return mIndexer.indexOf(section); } public int getSectionForPosition(int position) { return 0; } public Object[] getSections() { return mAlphabet; } } /** * This is our specialization of AsyncQueryHandler applies new cursors * to our state as they become available. */ private final class QueryHandler extends AsyncQueryHandler { public QueryHandler(Context context) { super(context.getContentResolver()); } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { if (!isFinishing()) { // Update the adapter: we are no longer loading, and have // a new cursor for it. mAdapter.setLoading(false); mAdapter.changeCursor(cursor); setProgressBarIndeterminateVisibility(false); // Now that the cursor is populated again, it's possible to restore the list state if (mListState != null) { getListView().onRestoreInstanceState(mListState); if (mListHasFocus) { getListView().requestFocus(); } mListHasFocus = false; mListState = null; } } else { cursor.close(); } } } public static String makeTimeString(Context context, long secs) { String durationformat = context.getString(R.string.durationformat); /* Provide multiple arguments so the format can be changed easily * by modifying the xml. */ sFormatBuilder.setLength(0); final Object[] timeArgs = sTimeArgs; timeArgs[0] = secs / 3600; timeArgs[1] = secs / 60; timeArgs[2] = (secs / 60) % 60; timeArgs[3] = secs; timeArgs[4] = secs % 60; return sFormatter.format(durationformat, timeArgs).toString(); } /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setTitle(R.string.musicPickerTitle); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); int sortMode = TRACK_MENU; if (icicle == null) { mSelectedUri = getIntent().getParcelableExtra( RingtoneManager.EXTRA_RINGTONE_EXISTING_URI); } else { mSelectedUri = (Uri)icicle.getParcelable( RingtoneManager.EXTRA_RINGTONE_EXISTING_URI); // Retrieve list state. This will be applied after the // QueryHandler has run mListState = icicle.getParcelable(LIST_STATE_KEY); mListHasFocus = icicle.getBoolean(FOCUS_KEY); sortMode = icicle.getInt(SORT_MODE_KEY, sortMode); } if (Intent.ACTION_GET_CONTENT.equals(getIntent().getAction())) { mBaseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } else { mBaseUri = getIntent().getData(); if (mBaseUri == null) { Log.w("MusicPicker", "No data URI given to PICK action"); finish(); return; } } setContentView(R.layout.music_picker); mSortOrder = MediaStore.Audio.Media.TITLE_KEY; final ListView listView = getListView(); listView.setItemsCanFocus(false); mAdapter = new TrackListAdapter(this, listView, R.layout.track_list_item, new String[] {}, new int[] {}); setListAdapter(mAdapter); listView.setTextFilterEnabled(true); // We manually save/restore the listview state listView.setSaveEnabled(false); mQueryHandler = new QueryHandler(this); mProgressContainer = findViewById(R.id.progressContainer); mListContainer = findViewById(R.id.listContainer); mOkayButton = findViewById(R.id.okayButton); mOkayButton.setOnClickListener(this); mCancelButton = findViewById(R.id.cancelButton); mCancelButton.setOnClickListener(this); // If there is a currently selected Uri, then try to determine who // it is. if (mSelectedUri != null) { Uri.Builder builder = mSelectedUri.buildUpon(); String path = mSelectedUri.getEncodedPath(); int idx = path.lastIndexOf('/'); if (idx >= 0) { path = path.substring(0, idx); } builder.encodedPath(path); Uri baseSelectedUri = builder.build(); if (DBG) Log.v(TAG, "Selected Uri: " + mSelectedUri); if (DBG) Log.v(TAG, "Selected base Uri: " + baseSelectedUri); if (DBG) Log.v(TAG, "Base Uri: " + mBaseUri); if (baseSelectedUri.equals(mBaseUri)) { // If the base Uri of the selected Uri is the same as our // content's base Uri, then use the selection! mSelectedId = ContentUris.parseId(mSelectedUri); } } setSortMode(sortMode); } @Override public void onRestart() { super.onRestart(); doQuery(false, null); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (setSortMode(item.getItemId())) { return true; } return super.onOptionsItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(Menu.NONE, TRACK_MENU, Menu.NONE, R.string.sortByTrack); menu.add(Menu.NONE, ALBUM_MENU, Menu.NONE, R.string.sortByAlbum); menu.add(Menu.NONE, ARTIST_MENU, Menu.NONE, R.string.sortByArtist); return true; } @Override protected void onSaveInstanceState(Bundle icicle) { super.onSaveInstanceState(icicle); // Save list state in the bundle so we can restore it after the // QueryHandler has run icicle.putParcelable(LIST_STATE_KEY, getListView().onSaveInstanceState()); icicle.putBoolean(FOCUS_KEY, getListView().hasFocus()); icicle.putInt(SORT_MODE_KEY, mSortMode); } @Override public void onPause() { super.onPause(); stopMediaPlayer(); } @Override public void onStop() { super.onStop(); // We don't want the list to display the empty state, since when we // resume it will still be there and show up while the new query is // happening. After the async query finishes in response to onResume() // setLoading(false) will be called. mAdapter.setLoading(true); mAdapter.changeCursor(null); } /** * Changes the current sort order, building the appropriate query string * for the selected order. */ boolean setSortMode(int sortMode) { if (sortMode != mSortMode) { switch (sortMode) { case TRACK_MENU: mSortMode = sortMode; mSortOrder = MediaStore.Audio.Media.TITLE_KEY; doQuery(false, null); return true; case ALBUM_MENU: mSortMode = sortMode; mSortOrder = MediaStore.Audio.Media.ALBUM_KEY + " ASC, " + MediaStore.Audio.Media.TRACK + " ASC, " + MediaStore.Audio.Media.TITLE_KEY + " ASC"; doQuery(false, null); return true; case ARTIST_MENU: mSortMode = sortMode; mSortOrder = MediaStore.Audio.Media.ARTIST_KEY + " ASC, " + MediaStore.Audio.Media.ALBUM_KEY + " ASC, " + MediaStore.Audio.Media.TRACK + " ASC, " + MediaStore.Audio.Media.TITLE_KEY + " ASC"; doQuery(false, null); return true; } } return false; } /** * The first time this is called, we hide the large progress indicator * and show the list view, doing fade animations between them. */ void makeListShown() { if (!mListShown) { mListShown = true; mProgressContainer.startAnimation(AnimationUtils.loadAnimation( this, android.R.anim.fade_out)); mProgressContainer.setVisibility(View.GONE); mListContainer.startAnimation(AnimationUtils.loadAnimation( this, android.R.anim.fade_in)); mListContainer.setVisibility(View.VISIBLE); } } /** * Common method for performing a query of the music database, called for * both top-level queries and filtering. * * @param sync If true, this query should be done synchronously and the * resulting cursor returned. If false, it will be done asynchronously and * null returned. * @param filterstring If non-null, this is a filter to apply to the query. */ Cursor doQuery(boolean sync, String filterstring) { // Cancel any pending queries mQueryHandler.cancelOperation(MY_QUERY_TOKEN); StringBuilder where = new StringBuilder(); where.append(MediaStore.Audio.Media.TITLE + " != ''"); // Add in the filtering constraints String [] keywords = null; if (filterstring != null) { String [] searchWords = filterstring.split(" "); keywords = new String[searchWords.length]; Collator col = Collator.getInstance(); col.setStrength(Collator.PRIMARY); for (int i = 0; i < searchWords.length; i++) { keywords[i] = '%' + MediaStore.Audio.keyFor(searchWords[i]) + '%'; } for (int i = 0; i < searchWords.length; i++) { where.append(" AND "); where.append(MediaStore.Audio.Media.ARTIST_KEY + "||"); where.append(MediaStore.Audio.Media.ALBUM_KEY + "||"); where.append(MediaStore.Audio.Media.TITLE_KEY + " LIKE ?"); } } // We want to show all audio files, even recordings. Enforcing the // following condition would hide recordings. //where.append(" AND " + MediaStore.Audio.Media.IS_MUSIC + "=1"); if (sync) { try { return getContentResolver().query(mBaseUri, CURSOR_COLS, where.toString(), keywords, mSortOrder); } catch (UnsupportedOperationException ex) { } } else { mAdapter.setLoading(true); setProgressBarIndeterminateVisibility(true); mQueryHandler.startQuery(MY_QUERY_TOKEN, null, mBaseUri, CURSOR_COLS, where.toString(), keywords, mSortOrder); } return null; } @Override protected void onListItemClick(ListView l, View v, int position, long id) { mCursor.moveToPosition(position); if (DBG) Log.v(TAG, "Click on " + position + " (id=" + id + ", cursid=" + mCursor.getLong(mCursor.getColumnIndex(MediaStore.Audio.Media._ID)) + ") in cursor " + mCursor + " adapter=" + l.getAdapter()); setSelected(mCursor); } void setSelected(Cursor c) { Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; long newId = mCursor.getLong(mCursor.getColumnIndex(MediaStore.Audio.Media._ID)); mSelectedUri = ContentUris.withAppendedId(uri, newId); mSelectedId = newId; if (newId != mPlayingId || mMediaPlayer == null) { stopMediaPlayer(); mMediaPlayer = new MediaPlayer(); try { mMediaPlayer.setDataSource(this, mSelectedUri); mMediaPlayer.setOnCompletionListener(this); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING); mMediaPlayer.prepare(); mMediaPlayer.start(); mPlayingId = newId; getListView().invalidateViews(); } catch (IOException e) { Log.w("MusicPicker", "Unable to play track", e); } } else if (mMediaPlayer != null) { stopMediaPlayer(); getListView().invalidateViews(); } } public void onCompletion(MediaPlayer mp) { if (mMediaPlayer == mp) { mp.stop(); mp.release(); mMediaPlayer = null; mPlayingId = -1; getListView().invalidateViews(); } } void stopMediaPlayer() { if (mMediaPlayer != null) { mMediaPlayer.stop(); mMediaPlayer.release(); mMediaPlayer = null; mPlayingId = -1; } } public void onClick(View v) { switch (v.getId()) { case R.id.okayButton: if (mSelectedId >= 0) { setResult(RESULT_OK, new Intent().setData(mSelectedUri)); finish(); } break; case R.id.cancelButton: finish(); break; } } }
Java
package com.example.android.rings_extended; import android.app.ListActivity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.util.Config; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.RadioButton; import android.widget.TextView; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * The RingsExtended application, implementing an advanced ringtone picker. * This is a ListActivity display an adapter of dynamic state built by the * activity: at the top are simple options the user can be picked, next an * item to run the built-in ringtone picker, and next are any other activities * that can supply music Uris. */ public class RingsExtended extends ListActivity implements View.OnClickListener, MediaPlayer.OnCompletionListener { static final boolean DBG = false; static final String TAG = "RingsExtended"; /** * Request code when we are launching an activity to handle our same * original Intent, meaning we can propagate its result back to our caller * as-is. */ static final int REQUEST_ORIGINAL = 2; /** * Request code when launching an activity that returns an audio Uri, * meaning we need to translate its result into one that our caller * expects. */ static final int REQUEST_SOUND = 1; Adapter mAdapter; private View mOkayButton; private View mCancelButton; /** Where the silent option item is in the list, or -1 if there is none. */ private int mSilentItemIdx = -1; /** The Uri to play when the 'Default' item is clicked. */ private Uri mUriForDefaultItem; /** Where the default option item is in the list, or -1 if there is none. */ private int mDefaultItemIdx = -1; /** The Uri to place a checkmark next to. */ private Uri mExistingUri; /** Where the existing option item is in the list. */ private int mExistingItemIdx; /** Currently selected options in the radio buttons, if any. */ private long mSelectedItem = -1; /** Loaded ringtone for the existing URI. */ private Ringtone mExistingRingtone; /** Id of option that is currently playing. */ private long mPlayingId = -1; /** Used for playing previews of ring tones. */ private MediaPlayer mMediaPlayer; /** * Information about one static item in the list. This is used for items * that are added and handled manually, which don't have an Intent * associated with them. */ final static class ItemInfo { final CharSequence name; final CharSequence subtitle; final Drawable icon; ItemInfo(CharSequence _name, CharSequence _subtitle, Drawable _icon) { name = _name; subtitle = _subtitle; icon = _icon; } } /** * Our special adapter implementation, merging the various kinds of items * that we will display into one list. There are two sections to the * list of items: * (1) First are any fixed items as described by ItemInfo objects. * (2) Next are any activities that do the same thing as our own. * (3) Finally are any activities that can execute a different Intent. */ private final class Adapter extends BaseAdapter { private final List<ItemInfo> mInitialItems; private final Intent mIntent; private final Intent mOrigIntent; private final LayoutInflater mInflater; private List<ResolveInfo> mList; private int mRealListStart = 0; class ViewHolder { ImageView icon; RadioButton radio; TextView textSingle; TextView textDouble1; TextView textDouble2; ImageView more; } /** * Create a new adapter with the items to be displayed. * * @param context The Context we are running in. * @param initialItems A fixed set of items that appear at the * top of the list. * @param origIntent The original Intent that was used to launch this * activity, used to find all activities that can do the same thing. * @param excludeOrigIntent Our component name, to exclude from the * origIntent list since that is what the user is already running! * @param intent An Intent used to query for additional items to * appear in the rest of the list. */ public Adapter(Context context, List<ItemInfo> initialItems, Intent origIntent, ComponentName excludeOrigIntent, Intent intent) { mInitialItems = initialItems; mIntent = new Intent(intent); mIntent.setComponent(null); mIntent.setFlags(0); if (origIntent != null) { mOrigIntent = new Intent(origIntent); mOrigIntent.setComponent(null); mOrigIntent.setFlags(0); } else { mOrigIntent = null; } mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mList = getActivities(context, mIntent, null); if (origIntent != null) { List<ResolveInfo> orig = getActivities(context, mOrigIntent, excludeOrigIntent); if (orig != null && orig.size() > 0) { mRealListStart = orig.size(); orig.addAll(mList); mList = orig; } } } /** * If the position is within the range of initial items, return the * corresponding index into that array. Otherwise return -1. */ public int initialItemForPosition(int position) { if (position >= getIntentStartIndex()) { return -1; } return position; } /** * Returns true if the given position is for one of the * "original intent" items. */ public boolean isOrigIntentPosition(int position) { position -= getIntentStartIndex(); return position >= 0 && position < mRealListStart; } /** * Returns the ResolveInfo corresponding to the given position, or null * if that position is not an Intent item (that is if it is one * of the static list items). */ public ResolveInfo resolveInfoForPosition(int position) { position -= getIntentStartIndex(); if (mList == null || position < 0) { return null; } return mList.get(position); } /** * Returns the Intent corresponding to the given position, or null * if that position is not an Intent item (that is if it is one * of the static list items). */ public Intent intentForPosition(int position) { position -= getIntentStartIndex(); if (mList == null || position < 0) { return null; } Intent intent = new Intent( position >= mRealListStart ? mIntent : mOrigIntent); ActivityInfo ai = mList.get(position).activityInfo; intent.setComponent(new ComponentName( ai.applicationInfo.packageName, ai.name)); return intent; } public int getCount() { return getIntentStartIndex() + (mList != null ? mList.size() : 0); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { View view; if (convertView == null) { view = mInflater.inflate(R.layout.list_item, parent, false); ViewHolder vh = new ViewHolder(); vh.icon = (ImageView)view.findViewById(R.id.icon); vh.radio = (RadioButton)view.findViewById(R.id.radio); vh.textSingle = (TextView)view.findViewById(R.id.textSingle); vh.textDouble1 = (TextView)view.findViewById(R.id.textDouble1); vh.textDouble2 = (TextView)view.findViewById(R.id.textDouble2); vh.more = (ImageView)view.findViewById(R.id.more); view.setTag(vh); } else { view = convertView; } int intentStart = getIntentStartIndex(); if (position < intentStart) { bindView(view, position, mInitialItems.get(position)); } else { bindView(view, mList.get(position-intentStart)); } return view; } private final int getIntentStartIndex() { return mInitialItems != null ? mInitialItems.size() : 0; } private final void bindView(View view, ResolveInfo info) { PackageManager pm = getPackageManager(); ViewHolder vh = (ViewHolder)view.getTag(); CharSequence label = info.loadLabel(pm); if (label == null) label = info.activityInfo.name; bindTextViews(vh, label, null); vh.icon.setImageDrawable(info.loadIcon(pm)); vh.icon.setVisibility(View.VISIBLE); vh.radio.setVisibility(View.GONE); vh.more.setImageResource(R.drawable.icon_more); vh.more.setVisibility(View.VISIBLE); } private final void bindTextViews(ViewHolder vh, CharSequence txt1, CharSequence txt2) { if (txt2 == null) { vh.textSingle.setText(txt1); vh.textSingle.setVisibility(View.VISIBLE); vh.textDouble1.setVisibility(View.INVISIBLE); vh.textDouble2.setVisibility(View.INVISIBLE); } else { vh.textDouble1.setText(txt1); vh.textDouble1.setVisibility(View.VISIBLE); vh.textDouble2.setText(txt2); vh.textDouble2.setVisibility(View.VISIBLE); vh.textSingle.setVisibility(View.INVISIBLE); } } private final void bindView(View view, int position, ItemInfo inf) { ViewHolder vh = (ViewHolder)view.getTag(); bindTextViews(vh, inf.name, inf.subtitle); // Set the standard icon and radio button. When the radio button // is displayed, we mark it if this is the currently selected row, // meaning we need to invalidate the view list whenever the // selection changes. if (inf.icon != null) { vh.icon.setImageDrawable(inf.icon); vh.icon.setVisibility(View.VISIBLE); vh.radio.setVisibility(View.GONE); } else { vh.icon.setVisibility(View.GONE); vh.radio.setVisibility(View.VISIBLE); vh.radio.setChecked(position == mSelectedItem); } // Show the "now playing" icon if this item is playing. Doing this // means that we need to invalidate the displayed views when the // playing state changes. if (mPlayingId == position) { vh.more.setImageResource(R.drawable.now_playing); vh.more.setVisibility(View.VISIBLE); } else { vh.more.setVisibility(View.GONE); } } } /** * Retrieve a list of all of the activities that can handle the given Intent, * optionally excluding the explicit component 'exclude'. The returned list * is sorted by the label for reach resolved activity. */ static final List<ResolveInfo> getActivities(Context context, Intent intent, ComponentName exclude) { PackageManager pm = context.getPackageManager(); List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); if (list != null) { int N = list.size(); if (exclude != null) { for (int i=0; i<N; i++) { ResolveInfo ri = list.get(i); if (ri.activityInfo.packageName.equals(exclude.getPackageName()) || ri.activityInfo.name.equals(exclude.getClassName())) { list.remove(i); N--; } } } if (N > 1) { // Only display the first matches that are either of equal // priority or have asked to be default options. ResolveInfo r0 = list.get(0); for (int i=1; i<N; i++) { ResolveInfo ri = list.get(i); if (Config.LOGV) Log.v( "ResolveListActivity", r0.activityInfo.name + "=" + r0.priority + "/" + r0.isDefault + " vs " + ri.activityInfo.name + "=" + ri.priority + "/" + ri.isDefault); if (r0.priority != ri.priority || r0.isDefault != ri.isDefault) { while (i < N) { list.remove(i); N--; } } } Collections.sort(list, new ResolveInfo.DisplayNameComparator(pm)); } } return list; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.rings_extended); mOkayButton = findViewById(R.id.okayButton); mOkayButton.setOnClickListener(this); mCancelButton = findViewById(R.id.cancelButton); mCancelButton.setOnClickListener(this); Intent intent = getIntent(); /* * Get whether to show the 'Default' item, and the URI to play when the * default is clicked */ mUriForDefaultItem = intent.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI); if (mUriForDefaultItem == null) { mUriForDefaultItem = Settings.System.DEFAULT_RINGTONE_URI; } // Get the URI whose list item should have a checkmark mExistingUri = intent .getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI); // We are now going to build the set of static items. ArrayList<ItemInfo> initialItems = new ArrayList<ItemInfo>(); // If the caller has asked to allow the user to select "silent", then // show an option for that. if (intent.getBooleanExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, true)) { mSilentItemIdx = initialItems.size(); initialItems.add(new ItemInfo(getText(R.string.silentLabel), null, null)); } // If the caller has asked to allow the user to select "default", then // show an option for that. if (intent.getBooleanExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true)) { mDefaultItemIdx = initialItems.size(); Ringtone defRing = RingtoneManager.getRingtone(this, mUriForDefaultItem); initialItems.add(new ItemInfo(getText(R.string.defaultRingtoneLabel), defRing.getTitle(this), null)); } // If the caller has supplied a currently selected Uri, then show an // open for keeping that. if (mExistingUri != null) { mExistingRingtone = RingtoneManager.getRingtone(this, mExistingUri); mExistingItemIdx = initialItems.size(); initialItems.add(new ItemInfo(getText(R.string.existingRingtoneLabel), mExistingRingtone.getTitle(this), null)); } if (DBG) { Log.v(TAG, "default=" + mUriForDefaultItem); Log.v(TAG, "existing=" + mExistingUri); } // Figure out which of the static items should start out with its // radio button checked. if (mExistingUri == null) { if (mSilentItemIdx >= 0) { mSelectedItem = mSilentItemIdx; } } else if (mDefaultItemIdx >= 0 && mExistingUri.equals(mUriForDefaultItem)) { mSelectedItem = mDefaultItemIdx; } else { mSelectedItem = mExistingItemIdx; } if (mSelectedItem >= 0) { mOkayButton.setEnabled(true); } mAdapter = new Adapter(this, initialItems, getIntent(), getComponentName(), new Intent(Intent.ACTION_GET_CONTENT).setType("audio/mp3") .addCategory(Intent.CATEGORY_OPENABLE)); this.setListAdapter(mAdapter); } @Override public void onPause() { super.onPause(); stopMediaPlayer(); } public void onCompletion(MediaPlayer mp) { if (mMediaPlayer == mp) { mp.stop(); mp.release(); mMediaPlayer = null; mPlayingId = -1; getListView().invalidateViews(); } } private void stopMediaPlayer() { if (mMediaPlayer != null) { mMediaPlayer.stop(); mMediaPlayer.release(); mMediaPlayer = null; mPlayingId = -1; } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { int initialItem = mAdapter.initialItemForPosition((int)id); if (initialItem >= 0) { // If the selected item is from our static list, then take // care of handling it. mSelectedItem = initialItem; Uri uri = getSelectedUri(); // If a new item has been selected, then play it for the user. if (uri != null && (id != mPlayingId || mMediaPlayer == null)) { stopMediaPlayer(); mMediaPlayer = new MediaPlayer(); try { if (DBG) Log.v(TAG, "Playing: " + uri); mMediaPlayer.setDataSource(this, uri); mMediaPlayer.setOnCompletionListener(this); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING); mMediaPlayer.prepare(); mMediaPlayer.start(); mPlayingId = id; getListView().invalidateViews(); } catch (IOException e) { Log.w("MusicPicker", "Unable to play track", e); } // Otherwise stop any currently playing item. } else if (mMediaPlayer != null) { stopMediaPlayer(); getListView().invalidateViews(); } getListView().invalidateViews(); mOkayButton.setEnabled(true); } else if (mAdapter.isOrigIntentPosition((int)id)) { // If the item is one of the original intent activities, then // launch it with the result code to simply propagate its result // back to our caller. Intent intent = mAdapter.intentForPosition((int)id); startActivityForResult(intent, REQUEST_ORIGINAL); } else { // If the item is one of the music retrieval activities, then launch // it with the result code to transform its result into our caller's // expected result. Intent intent = mAdapter.intentForPosition((int)id); intent.putExtras(getIntent()); startActivityForResult(intent, REQUEST_SOUND); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_SOUND && resultCode == RESULT_OK) { Intent resultIntent = new Intent(); Uri uri = data != null ? data.getData() : null; resultIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI, uri); setResult(RESULT_OK, resultIntent); finish(); } else if (requestCode == REQUEST_ORIGINAL && resultCode == RESULT_OK) { setResult(RESULT_OK, data); finish(); } } public void onClick(View v) { switch (v.getId()) { case R.id.okayButton: Intent resultIntent = new Intent(); Uri uri = getSelectedUri(); resultIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI, uri); setResult(RESULT_OK, resultIntent); finish(); break; case R.id.cancelButton: finish(); break; } } private Uri getSelectedUri() { if (mSelectedItem == mSilentItemIdx) { // The null uri is silent. return null; } else if (mSelectedItem == mDefaultItemIdx) { return mUriForDefaultItem; } else if (mSelectedItem == mExistingItemIdx) { return mExistingUri; } 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.android.rings_extended; import android.database.Cursor; import android.database.DataSetObserver; import android.util.SparseIntArray; /** * This class essentially helps in building an index of section boundaries of a * sorted column of a cursor. For instance, if a cursor contains a data set * sorted by first name of a person or the title of a song, this class will * perform a binary search to identify the first row that begins with a * particular letter. The search is case-insensitive. The class caches the index * such that subsequent queries for the same letter will return right away. * * <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 AlphabetIndexer extends DataSetObserver { protected Cursor mDataCursor; protected int mColumnIndex; protected Object[] mAlphabetArray; private SparseIntArray mAlphaMap; private java.text.Collator mCollator; /** * Constructs the indexer. * @param cursor the cursor containing the data set * @param columnIndex the column number in the cursor that is sorted * alphabetically * @param sections the array of objects that represent the sections. The * toString() method of each item is called and the first letter of the * String is used as the letter to search for. */ public AlphabetIndexer(Cursor cursor, int columnIndex, Object[] sections) { mDataCursor = cursor; mColumnIndex = columnIndex; mAlphabetArray = sections; mAlphaMap = new SparseIntArray(26 /* Optimize for English */); if (cursor != null) { cursor.registerDataSetObserver(this); } // Get a Collator for the current locale for string comparisons. mCollator = java.text.Collator.getInstance(); mCollator.setStrength(java.text.Collator.PRIMARY); } /** * Sets a new cursor as the data set and resets the cache of indices. * @param cursor the new cursor to use as the data set */ public void setCursor(Cursor cursor) { if (mDataCursor != null) { mDataCursor.unregisterDataSetObserver(this); } mDataCursor = cursor; if (cursor != null) { mDataCursor.registerDataSetObserver(this); } mAlphaMap.clear(); } /** * Performs a binary search or cache lookup to find the first row that * matches a given section's starting letter. * @param sectionIndex the section to search for * @return the row index of the first occurrence, or the nearest next letter. * For instance, if searching for "T" and no "T" is found, then the first * row starting with "U" or any higher letter is returned. If there is no * data following "T" at all, then the list size is returned. */ public int indexOf(int sectionIndex) { final SparseIntArray alphaMap = mAlphaMap; final Cursor cursor = mDataCursor; if (cursor == null || mAlphabetArray == null) { return 0; } // Check bounds if (sectionIndex <= 0) { return 0; } if (sectionIndex >= mAlphabetArray.length) { sectionIndex = mAlphabetArray.length - 1; } int savedCursorPos = cursor.getPosition(); int count = cursor.getCount(); int start = 0; int end = count; int pos; String letter = mAlphabetArray[sectionIndex].toString(); letter = letter.toUpperCase(); int key = letter.charAt(0); // Check map if (Integer.MIN_VALUE != (pos = alphaMap.get(key, Integer.MIN_VALUE))) { // Is it approximate? Using negative value to indicate that it's // an approximation and positive value when it is the accurate // position. if (pos < 0) { pos = -pos; end = pos; } else { // Not approximate, this is the confirmed start of section, return it return pos; } } // Do we have the position of the previous section? if (sectionIndex > 0) { int prevLetter = mAlphabetArray[sectionIndex - 1].toString().charAt(0); int prevLetterPos = alphaMap.get(prevLetter, Integer.MIN_VALUE); if (prevLetterPos != Integer.MIN_VALUE) { start = Math.abs(prevLetterPos); } } // Now that we have a possibly optimized start and end, let's binary search pos = (end + start) / 2; while (pos < end) { // Get letter at pos cursor.moveToPosition(pos); String curName = cursor.getString(mColumnIndex); if (curName == null) { if (pos == 0) { break; } else { pos--; continue; } } int curLetter = Character.toUpperCase(curName.charAt(0)); if (curLetter != key) { // Enter approximation in hash if a better solution doesn't exist int curPos = alphaMap.get(curLetter, Integer.MIN_VALUE); if (curPos == Integer.MIN_VALUE || Math.abs(curPos) > pos) { // Negative pos indicates that it is an approximation alphaMap.put(curLetter, -pos); } if (mCollator.compare(curName, letter) < 0) { start = pos + 1; if (start >= count) { pos = count; break; } } else { end = pos; } } else { // They're the same, but that doesn't mean it's the start if (start == pos) { // This is it break; } else { // Need to go further lower to find the starting row end = pos; } } pos = (start + end) / 2; } alphaMap.put(key, pos); cursor.moveToPosition(savedCursorPos); return pos; } @Override public void onChanged() { super.onChanged(); mAlphaMap.clear(); } @Override public void onInvalidated() { super.onInvalidated(); mAlphaMap.clear(); } }
Java
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 2008 Google Inc. All Rights Reserved. package com.beust.android.translate; import com.beust.android.translate.ITranslate; import com.beust.android.translate.Translate; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; /** * Performs language translation. * * @author Daniel Rall */ public class TranslateService extends Service { public static final String TAG = "TranslateService"; private static final String[] TRANSLATE_ACTIONS = { Intent.ACTION_GET_CONTENT, Intent.ACTION_PICK, Intent.ACTION_VIEW }; private final ITranslate.Stub mBinder = new ITranslate.Stub() { /** * Translates text from a given language to another given language * using Google Translate. * * @param text The text to translate. * @param from The language code to translate from. * @param to The language code to translate to. * @return The translated text, or <code>null</code> on error. */ public String translate(String text, String from, String to) { try { return Translate.translate(text, from, to); } catch (Exception e) { Log.e(TAG, "Failed to perform translation: " + e.getMessage()); return null; } } /** * @return The service version number. */ public int getVersion() { return 1; } }; @Override public IBinder onBind(Intent intent) { for (int i = 0; i < TRANSLATE_ACTIONS.length; i++) { if (TRANSLATE_ACTIONS[i].equals(intent.getAction())) { return mBinder; } } 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.beust.android.translate; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import org.json.JSONObject; /** * Makes the Google Translate API available to Java applications. * * @author Richard Midwinter * @author Emeric Vernat * @author Juan B Cabral * @author Cedric Beust */ public class Translate { private static final String ENCODING = "UTF-8"; private static final String URL_STRING = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&langpair="; private static final String TEXT_VAR = "&q="; /** * Translates text from a given language to another given language using Google Translate * * @param text The String to translate. * @param from The language code to translate from. * @param to The language code to translate to. * @return The translated String. * @throws MalformedURLException * @throws IOException */ public static String translate(String text, String from, String to) throws Exception { return retrieveTranslation(text, from, to); } /** * Forms an HTTP request and parses the response for a translation. * * @param text The String to translate. * @param from The language code to translate from. * @param to The language code to translate to. * @return The translated String. * @throws Exception */ private static String retrieveTranslation(String text, String from, String to) throws Exception { try { StringBuilder url = new StringBuilder(); url.append(URL_STRING).append(from).append("%7C").append(to); url.append(TEXT_VAR).append(URLEncoder.encode(text, ENCODING)); Log.d(TranslateService.TAG, "Connecting to " + url.toString()); HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection(); uc.setDoInput(true); uc.setDoOutput(true); try { Log.d(TranslateService.TAG, "getInputStream()"); InputStream is= uc.getInputStream(); String result = toString(is); JSONObject json = new JSONObject(result); return ((JSONObject)json.get("responseData")).getString("translatedText"); } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html uc.getInputStream().close(); if (uc.getErrorStream() != null) uc.getErrorStream().close(); } } catch (Exception ex) { throw ex; } } /** * Reads an InputStream and returns its contents as a String. Also effects rate control. * @param inputStream The InputStream to read from. * @return The contents of the InputStream as a String. * @throws Exception */ private static String toString(InputStream inputStream) throws Exception { StringBuilder outputBuilder = new StringBuilder(); try { String string; if (inputStream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, ENCODING)); while (null != (string = reader.readLine())) { outputBuilder.append(string).append('\n'); } } } catch (Exception ex) { Log.e(TranslateService.TAG, "Error reading translation stream.", ex); } return outputBuilder.toString(); } }
Java
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.beust.android.translate; import java.util.ArrayList; import java.util.Collections; /** * Provides static methods for creating {@code List} instances easily, and other * utility methods for working with lists. */ public class Lists { /** * Creates an empty {@code ArrayList} instance. * * <p><b>Note:</b> if you only need an <i>immutable</i> empty List, use * {@link Collections#emptyList} instead. * * @return a newly-created, initially-empty {@code ArrayList} */ public static <E> ArrayList<E> newArrayList() { return new ArrayList<E>(); } /** * Creates a resizable {@code ArrayList} instance containing the given * elements. * * <p><b>Note:</b> due to a bug in javac 1.5.0_06, we cannot support the * following: * * <p>{@code List<Base> list = Lists.newArrayList(sub1, sub2);} * * <p>where {@code sub1} and {@code sub2} are references to subtypes of * {@code Base}, not of {@code Base} itself. To get around this, you must * use: * * <p>{@code List<Base> list = Lists.<Base>newArrayList(sub1, sub2);} * * @param elements the elements that the list should contain, in order * @return a newly-created {@code ArrayList} containing those elements */ public static <E> ArrayList<E> newArrayList(E... elements) { int capacity = (elements.length * 110) / 100 + 5; ArrayList<E> list = new ArrayList<E>(capacity); Collections.addAll(list, elements); return list; } }
Java
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.beust.android.translate; import java.util.HashMap; /** * Provides static methods for creating mutable {@code Maps} instances easily. */ public class Maps { /** * Creates a {@code HashMap} instance. * * @return a newly-created, initially-empty {@code HashMap} */ public static <K, V> HashMap<K, V> newHashMap() { return new HashMap<K, V>(); } }
Java
/* * Copyright (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.beust.android.translate; import android.app.Activity; import android.graphics.drawable.Drawable; import android.util.Log; import android.widget.Button; import java.util.Map; /** * Language information for the Google Translate API. */ public final class Languages { /** * Reference at http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 */ static enum Language { // AFRIKAANS("af", "Afrikaans", R.drawable.af), // ALBANIAN("sq", "Albanian"), // AMHARIC("am", "Amharic", R.drawable.am), // ARABIC("ar", "Arabic", R.drawable.ar), // ARMENIAN("hy", "Armenian"), // AZERBAIJANI("az", "Azerbaijani", R.drawable.az), // BASQUE("eu", "Basque"), // BELARUSIAN("be", "Belarusian", R.drawable.be), // BENGALI("bn", "Bengali", R.drawable.bn), // BIHARI("bh", "Bihari", R.drawable.bh), BULGARIAN("bg", "Bulgarian", R.drawable.bg), // BURMESE("my", "Burmese", R.drawable.my), CATALAN("ca", "Catalan"), CHINESE("zh", "Chinese", R.drawable.cn), CHINESE_SIMPLIFIED("zh-CN", "Chinese simplified", R.drawable.cn), CHINESE_TRADITIONAL("zh-TW", "Chinese traditional", R.drawable.tw), CROATIAN("hr", "Croatian", R.drawable.hr), CZECH("cs", "Czech", R.drawable.cs), DANISH("da", "Danish", R.drawable.dk), // DHIVEHI("dv", "Dhivehi"), DUTCH("nl", "Dutch", R.drawable.nl), ENGLISH("en", "English", R.drawable.us), // ESPERANTO("eo", "Esperanto"), // ESTONIAN("et", "Estonian", R.drawable.et), FILIPINO("tl", "Filipino", R.drawable.ph), FINNISH("fi", "Finnish", R.drawable.fi), FRENCH("fr", "French", R.drawable.fr), // GALICIAN("gl", "Galician", R.drawable.gl), // GEORGIAN("ka", "Georgian"), GERMAN("de", "German", R.drawable.de), GREEK("el", "Greek", R.drawable.gr), // GUARANI("gn", "Guarani", R.drawable.gn), // GUJARATI("gu", "Gujarati", R.drawable.gu), // HEBREW("iw", "Hebrew", R.drawable.il), // HINDI("hi", "Hindi"), // HUNGARIAN("hu", "Hungarian", R.drawable.hu), // ICELANDIC("is", "Icelandic", R.drawable.is), INDONESIAN("id", "Indonesian", R.drawable.id), // INUKTITUT("iu", "Inuktitut"), ITALIAN("it", "Italian", R.drawable.it), JAPANESE("ja", "Japanese", R.drawable.jp), // KANNADA("kn", "Kannada", R.drawable.kn), // KAZAKH("kk", "Kazakh"), // KHMER("km", "Khmer", R.drawable.km), KOREAN("ko", "Korean", R.drawable.kr), // KURDISH("ky", "Kurdish", R.drawable.ky), // LAOTHIAN("lo", "Laothian"), // LATVIAN("la", "Latvian", R.drawable.la), LITHUANIAN("lt", "Lithuanian", R.drawable.lt), // MACEDONIAN("mk", "Macedonian", R.drawable.mk), // MALAY("ms", "Malay", R.drawable.ms), // MALAYALAM("ml", "Malayalam", R.drawable.ml), // MALTESE("mt", "Maltese", R.drawable.mt), // MARATHI("mr", "Marathi", R.drawable.mr), // MONGOLIAN("mn", "Mongolian", R.drawable.mn), // NEPALI("ne", "Nepali", R.drawable.ne), NORWEGIAN("no", "Norwegian", R.drawable.no), // ORIYA("or", "Oriya"), // PASHTO("ps", "Pashto", R.drawable.ps), // PERSIAN("fa", "Persian"), POLISH("pl", "Polish", R.drawable.pl), PORTUGUESE("pt", "Portuguese", R.drawable.pt), // PUNJABI("pa", "Punjabi", R.drawable.pa), ROMANIAN("ro", "Romanian", R.drawable.ro), RUSSIAN("ru", "Russian", R.drawable.ru), // SANSKRIT("sa", "Sanskrit", R.drawable.sa), SERBIAN("sr", "Serbian", R.drawable.sr), // SINDHI("sd", "Sindhi", R.drawable.sd), // SINHALESE("si", "Sinhalese", R.drawable.si), SLOVAK("sk", "Slovak", R.drawable.sk), SLOVENIAN("sl", "Slovenian", R.drawable.sl), SPANISH("es", "Spanish", R.drawable.es), // SWAHILI("sw", "Swahili"), SWEDISH("sv", "Swedish", R.drawable.sv), // TAJIK("tg", "Tajik", R.drawable.tg), // TAMIL("ta", "Tamil"), TAGALOG("tl", "Tagalog", R.drawable.ph), // TELUGU("te", "Telugu"), // THAI("th", "Thai", R.drawable.th), // TIBETAN("bo", "Tibetan", R.drawable.bo), // TURKISH("tr", "Turkish", R.drawable.tr), UKRAINIAN("uk", "Ukrainian", R.drawable.ua), // URDU("ur", "Urdu"), // UZBEK("uz", "Uzbek", R.drawable.uz), // UIGHUR("ug", "Uighur", R.drawable.ug), ; private String mShortName; private String mLongName; private int mFlag; private static Map<String, String> mLongNameToShortName = Maps.newHashMap(); private static Map<String, Language> mShortNameToLanguage = Maps.newHashMap(); static { for (Language language : values()) { mLongNameToShortName.put(language.getLongName(), language.getShortName()); mShortNameToLanguage.put(language.getShortName(), language); } } private Language(String shortName, String longName, int flag) { init(shortName, longName, flag); } private Language(String shortName, String longName) { init(shortName, longName, -1); } private void init(String shortName, String longName, int flag) { mShortName = shortName; mLongName = longName; mFlag = flag; } public String getShortName() { return mShortName; } public String getLongName() { return mLongName; } public int getFlag() { return mFlag; } @Override public String toString() { return mLongName; } public static Language findLanguageByShortName(String shortName) { return mShortNameToLanguage.get(shortName); } public void configureButton(Activity activity, Button button) { button.setTag(this); button.setText(getLongName()); int f = getFlag(); if (f != -1) { Drawable flag = activity.getResources().getDrawable(f); button.setCompoundDrawablesWithIntrinsicBounds(flag, null, null, null); button.setCompoundDrawablePadding(5); } } } public static String getShortName(String longName) { return Language.mLongNameToShortName.get(longName); } private static void log(String s) { Log.d(TranslateActivity.TAG, "[Languages] " + s); } }
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.beust.android.translate; import static android.view.ViewGroup.LayoutParams.FILL_PARENT; import com.beust.android.translate.Languages.Language; import android.app.AlertDialog; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ScrollView; /** * This dialog displays a list of languages and then tells the calling activity which language * was selected. */ public class LanguageDialog extends AlertDialog implements OnClickListener { private TranslateActivity mActivity; private boolean mFrom; protected LanguageDialog(TranslateActivity activity) { super(activity); mActivity = activity; LayoutInflater inflater = (LayoutInflater) activity.getSystemService( Context.LAYOUT_INFLATER_SERVICE); ScrollView scrollView = (ScrollView) inflater.inflate(R.layout.language_dialog, null); setView(scrollView); LinearLayout layout = (LinearLayout) scrollView.findViewById(R.id.languages); LinearLayout current = null; Language[] languages = Language.values(); for (int i = 0; i < languages.length; i++) { if (current != null) { layout.addView(current, new LayoutParams(FILL_PARENT, FILL_PARENT)); } current = new LinearLayout(activity); current.setOrientation(LinearLayout.HORIZONTAL); Button button = (Button) inflater.inflate(R.layout.language_entry, current, false); Language language = languages[i]; language.configureButton(mActivity, button); button.setOnClickListener(this); current.addView(button, button.getLayoutParams()); } if (current != null) { layout.addView(current, new LayoutParams(FILL_PARENT, FILL_PARENT)); } setTitle(" "); // set later, but necessary to put a non-empty string here } private void log(String s) { Log.d(TranslateActivity.TAG, s); } public void onClick(View v) { mActivity.setNewLanguage((Language) v.getTag(), mFrom, true /* translate */); dismiss(); } public void setFrom(boolean from) { log("From set to " + from); mFrom = from; setTitle(from ? mActivity.getString(R.string.translate_from) : mActivity.getString(R.string.translate_to)); } }
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.beust.android.translate; import com.beust.android.translate.Languages.Language; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.util.Log; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; /** * This class handles the history of past translations. */ public class History { private static final String HISTORY = "history"; /** * Sort the translations by timestamp. */ private static final Comparator<HistoryRecord> MOST_RECENT_COMPARATOR = new Comparator<HistoryRecord>() { public int compare(HistoryRecord object1, HistoryRecord object2) { return (int) (object2.when - object1.when); } }; /** * Sort the translations by destination language and then by input. */ private static final Comparator<HistoryRecord> LANGUAGE_COMPARATOR = new Comparator<HistoryRecord>() { public int compare(HistoryRecord object1, HistoryRecord object2) { int result = object1.to.getLongName().compareTo(object2.to.getLongName()); if (result == 0) { result = object1.input.compareTo(object2.input); } return result; } }; private List<HistoryRecord> mHistoryRecords = Lists.newArrayList(); public History(SharedPreferences prefs) { mHistoryRecords = restoreHistory(prefs); } public static List<HistoryRecord> restoreHistory(SharedPreferences prefs) { List<HistoryRecord> result = Lists.newArrayList(); boolean done = false; int i = 0; Map<String, ?> allKeys = prefs.getAll(); for (String key : allKeys.keySet()) { if (key.startsWith(HISTORY)) { String value = (String) allKeys.get(key); result.add(HistoryRecord.decode(value)); } } // while (! done) { // String history = prefs.getString(HISTORY + "-" + i++, null); // if (history != null) { // result.add(HistoryRecord.decode(history)); // } else { // done = true; // } // } return result; } // public void saveHistory(Editor edit) { // log("Saving history"); // for (int i = 0; i < mHistoryRecords.size(); i++) { // HistoryRecord hr = mHistoryRecords.get(i); // edit.putString(HISTORY + "-" + i, hr.encode()); // } // } public static void addHistoryRecord(Context context, Language from, Language to, String input, String output) { History historyRecord = new History(TranslateActivity.getPrefs(context)); HistoryRecord hr = new HistoryRecord(from, to, input, output, System.currentTimeMillis()); // Find an empty key to add this history record SharedPreferences prefs = TranslateActivity.getPrefs(context); int i = 0; while (true) { String key = HISTORY + "-" + i; if (!prefs.contains(key)) { Editor edit = prefs.edit(); edit.putString(key, hr.encode()); log("Committing " + key + " " + hr.encode()); edit.commit(); return; } else { i++; } } } // public static void addHistoryRecord(Context context, List<HistoryRecord> result, HistoryRecord hr) { // if (! result.contains(hr)) { // result.add(hr); // } // Editor edit = getPrefs(context).edit(); // } private static void log(String s) { Log.d(TranslateActivity.TAG, "[History] " + s); } public List<HistoryRecord> getHistoryRecordsMostRecentFirst() { Collections.sort(mHistoryRecords, MOST_RECENT_COMPARATOR); return mHistoryRecords; } public List<HistoryRecord> getHistoryRecordsByLanguages() { Collections.sort(mHistoryRecords, LANGUAGE_COMPARATOR); return mHistoryRecords; } public List<HistoryRecord> getHistoryRecords(Comparator<HistoryRecord> comparator) { if (comparator != null) { Collections.sort(mHistoryRecords, comparator); } return mHistoryRecords; } public void clear(Context context) { int size = mHistoryRecords.size(); mHistoryRecords = Lists.newArrayList(); Editor edit = TranslateActivity.getPrefs(context).edit(); for (int i = 0; i < size; i++) { String key = HISTORY + "-" + i; log("Removing key " + key); edit.remove(key); } edit.commit(); } }
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.beust.android.translate; import com.beust.android.translate.Languages.Language; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.provider.Contacts; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.zip.GZIPInputStream; /** * Main activity for the Translate application. * * @author Cedric Beust * @author Daniel Rall */ public class TranslateActivity extends Activity implements OnClickListener { static final String TAG = "Translate"; private EditText mToEditText; private EditText mFromEditText; private Button mFromButton; private Button mToButton; private Button mTranslateButton; private Button mSwapButton; private Handler mHandler = new Handler(); private ProgressBar mProgressBar; private TextView mStatusView; // true if changing a language should automatically trigger a translation private boolean mDoTranslate = true; // Dialog id's private static final int LANGUAGE_DIALOG_ID = 1; private static final int ABOUT_DIALOG_ID = 2; // Saved preferences private static final String FROM = "from"; private static final String TO = "to"; private static final String INPUT = "input"; private static final String OUTPUT = "output"; // Default language pair if no saved preferences are found private static final String DEFAULT_FROM = Language.ENGLISH.getShortName(); private static final String DEFAULT_TO = Language.GERMAN.getShortName(); private Button mLatestButton; private OnClickListener mClickListener = new OnClickListener() { public void onClick(View v) { mLatestButton = (Button) v; showDialog(LANGUAGE_DIALOG_ID); } }; // Translation service handle. private ITranslate mTranslateService; // ServiceConnection implementation for translation. private ServiceConnection mTranslateConn = new ServiceConnection() { public void onServiceConnected(ComponentName name, IBinder service) { mTranslateService = ITranslate.Stub.asInterface(service); /* TODO(dlr): Register a callback to assure we don't lose our svc. try { mTranslateervice.registerCallback(mTranslateCallback); } catch (RemoteException e) { log("Failed to establish Translate service connection: " + e); return; } */ if (mTranslateService != null) { mTranslateButton.setEnabled(true); } else { mTranslateButton.setEnabled(false); mStatusView.setText(getString(R.string.error)); log("Unable to acquire TranslateService"); } } public void onServiceDisconnected(ComponentName name) { mTranslateButton.setEnabled(false); mTranslateService = null; } }; // Dictionary private static byte[] mWordBuffer; private static int mWordCount; private static ArrayList<Integer> mWordIndices; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.translate_activity); mFromEditText = (EditText) findViewById(R.id.input); mToEditText = (EditText) findViewById(R.id.translation); mFromButton = (Button) findViewById(R.id.from); mToButton = (Button) findViewById(R.id.to); mTranslateButton = (Button) findViewById(R.id.button_translate); mSwapButton = (Button) findViewById(R.id.button_swap); mProgressBar = (ProgressBar) findViewById(R.id.progress_bar); mStatusView = (TextView) findViewById(R.id.status); // // Install the language adapters on both the From and To spinners. // mFromButton.setOnClickListener(mClickListener); mToButton.setOnClickListener(mClickListener); mTranslateButton.setOnClickListener(this); mSwapButton.setOnClickListener(this); mFromEditText.selectAll(); connectToTranslateService(); } private void connectToTranslateService() { Intent intent = new Intent(Intent.ACTION_VIEW); bindService(intent, mTranslateConn, Context.BIND_AUTO_CREATE); } @Override public void onResume() { super.onResume(); SharedPreferences prefs = getPrefs(this); mDoTranslate = false; // // See if we have any saved preference for From // Language from = Language.findLanguageByShortName(prefs.getString(FROM, DEFAULT_FROM)); updateButton(mFromButton, from, false /* don't translate */); // // See if we have any saved preference for To // // Language to = Language.findLanguageByShortName(prefs.getString(TO, DEFAULT_TO)); updateButton(mToButton, to, true /* translate */); // // Restore input and output, if any // mFromEditText.setText(prefs.getString(INPUT, "")); setOutputText(prefs.getString(OUTPUT, "")); mDoTranslate = true; } private void setOutputText(String string) { log("Setting output to " + string); mToEditText.setText(new Entities().unescape(string)); } private void updateButton(Button button, Language language, boolean translate) { language.configureButton(this, button); if (translate) maybeTranslate(); } /** * Launch the translation if the input text field is not empty. */ private void maybeTranslate() { if (mDoTranslate && !TextUtils.isEmpty(mFromEditText.getText().toString())) { doTranslate(); } } @Override public void onPause() { super.onPause(); // // Save the content of our views to the shared preferences // Editor edit = getPrefs(this).edit(); String f = ((Language) mFromButton.getTag()).getShortName(); String t = ((Language) mToButton.getTag()).getShortName(); String input = mFromEditText.getText().toString(); String output = mToEditText.getText().toString(); savePreferences(edit, f, t, input, output); } static void savePreferences(Editor edit, String from, String to, String input, String output) { log("Saving preferences " + from + " " + to + " " + input + " " + output); edit.putString(FROM, from); edit.putString(TO, to); edit.putString(INPUT, input); edit.putString(OUTPUT, output); edit.commit(); } static SharedPreferences getPrefs(Context context) { return context.getSharedPreferences(TAG, Context.MODE_PRIVATE); } @Override protected void onDestroy() { super.onDestroy(); unbindService(mTranslateConn); } public void onClick(View v) { if (v == mTranslateButton) { maybeTranslate(); } else if (v == mSwapButton) { Object newFrom = mToButton.getTag(); Object newTo = mFromButton.getTag(); mFromEditText.setText(mToEditText.getText()); mToEditText.setText(""); setNewLanguage((Language) newFrom, true /* from */, false /* don't translate */); setNewLanguage((Language) newTo, false /* to */, true /* translate */); mFromEditText.requestFocus(); mStatusView.setText(R.string.languages_swapped); } } private void doTranslate() { mStatusView.setText(R.string.retrieving_translation); mHandler.post(new Runnable() { public void run() { mProgressBar.setVisibility(View.VISIBLE); String result = ""; try { Language from = (Language) mFromButton.getTag(); Language to = (Language) mToButton.getTag(); String fromShortName = from.getShortName(); String toShortName = to.getShortName(); String input = mFromEditText.getText().toString(); log("Translating from " + fromShortName + " to " + toShortName); result = mTranslateService.translate(input, fromShortName, toShortName); if (result == null) { throw new Exception(getString(R.string.translation_failed)); } History.addHistoryRecord(TranslateActivity.this, from, to, input, result); mStatusView.setText(R.string.found_translation); setOutputText(result); mProgressBar.setVisibility(View.INVISIBLE); mFromEditText.selectAll(); } catch (Exception e) { mProgressBar.setVisibility(View.INVISIBLE); mStatusView.setText("Error:" + e.getMessage()); } } }); } @Override protected void onPrepareDialog(int id, Dialog d) { if (id == LANGUAGE_DIALOG_ID) { boolean from = mLatestButton == mFromButton; ((LanguageDialog) d).setFrom(from); } } @Override protected Dialog onCreateDialog(int id) { if (id == LANGUAGE_DIALOG_ID) { return new LanguageDialog(this); } else if (id == ABOUT_DIALOG_ID) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.about_title); builder.setMessage(getString(R.string.about_message)); builder.setIcon(R.drawable.babelfish); builder.setPositiveButton(android.R.string.ok, null); builder.setNeutralButton(R.string.send_email, new android.content.DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Intent.ACTION_SENDTO); intent.setData(Uri.parse("mailto:cedric@beust.com")); startActivity(intent); } }); builder.setCancelable(true); return builder.create(); } return null; } /** * Pick a random word and set it as the input word. */ public void selectRandomWord() { BufferedReader fr = null; try { GZIPInputStream is = new GZIPInputStream(getResources().openRawResource(R.raw.dictionary)); if (mWordBuffer == null) { mWordBuffer = new byte[601000]; int n = is.read(mWordBuffer, 0, mWordBuffer.length); int current = n; while (n != -1) { n = is.read(mWordBuffer, current, mWordBuffer.length - current); current += n; } is.close(); mWordCount = 0; mWordIndices = Lists.newArrayList(); for (int i = 0; i < mWordBuffer.length; i++) { if (mWordBuffer[i] == '\n') { mWordCount++; mWordIndices.add(i); } } log("Found " + mWordCount + " words"); } int randomWordIndex = (int) (System.currentTimeMillis() % (mWordCount - 1)); log("Random word index:" + randomWordIndex + " wordCount:" + mWordCount); int start = mWordIndices.get(randomWordIndex); int end = mWordIndices.get(randomWordIndex + 1); byte[] b = new byte[end - start - 2]; System.arraycopy(mWordBuffer, start + 1, b, 0, (end - start - 2)); String randomWord = new String(b); mFromEditText.setText(randomWord); updateButton(mFromButton, Language.findLanguageByShortName(Language.ENGLISH.getShortName()), true /* translate */); } catch (FileNotFoundException e) { Log.e(TAG, e.getMessage(), e); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } } public void setNewLanguage(Language language, boolean from, boolean translate) { updateButton(from ? mFromButton : mToButton, language, translate); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.translate_activity_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.about: showDialog(ABOUT_DIALOG_ID); break; case R.id.show_history: showHistory(); break; case R.id.random_word: selectRandomWord(); break; // We shouldn't need this menu item but because of a bug in 1.0, neither SMS nor Email // filter on the ACTION_SEND intent. Since they won't be shown in the activity chooser, // I need to make an explicit menu for SMS case R.id.send_with_sms: { Intent i = new Intent(Intent.ACTION_PICK, Contacts.Phones.CONTENT_URI); Intent intent = new Intent(Intent.ACTION_PICK); intent.setType(Contacts.Phones.CONTENT_TYPE); startActivityForResult(intent, 42 /* not used */); break; } case R.id.send_with_email: Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, mToEditText.getText()); startActivity(Intent.createChooser(intent, null)); break; } return true; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent resultIntent) { if (resultIntent != null) { Uri contactURI = resultIntent.getData(); Cursor cursor = getContentResolver().query(contactURI, new String[] { Contacts.PhonesColumns.NUMBER }, null, null, null); if (cursor.moveToFirst()) { String phone = cursor.getString(0); Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto://" + phone)); intent.putExtra("sms_body", mToEditText.getText().toString()); startActivity(intent); } } } private void showHistory() { startActivity(new Intent(this, HistoryActivity.class)); } private static void log(String s) { Log.d(TAG, "[TranslateActivity] " + s); } }
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.beust.android.translate; import android.app.AlertDialog; import android.content.Context; import android.webkit.WebView; /** * Display a simple about dialog. */ public class AboutDialog extends AlertDialog { protected AboutDialog(Context context) { super(context); setContentView(R.layout.about_dialog); setTitle(R.string.about_title); setCancelable(true); WebView webView = (WebView) findViewById(R.id.webview); webView.loadData("Written by C&eacute;dric Beust (<a href=\"mailto:cedric@beust.com\">cedric@beust.com)</a>", "text/html", "utf-8"); } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.beust.android.translate; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; /** * <p> * Provides HTML and XML entity utilities. * </p> * * @see <a href="http://hotwired.lycos.com/webmonkey/reference/special_characters/">ISO Entities</a> * @see <a href="http://www.w3.org/TR/REC-html32#latin1">HTML 3.2 Character Entities for ISO Latin-1</a> * @see <a href="http://www.w3.org/TR/REC-html40/sgml/entities.html">HTML 4.0 Character entity references</a> * @see <a href="http://www.w3.org/TR/html401/charset.html#h-5.3">HTML 4.01 Character References</a> * @see <a href="http://www.w3.org/TR/html401/charset.html#code-position">HTML 4.01 Code positions</a> * * @author <a href="mailto:alex@purpletech.com">Alexander Day Chaffee</a> * @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a> * @since 2.0 * @version $Id: Entities.java 636641 2008-03-13 06:11:30Z bayard $ */ class Entities { private static final String[][] BASIC_ARRAY = {{"quot", "34"}, // " - double-quote {"amp", "38"}, // & - ampersand {"lt", "60"}, // < - less-than {"gt", "62"}, // > - greater-than }; private static final String[][] APOS_ARRAY = {{"apos", "39"}, // XML apostrophe }; // package scoped for testing static final String[][] ISO8859_1_ARRAY = {{"nbsp", "160"}, // non-breaking space {"iexcl", "161"}, // inverted exclamation mark {"cent", "162"}, // cent sign {"pound", "163"}, // pound sign {"curren", "164"}, // currency sign {"yen", "165"}, // yen sign = yuan sign {"brvbar", "166"}, // broken bar = broken vertical bar {"sect", "167"}, // section sign {"uml", "168"}, // diaeresis = spacing diaeresis {"copy", "169"}, // - copyright sign {"ordf", "170"}, // feminine ordinal indicator {"laquo", "171"}, // left-pointing double angle quotation mark = left pointing guillemet {"not", "172"}, // not sign {"shy", "173"}, // soft hyphen = discretionary hyphen {"reg", "174"}, // - registered trademark sign {"macr", "175"}, // macron = spacing macron = overline = APL overbar {"deg", "176"}, // degree sign {"plusmn", "177"}, // plus-minus sign = plus-or-minus sign {"sup2", "178"}, // superscript two = superscript digit two = squared {"sup3", "179"}, // superscript three = superscript digit three = cubed {"acute", "180"}, // acute accent = spacing acute {"micro", "181"}, // micro sign {"para", "182"}, // pilcrow sign = paragraph sign {"middot", "183"}, // middle dot = Georgian comma = Greek middle dot {"cedil", "184"}, // cedilla = spacing cedilla {"sup1", "185"}, // superscript one = superscript digit one {"ordm", "186"}, // masculine ordinal indicator {"raquo", "187"}, // right-pointing double angle quotation mark = right pointing guillemet {"frac14", "188"}, // vulgar fraction one quarter = fraction one quarter {"frac12", "189"}, // vulgar fraction one half = fraction one half {"frac34", "190"}, // vulgar fraction three quarters = fraction three quarters {"iquest", "191"}, // inverted question mark = turned question mark {"Agrave", "192"}, // - uppercase A, grave accent {"Aacute", "193"}, // - uppercase A, acute accent {"Acirc", "194"}, // - uppercase A, circumflex accent {"Atilde", "195"}, // - uppercase A, tilde {"Auml", "196"}, // - uppercase A, umlaut {"Aring", "197"}, // - uppercase A, ring {"AElig", "198"}, // - uppercase AE {"Ccedil", "199"}, // - uppercase C, cedilla {"Egrave", "200"}, // - uppercase E, grave accent {"Eacute", "201"}, // - uppercase E, acute accent {"Ecirc", "202"}, // - uppercase E, circumflex accent {"Euml", "203"}, // - uppercase E, umlaut {"Igrave", "204"}, // - uppercase I, grave accent {"Iacute", "205"}, // - uppercase I, acute accent {"Icirc", "206"}, // - uppercase I, circumflex accent {"Iuml", "207"}, // - uppercase I, umlaut {"ETH", "208"}, // - uppercase Eth, Icelandic {"Ntilde", "209"}, // - uppercase N, tilde {"Ograve", "210"}, // - uppercase O, grave accent {"Oacute", "211"}, // - uppercase O, acute accent {"Ocirc", "212"}, // - uppercase O, circumflex accent {"Otilde", "213"}, // - uppercase O, tilde {"Ouml", "214"}, // - uppercase O, umlaut {"times", "215"}, // multiplication sign {"Oslash", "216"}, // - uppercase O, slash {"Ugrave", "217"}, // - uppercase U, grave accent {"Uacute", "218"}, // - uppercase U, acute accent {"Ucirc", "219"}, // - uppercase U, circumflex accent {"Uuml", "220"}, // - uppercase U, umlaut {"Yacute", "221"}, // - uppercase Y, acute accent {"THORN", "222"}, // - uppercase THORN, Icelandic {"szlig", "223"}, // - lowercase sharps, German {"agrave", "224"}, // - lowercase a, grave accent {"aacute", "225"}, // - lowercase a, acute accent {"acirc", "226"}, // - lowercase a, circumflex accent {"atilde", "227"}, // - lowercase a, tilde {"auml", "228"}, // - lowercase a, umlaut {"aring", "229"}, // - lowercase a, ring {"aelig", "230"}, // - lowercase ae {"ccedil", "231"}, // - lowercase c, cedilla {"egrave", "232"}, // - lowercase e, grave accent {"eacute", "233"}, // - lowercase e, acute accent {"ecirc", "234"}, // - lowercase e, circumflex accent {"euml", "235"}, // - lowercase e, umlaut {"igrave", "236"}, // - lowercase i, grave accent {"iacute", "237"}, // - lowercase i, acute accent {"icirc", "238"}, // - lowercase i, circumflex accent {"iuml", "239"}, // - lowercase i, umlaut {"eth", "240"}, // - lowercase eth, Icelandic {"ntilde", "241"}, // - lowercase n, tilde {"ograve", "242"}, // - lowercase o, grave accent {"oacute", "243"}, // - lowercase o, acute accent {"ocirc", "244"}, // - lowercase o, circumflex accent {"otilde", "245"}, // - lowercase o, tilde {"ouml", "246"}, // - lowercase o, umlaut {"divide", "247"}, // division sign {"oslash", "248"}, // - lowercase o, slash {"ugrave", "249"}, // - lowercase u, grave accent {"uacute", "250"}, // - lowercase u, acute accent {"ucirc", "251"}, // - lowercase u, circumflex accent {"uuml", "252"}, // - lowercase u, umlaut {"yacute", "253"}, // - lowercase y, acute accent {"thorn", "254"}, // - lowercase thorn, Icelandic {"yuml", "255"}, // - lowercase y, umlaut }; // http://www.w3.org/TR/REC-html40/sgml/entities.html // package scoped for testing static final String[][] HTML40_ARRAY = { // <!-- Latin Extended-B --> {"fnof", "402"}, // latin small f with hook = function= florin, U+0192 ISOtech --> // <!-- Greek --> {"Alpha", "913"}, // greek capital letter alpha, U+0391 --> {"Beta", "914"}, // greek capital letter beta, U+0392 --> {"Gamma", "915"}, // greek capital letter gamma,U+0393 ISOgrk3 --> {"Delta", "916"}, // greek capital letter delta,U+0394 ISOgrk3 --> {"Epsilon", "917"}, // greek capital letter epsilon, U+0395 --> {"Zeta", "918"}, // greek capital letter zeta, U+0396 --> {"Eta", "919"}, // greek capital letter eta, U+0397 --> {"Theta", "920"}, // greek capital letter theta,U+0398 ISOgrk3 --> {"Iota", "921"}, // greek capital letter iota, U+0399 --> {"Kappa", "922"}, // greek capital letter kappa, U+039A --> {"Lambda", "923"}, // greek capital letter lambda,U+039B ISOgrk3 --> {"Mu", "924"}, // greek capital letter mu, U+039C --> {"Nu", "925"}, // greek capital letter nu, U+039D --> {"Xi", "926"}, // greek capital letter xi, U+039E ISOgrk3 --> {"Omicron", "927"}, // greek capital letter omicron, U+039F --> {"Pi", "928"}, // greek capital letter pi, U+03A0 ISOgrk3 --> {"Rho", "929"}, // greek capital letter rho, U+03A1 --> // <!-- there is no Sigmaf, and no U+03A2 character either --> {"Sigma", "931"}, // greek capital letter sigma,U+03A3 ISOgrk3 --> {"Tau", "932"}, // greek capital letter tau, U+03A4 --> {"Upsilon", "933"}, // greek capital letter upsilon,U+03A5 ISOgrk3 --> {"Phi", "934"}, // greek capital letter phi,U+03A6 ISOgrk3 --> {"Chi", "935"}, // greek capital letter chi, U+03A7 --> {"Psi", "936"}, // greek capital letter psi,U+03A8 ISOgrk3 --> {"Omega", "937"}, // greek capital letter omega,U+03A9 ISOgrk3 --> {"alpha", "945"}, // greek small letter alpha,U+03B1 ISOgrk3 --> {"beta", "946"}, // greek small letter beta, U+03B2 ISOgrk3 --> {"gamma", "947"}, // greek small letter gamma,U+03B3 ISOgrk3 --> {"delta", "948"}, // greek small letter delta,U+03B4 ISOgrk3 --> {"epsilon", "949"}, // greek small letter epsilon,U+03B5 ISOgrk3 --> {"zeta", "950"}, // greek small letter zeta, U+03B6 ISOgrk3 --> {"eta", "951"}, // greek small letter eta, U+03B7 ISOgrk3 --> {"theta", "952"}, // greek small letter theta,U+03B8 ISOgrk3 --> {"iota", "953"}, // greek small letter iota, U+03B9 ISOgrk3 --> {"kappa", "954"}, // greek small letter kappa,U+03BA ISOgrk3 --> {"lambda", "955"}, // greek small letter lambda,U+03BB ISOgrk3 --> {"mu", "956"}, // greek small letter mu, U+03BC ISOgrk3 --> {"nu", "957"}, // greek small letter nu, U+03BD ISOgrk3 --> {"xi", "958"}, // greek small letter xi, U+03BE ISOgrk3 --> {"omicron", "959"}, // greek small letter omicron, U+03BF NEW --> {"pi", "960"}, // greek small letter pi, U+03C0 ISOgrk3 --> {"rho", "961"}, // greek small letter rho, U+03C1 ISOgrk3 --> {"sigmaf", "962"}, // greek small letter final sigma,U+03C2 ISOgrk3 --> {"sigma", "963"}, // greek small letter sigma,U+03C3 ISOgrk3 --> {"tau", "964"}, // greek small letter tau, U+03C4 ISOgrk3 --> {"upsilon", "965"}, // greek small letter upsilon,U+03C5 ISOgrk3 --> {"phi", "966"}, // greek small letter phi, U+03C6 ISOgrk3 --> {"chi", "967"}, // greek small letter chi, U+03C7 ISOgrk3 --> {"psi", "968"}, // greek small letter psi, U+03C8 ISOgrk3 --> {"omega", "969"}, // greek small letter omega,U+03C9 ISOgrk3 --> {"thetasym", "977"}, // greek small letter theta symbol,U+03D1 NEW --> {"upsih", "978"}, // greek upsilon with hook symbol,U+03D2 NEW --> {"piv", "982"}, // greek pi symbol, U+03D6 ISOgrk3 --> // <!-- General Punctuation --> {"bull", "8226"}, // bullet = black small circle,U+2022 ISOpub --> // <!-- bullet is NOT the same as bullet operator, U+2219 --> {"hellip", "8230"}, // horizontal ellipsis = three dot leader,U+2026 ISOpub --> {"prime", "8242"}, // prime = minutes = feet, U+2032 ISOtech --> {"Prime", "8243"}, // double prime = seconds = inches,U+2033 ISOtech --> {"oline", "8254"}, // overline = spacing overscore,U+203E NEW --> {"frasl", "8260"}, // fraction slash, U+2044 NEW --> // <!-- Letterlike Symbols --> {"weierp", "8472"}, // script capital P = power set= Weierstrass p, U+2118 ISOamso --> {"image", "8465"}, // blackletter capital I = imaginary part,U+2111 ISOamso --> {"real", "8476"}, // blackletter capital R = real part symbol,U+211C ISOamso --> {"trade", "8482"}, // trade mark sign, U+2122 ISOnum --> {"alefsym", "8501"}, // alef symbol = first transfinite cardinal,U+2135 NEW --> // <!-- alef symbol is NOT the same as hebrew letter alef,U+05D0 although the // same glyph could be used to depict both characters --> // <!-- Arrows --> {"larr", "8592"}, // leftwards arrow, U+2190 ISOnum --> {"uarr", "8593"}, // upwards arrow, U+2191 ISOnum--> {"rarr", "8594"}, // rightwards arrow, U+2192 ISOnum --> {"darr", "8595"}, // downwards arrow, U+2193 ISOnum --> {"harr", "8596"}, // left right arrow, U+2194 ISOamsa --> {"crarr", "8629"}, // downwards arrow with corner leftwards= carriage return, U+21B5 NEW --> {"lArr", "8656"}, // leftwards double arrow, U+21D0 ISOtech --> // <!-- ISO 10646 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 canbe used for 'is implied by' as ISOtech suggests --> {"uArr", "8657"}, // upwards double arrow, U+21D1 ISOamsa --> {"rArr", "8658"}, // rightwards double arrow,U+21D2 ISOtech --> // <!-- ISO 10646 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, U+21D3 ISOamsa --> {"hArr", "8660"}, // left right double arrow,U+21D4 ISOamsa --> // <!-- Mathematical Operators --> {"forall", "8704"}, // for all, U+2200 ISOtech --> {"part", "8706"}, // partial differential, U+2202 ISOtech --> {"exist", "8707"}, // there exists, U+2203 ISOtech --> {"empty", "8709"}, // empty set = null set = diameter,U+2205 ISOamso --> {"nabla", "8711"}, // nabla = backward difference,U+2207 ISOtech --> {"isin", "8712"}, // element of, U+2208 ISOtech --> {"notin", "8713"}, // not an element of, U+2209 ISOtech --> {"ni", "8715"}, // contains as member, U+220B ISOtech --> // <!-- should there be a more memorable name than 'ni'? --> {"prod", "8719"}, // n-ary product = product sign,U+220F ISOamsb --> // <!-- prod is NOT the same character as U+03A0 'greek capital letter pi' // though the same glyph might be used for both --> {"sum", "8721"}, // n-ary summation, U+2211 ISOamsb --> // <!-- sum is NOT the same character as U+03A3 'greek capital letter sigma' // though the same glyph might be used for both --> {"minus", "8722"}, // minus sign, U+2212 ISOtech --> {"lowast", "8727"}, // asterisk operator, U+2217 ISOtech --> {"radic", "8730"}, // square root = radical sign,U+221A ISOtech --> {"prop", "8733"}, // proportional to, U+221D ISOtech --> {"infin", "8734"}, // infinity, U+221E ISOtech --> {"ang", "8736"}, // angle, U+2220 ISOamso --> {"and", "8743"}, // logical and = wedge, U+2227 ISOtech --> {"or", "8744"}, // logical or = vee, U+2228 ISOtech --> {"cap", "8745"}, // intersection = cap, U+2229 ISOtech --> {"cup", "8746"}, // union = cup, U+222A ISOtech --> {"int", "8747"}, // integral, U+222B ISOtech --> {"there4", "8756"}, // therefore, U+2234 ISOtech --> {"sim", "8764"}, // tilde operator = varies with = similar to,U+223C ISOtech --> // <!-- tilde operator is NOT the same character as the tilde, U+007E,although // the same glyph might be used to represent both --> {"cong", "8773"}, // approximately equal to, U+2245 ISOtech --> {"asymp", "8776"}, // almost equal to = asymptotic to,U+2248 ISOamsr --> {"ne", "8800"}, // not equal to, U+2260 ISOtech --> {"equiv", "8801"}, // identical to, U+2261 ISOtech --> {"le", "8804"}, // less-than or equal to, U+2264 ISOtech --> {"ge", "8805"}, // greater-than or equal to,U+2265 ISOtech --> {"sub", "8834"}, // subset of, U+2282 ISOtech --> {"sup", "8835"}, // superset of, U+2283 ISOtech --> // <!-- note that nsup, 'not a superset of, U+2283' is not covered by the // Symbol font encoding and is not included. Should it be, for symmetry? // It is in ISOamsn --> <!ENTITY nsub", "8836"}, // not a subset of, U+2284 ISOamsn --> {"sube", "8838"}, // subset of or equal to, U+2286 ISOtech --> {"supe", "8839"}, // superset of or equal to,U+2287 ISOtech --> {"oplus", "8853"}, // circled plus = direct sum,U+2295 ISOamsb --> {"otimes", "8855"}, // circled times = vector product,U+2297 ISOamsb --> {"perp", "8869"}, // up tack = orthogonal to = perpendicular,U+22A5 ISOtech --> {"sdot", "8901"}, // dot operator, U+22C5 ISOamsb --> // <!-- dot operator is NOT the same character as U+00B7 middle dot --> // <!-- Miscellaneous Technical --> {"lceil", "8968"}, // left ceiling = apl upstile,U+2308 ISOamsc --> {"rceil", "8969"}, // right ceiling, U+2309 ISOamsc --> {"lfloor", "8970"}, // left floor = apl downstile,U+230A ISOamsc --> {"rfloor", "8971"}, // right floor, U+230B ISOamsc --> {"lang", "9001"}, // left-pointing angle bracket = bra,U+2329 ISOtech --> // <!-- lang is NOT the same character as U+003C 'less than' or U+2039 'single left-pointing angle quotation // mark' --> {"rang", "9002"}, // right-pointing angle bracket = ket,U+232A ISOtech --> // <!-- rang is NOT the same character as U+003E 'greater than' or U+203A // 'single right-pointing angle quotation mark' --> // <!-- Geometric Shapes --> {"loz", "9674"}, // lozenge, U+25CA ISOpub --> // <!-- Miscellaneous Symbols --> {"spades", "9824"}, // black spade suit, U+2660 ISOpub --> // <!-- black here seems to mean filled as opposed to hollow --> {"clubs", "9827"}, // black club suit = shamrock,U+2663 ISOpub --> {"hearts", "9829"}, // black heart suit = valentine,U+2665 ISOpub --> {"diams", "9830"}, // black diamond suit, U+2666 ISOpub --> // <!-- Latin Extended-A --> {"OElig", "338"}, // -- latin capital ligature OE,U+0152 ISOlat2 --> {"oelig", "339"}, // -- latin small ligature oe, U+0153 ISOlat2 --> // <!-- ligature is a misnomer, this is a separate character in some languages --> {"Scaron", "352"}, // -- latin capital letter S with caron,U+0160 ISOlat2 --> {"scaron", "353"}, // -- latin small letter s with caron,U+0161 ISOlat2 --> {"Yuml", "376"}, // -- latin capital letter Y with diaeresis,U+0178 ISOlat2 --> // <!-- Spacing Modifier Letters --> {"circ", "710"}, // -- modifier letter circumflex accent,U+02C6 ISOpub --> {"tilde", "732"}, // small tilde, U+02DC ISOdia --> // <!-- General Punctuation --> {"ensp", "8194"}, // en space, U+2002 ISOpub --> {"emsp", "8195"}, // em space, U+2003 ISOpub --> {"thinsp", "8201"}, // thin space, U+2009 ISOpub --> {"zwnj", "8204"}, // zero width non-joiner,U+200C NEW RFC 2070 --> {"zwj", "8205"}, // zero width joiner, U+200D NEW RFC 2070 --> {"lrm", "8206"}, // left-to-right mark, U+200E NEW RFC 2070 --> {"rlm", "8207"}, // right-to-left mark, U+200F NEW RFC 2070 --> {"ndash", "8211"}, // en dash, U+2013 ISOpub --> {"mdash", "8212"}, // em dash, U+2014 ISOpub --> {"lsquo", "8216"}, // left single quotation mark,U+2018 ISOnum --> {"rsquo", "8217"}, // right single quotation mark,U+2019 ISOnum --> {"sbquo", "8218"}, // single low-9 quotation mark, U+201A NEW --> {"ldquo", "8220"}, // left double quotation mark,U+201C ISOnum --> {"rdquo", "8221"}, // right double quotation mark,U+201D ISOnum --> {"bdquo", "8222"}, // double low-9 quotation mark, U+201E NEW --> {"dagger", "8224"}, // dagger, U+2020 ISOpub --> {"Dagger", "8225"}, // double dagger, U+2021 ISOpub --> {"permil", "8240"}, // per mille sign, U+2030 ISOtech --> {"lsaquo", "8249"}, // single left-pointing angle quotation mark,U+2039 ISO proposed --> // <!-- lsaquo is proposed but not yet ISO standardized --> {"rsaquo", "8250"}, // single right-pointing angle quotation mark,U+203A ISO proposed --> // <!-- rsaquo is proposed but not yet ISO standardized --> {"euro", "8364"}, // -- euro sign, U+20AC NEW --> }; /** * <p> * The set of entities supported by standard XML. * </p> */ public static final Entities XML; /** * <p> * The set of entities supported by HTML 3.2. * </p> */ public static final Entities HTML32; /** * <p> * The set of entities supported by HTML 4.0. * </p> */ public static final Entities HTML40; static { XML = new Entities(); XML.addEntities(BASIC_ARRAY); XML.addEntities(APOS_ARRAY); } static { HTML32 = new Entities(); HTML32.addEntities(BASIC_ARRAY); HTML32.addEntities(ISO8859_1_ARRAY); } static { HTML40 = new Entities(); fillWithHtml40Entities(HTML40); } /** * <p> * Fills the specified entities instance with HTML 40 entities. * </p> * * @param entities * the instance to be filled. */ static void fillWithHtml40Entities(Entities entities) { entities.addEntities(BASIC_ARRAY); entities.addEntities(ISO8859_1_ARRAY); entities.addEntities(HTML40_ARRAY); } static interface EntityMap { /** * <p> * Add an entry to this entity map. * </p> * * @param name * the entity name * @param value * the entity value */ void add(String name, int value); /** * <p> * Returns the name of the entity identified by the specified value. * </p> * * @param value * the value to locate * @return entity name associated with the specified value */ String name(int value); /** * <p> * Returns the value of the entity identified by the specified name. * </p> * * @param name * the name to locate * @return entity value associated with the specified name */ int value(String name); } static class PrimitiveEntityMap implements EntityMap { private Map mapNameToValue = new HashMap(); private Map<Integer, Object> mapValueToName = Maps.newHashMap(); /** * {@inheritDoc} */ public void add(String name, int value) { mapNameToValue.put(name, new Integer(value)); mapValueToName.put(value, name); } /** * {@inheritDoc} */ public String name(int value) { return (String) mapValueToName.get(value); } /** * {@inheritDoc} */ public int value(String name) { Object value = mapNameToValue.get(name); if (value == null) { return -1; } return ((Integer) value).intValue(); } } static abstract class MapIntMap implements Entities.EntityMap { protected Map mapNameToValue; protected Map mapValueToName; /** * {@inheritDoc} */ public void add(String name, int value) { mapNameToValue.put(name, new Integer(value)); mapValueToName.put(new Integer(value), name); } /** * {@inheritDoc} */ public String name(int value) { return (String) mapValueToName.get(new Integer(value)); } /** * {@inheritDoc} */ public int value(String name) { Object value = mapNameToValue.get(name); if (value == null) { return -1; } return ((Integer) value).intValue(); } } static class HashEntityMap extends MapIntMap { /** * Constructs a new instance of <code>HashEntityMap</code>. */ public HashEntityMap() { mapNameToValue = new HashMap(); mapValueToName = new HashMap(); } } static class TreeEntityMap extends MapIntMap { /** * Constructs a new instance of <code>TreeEntityMap</code>. */ public TreeEntityMap() { mapNameToValue = new TreeMap(); mapValueToName = new TreeMap(); } } static class LookupEntityMap extends PrimitiveEntityMap { private String[] lookupTable; private int LOOKUP_TABLE_SIZE = 256; /** * {@inheritDoc} */ public String name(int value) { if (value < LOOKUP_TABLE_SIZE) { return lookupTable()[value]; } return super.name(value); } /** * <p> * Returns the lookup table for this entity map. The lookup table is created if it has not been previously. * </p> * * @return the lookup table */ private String[] lookupTable() { if (lookupTable == null) { createLookupTable(); } return lookupTable; } /** * <p> * Creates an entity lookup table of LOOKUP_TABLE_SIZE elements, initialized with entity names. * </p> */ private void createLookupTable() { lookupTable = new String[LOOKUP_TABLE_SIZE]; for (int i = 0; i < LOOKUP_TABLE_SIZE; ++i) { lookupTable[i] = super.name(i); } } } static class ArrayEntityMap implements EntityMap { protected int growBy = 100; protected int size = 0; protected String[] names; protected int[] values; /** * Constructs a new instance of <code>ArrayEntityMap</code>. */ public ArrayEntityMap() { names = new String[growBy]; values = new int[growBy]; } /** * Constructs a new instance of <code>ArrayEntityMap</code> specifying the size by which the array should * grow. * * @param growBy * array will be initialized to and will grow by this amount */ public ArrayEntityMap(int growBy) { this.growBy = growBy; names = new String[growBy]; values = new int[growBy]; } /** * {@inheritDoc} */ public void add(String name, int value) { ensureCapacity(size + 1); names[size] = name; values[size] = value; size++; } /** * Verifies the capacity of the entity array, adjusting the size if necessary. * * @param capacity * size the array should be */ protected void ensureCapacity(int capacity) { if (capacity > names.length) { int newSize = Math.max(capacity, size + growBy); String[] newNames = new String[newSize]; System.arraycopy(names, 0, newNames, 0, size); names = newNames; int[] newValues = new int[newSize]; System.arraycopy(values, 0, newValues, 0, size); values = newValues; } } /** * {@inheritDoc} */ public String name(int value) { for (int i = 0; i < size; ++i) { if (values[i] == value) { return names[i]; } } return null; } /** * {@inheritDoc} */ public int value(String name) { for (int i = 0; i < size; ++i) { if (names[i].equals(name)) { return values[i]; } } return -1; } } static class BinaryEntityMap extends ArrayEntityMap { /** * Constructs a new instance of <code>BinaryEntityMap</code>. */ public BinaryEntityMap() { super(); } /** * Constructs a new instance of <code>ArrayEntityMap</code> specifying the size by which the underlying array * should grow. * * @param growBy * array will be initialized to and will grow by this amount */ public BinaryEntityMap(int growBy) { super(growBy); } /** * Performs a binary search of the entity array for the specified key. This method is based on code in * {@link java.util.Arrays}. * * @param key * the key to be found * @return the index of the entity array matching the specified key */ private int binarySearch(int key) { int low = 0; int high = size - 1; while (low <= high) { int mid = (low + high) >>> 1; int midVal = values[mid]; if (midVal < key) { low = mid + 1; } else if (midVal > key) { high = mid - 1; } else { return mid; // key found } } return -(low + 1); // key not found. } /** * {@inheritDoc} */ public void add(String name, int value) { ensureCapacity(size + 1); int insertAt = binarySearch(value); if (insertAt > 0) { return; // note: this means you can't insert the same value twice } insertAt = -(insertAt + 1); // binarySearch returns it negative and off-by-one System.arraycopy(values, insertAt, values, insertAt + 1, size - insertAt); values[insertAt] = value; System.arraycopy(names, insertAt, names, insertAt + 1, size - insertAt); names[insertAt] = name; size++; } /** * {@inheritDoc} */ public String name(int value) { int index = binarySearch(value); if (index < 0) { return null; } return names[index]; } } // package scoped for testing EntityMap map = new Entities.LookupEntityMap(); /** * <p> * Adds entities to this entity. * </p> * * @param entityArray * array of entities to be added */ public void addEntities(String[][] entityArray) { for (int i = 0; i < entityArray.length; ++i) { addEntity(entityArray[i][0], Integer.parseInt(entityArray[i][1])); } } /** * <p> * Add an entity to this entity. * </p> * * @param name * name of the entity * @param value * vale of the entity */ public void addEntity(String name, int value) { map.add(name, value); } /** * <p> * Returns the name of the entity identified by the specified value. * </p> * * @param value * the value to locate * @return entity name associated with the specified value */ public String entityName(int value) { return map.name(value); } /** * <p> * Returns the value of the entity identified by the specified name. * </p> * * @param name * the name to locate * @return entity value associated with the specified name */ public int entityValue(String name) { return map.value(name); } /** * <p> * Escapes the characters in a <code>String</code>. * </p> * * <p> * For example, if you have called addEntity(&quot;foo&quot;, 0xA1), escape(&quot;\u00A1&quot;) will return * &quot;&amp;foo;&quot; * </p> * * @param str * The <code>String</code> to escape. * @return A new escaped <code>String</code>. */ public String escape(String str) { StringWriter stringWriter = createStringWriter(str); try { this.escape(stringWriter, str); } catch (IOException e) { // This should never happen because ALL the StringWriter methods called by #escape(Writer, String) do not // throw IOExceptions. throw new RuntimeException(e); } return stringWriter.toString(); } /** * <p> * Escapes the characters in the <code>String</code> passed and writes the result to the <code>Writer</code> * passed. * </p> * * @param writer * The <code>Writer</code> to write the results of the escaping to. Assumed to be a non-null value. * @param str * The <code>String</code> to escape. Assumed to be a non-null value. * @throws IOException * when <code>Writer</code> passed throws the exception from calls to the {@link Writer#write(int)} * methods. * * @see #escape(String) * @see Writer */ public void escape(Writer writer, String str) throws IOException { int len = str.length(); for (int i = 0; i < len; i++) { char c = str.charAt(i); String entityName = this.entityName(c); if (entityName == null) { if (c > 0x7F) { writer.write("&#"); writer.write(Integer.toString(c, 10)); writer.write(';'); } else { writer.write(c); } } else { writer.write('&'); writer.write(entityName); writer.write(';'); } } } /** * <p> * Unescapes the entities in a <code>String</code>. * </p> * * <p> * For example, if you have called addEntity(&quot;foo&quot;, 0xA1), unescape(&quot;&amp;foo;&quot;) will return * &quot;\u00A1&quot; * </p> * * @param str * The <code>String</code> to escape. * @return A new escaped <code>String</code>. */ public String unescape(String str) { int firstAmp = str.indexOf('&'); if (firstAmp < 0) { return str; } else { StringWriter stringWriter = createStringWriter(str); try { this.doUnescape(stringWriter, str, firstAmp); } catch (IOException e) { // This should never happen because ALL the StringWriter methods called by #escape(Writer, String) // do not throw IOExceptions. throw new RuntimeException(e); } return stringWriter.toString(); } } /** * Make the StringWriter 10% larger than the source String to avoid growing the writer * * @param str The source string * @return A newly created StringWriter */ private StringWriter createStringWriter(String str) { return new StringWriter((int) (str.length() + (str.length() * 0.1))); } /** * <p> * Unescapes the escaped entities in the <code>String</code> passed and writes the result to the * <code>Writer</code> passed. * </p> * * @param writer * The <code>Writer</code> to write the results to; assumed to be non-null. * @param str * The source <code>String</code> to unescape; assumed to be non-null. * @throws IOException * when <code>Writer</code> passed throws the exception from calls to the {@link Writer#write(int)} * methods. * * @see #escape(String) * @see Writer */ public void unescape(Writer writer, String str) throws IOException { int firstAmp = str.indexOf('&'); if (firstAmp < 0) { writer.write(str); return; } else { doUnescape(writer, str, firstAmp); } } /** * Underlying unescape method that allows the optimisation of not starting from the 0 index again. * * @param writer * The <code>Writer</code> to write the results to; assumed to be non-null. * @param str * The source <code>String</code> to unescape; assumed to be non-null. * @param firstAmp * The <code>int</code> index of the first ampersand in the source String. * @throws IOException * when <code>Writer</code> passed throws the exception from calls to the {@link Writer#write(int)} * methods. */ private void doUnescape(Writer writer, String str, int firstAmp) throws IOException { writer.write(str, 0, firstAmp); int len = str.length(); for (int i = firstAmp; i < len; i++) { char c = str.charAt(i); if (c == '&') { int nextIdx = i + 1; int semiColonIdx = str.indexOf(';', nextIdx); if (semiColonIdx == -1) { writer.write(c); continue; } int amphersandIdx = str.indexOf('&', i + 1); if (amphersandIdx != -1 && amphersandIdx < semiColonIdx) { // Then the text looks like &...&...; writer.write(c); continue; } String entityContent = str.substring(nextIdx, semiColonIdx); int entityValue = -1; int entityContentLen = entityContent.length(); if (entityContentLen > 0) { if (entityContent.charAt(0) == '#') { // escaped value content is an integer (decimal or // hexidecimal) if (entityContentLen > 1) { char isHexChar = entityContent.charAt(1); try { switch (isHexChar) { case 'X' : case 'x' : { entityValue = Integer.parseInt(entityContent.substring(2), 16); break; } default : { entityValue = Integer.parseInt(entityContent.substring(1), 10); } } if (entityValue > 0xFFFF) { entityValue = -1; } } catch (NumberFormatException e) { entityValue = -1; } } } else { // escaped value content is an entity name entityValue = this.entityValue(entityContent); } } if (entityValue == -1) { writer.write('&'); writer.write(entityContent); writer.write(';'); } else { writer.write(entityValue); } i = semiColonIdx; // move index up to the semi-colon } else { writer.write(c); } } } }
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.beust.android.translate; import static com.beust.android.translate.Languages.Language; /** * This class describes one entry in the history */ public class HistoryRecord { private static final String SEPARATOR = "@"; public Language from; public Language to; public String input; public String output; public long when; public HistoryRecord(Language from, Language to, String input, String output, long when) { super(); this.from = from; this.to = to; this.input = input; this.output = output; this.when = when; } @Override public boolean equals(Object o) { if (o == null) return false; if (o == this) return true; try { HistoryRecord other = (HistoryRecord) o; return other.from.equals(from) && other.to.equals(to) && other.input.equals(input) && other.output.equals(output); } catch(Exception ex) { return false; } } @Override public int hashCode() { return from.hashCode() ^ to.hashCode() ^ input.hashCode() ^ output.hashCode(); } public String encode() { return from.name() + SEPARATOR + to.name() + SEPARATOR + input + SEPARATOR + output + SEPARATOR + new Long(when); } @Override public String toString() { return encode(); } public static HistoryRecord decode(String s) { Object[] o = s.split(SEPARATOR); int i = 0; Language from = Language.valueOf((String) o[i++]); Language to = Language.valueOf((String) o[i++]); String input = (String) o[i++]; String output = (String) o[i++]; Long when = Long.valueOf((String) o[i++]); HistoryRecord result = new HistoryRecord(from, to, input, output, when); return result; } }
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.beust.android.translate; import android.app.ListActivity; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.SimpleAdapter; import android.widget.AdapterView.OnItemClickListener; import java.util.List; import java.util.Map; /** * This activity displays the history of past translations. * * @author Cedric Beust * @author Daniel Rall */ public class HistoryActivity extends ListActivity implements OnItemClickListener { private SimpleAdapter mAdapter; private List<Map<String, String>> mListData; private History mHistory; private static final String INPUT = "input"; private static final String OUTPUT = "output"; private static final String FROM = "from"; private static final String TO = "to"; private static final String FROM_SHORT_NAME = "from-short-name"; private static final String TO_SHORT_NAME = "to-short-name"; // These constants are used to bind the adapter to the list view private static final String[] COLUMN_NAMES = { INPUT, OUTPUT, FROM, TO }; private static final int[] VIEW_IDS = { R.id.input, R.id.output, R.id.from, R.id.to }; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.history_activity); mHistory = new History(TranslateActivity.getPrefs(this)); initializeAdapter(mHistory.getHistoryRecordsMostRecentFirst()); getListView().setEmptyView(findViewById(R.id.empty)); } private void initializeAdapter(List<HistoryRecord> historyRecords) { mListData = Lists.newArrayList(); for (HistoryRecord hr : historyRecords) { Map<String, String> data = Maps.newHashMap(); // Values that are bound to views data.put(INPUT, hr.input); data.put(OUTPUT, hr.output); data.put(FROM, hr.from.name().toLowerCase()); data.put(TO, hr.to.name().toLowerCase()); // Extra values we keep around for convenience data.put(FROM_SHORT_NAME, hr.from.getShortName()); data.put(TO_SHORT_NAME, hr.to.getShortName()); mListData.add(data); } mAdapter = new SimpleAdapter(this, mListData, R.layout.history_record, COLUMN_NAMES, VIEW_IDS); getListView().setAdapter(mAdapter); getListView().setOnItemClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.history_activity_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.most_recent: initializeAdapter(mHistory.getHistoryRecordsMostRecentFirst()); break; case R.id.languages: initializeAdapter(mHistory.getHistoryRecordsByLanguages()); break; case R.id.clear_history: mHistory.clear(this); initializeAdapter(mHistory.getHistoryRecordsByLanguages()); break; } return true; } public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Map<String, String> data = (Map<String, String>) parent.getItemAtPosition(position); Editor edit = TranslateActivity.getPrefs(this).edit(); TranslateActivity.savePreferences(edit, data.get(FROM_SHORT_NAME), data.get(TO_SHORT_NAME), data.get(INPUT), data.get(OUTPUT)); 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 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