code
stringlengths
3
1.18M
language
stringclasses
1 value
package org.anddev.andengine.examples.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:11:40 - 11.03.2011 */ public class ConnectionCloseServerMessage extends ServerMessage implements ServerMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public ConnectionCloseServerMessage() { } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_CONNECTION_CLOSE; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { /* Nothing to read. */ } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { /* Nothing to write. */ } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:23:15 - 21.05.2011 */ public class ConnectionRejectedProtocolMissmatchServerMessage extends ServerMessage implements ServerMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private short mProtocolVersion; // =========================================================== // Constructors // =========================================================== @Deprecated public ConnectionRejectedProtocolMissmatchServerMessage() { } public ConnectionRejectedProtocolMissmatchServerMessage(final short pProtocolVersion) { this.mProtocolVersion = pProtocolVersion; } // =========================================================== // Getter & Setter // =========================================================== public short getProtocolVersion() { return this.mProtocolVersion; } public void setProtocolVersion(final short pProtocolVersion) { this.mProtocolVersion = pProtocolVersion; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_CONNECTION_REJECTED_PROTOCOL_MISSMATCH; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mProtocolVersion = pDataInputStream.readShort(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeShort(this.mProtocolVersion); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.server; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:59:39 - 21.05.2011 */ public interface ServerMessageFlags { // =========================================================== // Final Fields // =========================================================== /* Connection Flags. */ public static final short FLAG_MESSAGE_SERVER_CONNECTION_CLOSE = Short.MIN_VALUE; public static final short FLAG_MESSAGE_SERVER_CONNECTION_ESTABLISHED = FLAG_MESSAGE_SERVER_CONNECTION_CLOSE + 1; public static final short FLAG_MESSAGE_SERVER_CONNECTION_REJECTED_PROTOCOL_MISSMATCH = FLAG_MESSAGE_SERVER_CONNECTION_ESTABLISHED + 1; public static final short FLAG_MESSAGE_SERVER_CONNECTION_PONG = FLAG_MESSAGE_SERVER_CONNECTION_REJECTED_PROTOCOL_MISSMATCH + 1; // =========================================================== // Methods // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:23:20 - 21.05.2011 */ public class ConnectionPongServerMessage extends ServerMessage implements ServerMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private long mTimestamp; // =========================================================== // Constructors // =========================================================== @Deprecated public ConnectionPongServerMessage() { } public ConnectionPongServerMessage(final long pTimestamp) { this.mTimestamp = pTimestamp; } // =========================================================== // Getter & Setter // =========================================================== public long getTimestamp() { return this.mTimestamp; } public void setTimestamp(long pTimestamp) { this.mTimestamp = pTimestamp; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_CONNECTION_PONG; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mTimestamp = pDataInputStream.readLong(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeLong(this.mTimestamp); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:23:25 - 21.05.2011 */ public class ConnectionEstablishedServerMessage extends ServerMessage implements ServerMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public ConnectionEstablishedServerMessage() { } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_CONNECTION_ESTABLISHED; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { /* Nothing to read. */ } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { /* Nothing to write. */ } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.cityradar; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:32:16 - 28.10.2010 */ public class City { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final String mName; private final double mLatitude; private final double mLongitude; private double mDistanceToUser; private double mBearingToUser; // =========================================================== // Constructors // =========================================================== public City(final String pName, final double pLatitude, final double pLongitude) { this.mName = pName; this.mLatitude = pLatitude; this.mLongitude = pLongitude; } // =========================================================== // Getter & Setter // =========================================================== public final String getName() { return this.mName; } public final double getLatitude() { return this.mLatitude; } public final double getLongitude() { return this.mLongitude; } public double getDistanceToUser() { return this.mDistanceToUser; } public void setDistanceToUser(final double pDistanceToUser) { this.mDistanceToUser = pDistanceToUser; } public double getBearingToUser() { return this.mBearingToUser; } public void setBearingToUser(final double pBearingToUser) { this.mBearingToUser = pBearingToUser; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt; public enum ZoomState { // =========================================================== // Elements // =========================================================== IN, OUT, NONE; // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.Scene.ITouchArea; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.messages.client.ClientMessageFlags; import org.anddev.andengine.examples.adt.messages.server.ConnectionCloseServerMessage; import org.anddev.andengine.examples.adt.messages.server.ServerMessageFlags; import org.anddev.andengine.examples.util.BluetoothListDevicesActivity; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.IMessage; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.IServerMessage; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; import org.anddev.andengine.extension.multiplayer.protocol.client.IServerMessageHandler; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.BluetoothSocketConnectionServerConnector; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.BluetoothSocketConnectionServerConnector.IBluetoothSocketConnectionServerConnectorListener; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.ServerConnector; import org.anddev.andengine.extension.multiplayer.protocol.exception.BluetoothException; import org.anddev.andengine.extension.multiplayer.protocol.server.BluetoothSocketServer; import org.anddev.andengine.extension.multiplayer.protocol.server.BluetoothSocketServer.IBluetoothSocketServerListener; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.BluetoothSocketConnectionClientConnector; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.BluetoothSocketConnectionClientConnector.IBluetoothSocketConnectionClientConnectorListener; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.ClientConnector; import org.anddev.andengine.extension.multiplayer.protocol.shared.BluetoothSocketConnection; import org.anddev.andengine.extension.multiplayer.protocol.util.MessagePool; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.Debug; import android.app.AlertDialog; import android.app.Dialog; import android.bluetooth.BluetoothAdapter; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.os.Bundle; import android.util.SparseArray; import android.view.KeyEvent; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:45:03 - 06.03.2011 */ public class MultiplayerBluetoothExample extends BaseExample implements ClientMessageFlags, ServerMessageFlags { // =========================================================== // Constants // =========================================================== /** Create your own unique UUID at: http://www.uuidgenerator.com/ */ private static final String EXAMPLE_UUID = "6D2DF50E-06EF-C21C-7DB0-345099A5F64E"; private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final short FLAG_MESSAGE_SERVER_ADD_FACE = 1; private static final short FLAG_MESSAGE_SERVER_MOVE_FACE = FLAG_MESSAGE_SERVER_ADD_FACE + 1; private static final int DIALOG_CHOOSE_SERVER_OR_CLIENT_ID = 0; private static final int DIALOG_SHOW_SERVER_IP_ID = DIALOG_CHOOSE_SERVER_OR_CLIENT_ID + 1; private static final int REQUESTCODE_BLUETOOTH_ENABLE = 0; private static final int REQUESTCODE_BLUETOOTH_CONNECT = REQUESTCODE_BLUETOOTH_ENABLE + 1; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private int mFaceIDCounter; private final SparseArray<Sprite> mFaces = new SparseArray<Sprite>(); private String mServerMACAddress; private BluetoothSocketServer<BluetoothSocketConnectionClientConnector> mBluetoothSocketServer; private ServerConnector<BluetoothSocketConnection> mServerConnector; private final MessagePool<IMessage> mMessagePool = new MessagePool<IMessage>(); private BluetoothAdapter mBluetoothAdapter; // =========================================================== // Constructors // =========================================================== public MultiplayerBluetoothExample() { this.initMessagePool(); } private void initMessagePool() { this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_ADD_FACE, AddFaceServerMessage.class); this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_MOVE_FACE, MoveFaceServerMessage.class); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onCreate(final Bundle pSavedInstanceState) { super.onCreate(pSavedInstanceState); this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); this.mServerMACAddress = BluetoothAdapter.getDefaultAdapter().getAddress(); if (this.mBluetoothAdapter == null) { Toast.makeText(this, "Bluetooth is not available!", Toast.LENGTH_LONG).show(); this.finish(); return; } else { if (this.mBluetoothAdapter.isEnabled()) { this.showDialog(DIALOG_CHOOSE_SERVER_OR_CLIENT_ID); } else { final Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); this.startActivityForResult(enableIntent, REQUESTCODE_BLUETOOTH_ENABLE); } } } @Override protected Dialog onCreateDialog(final int pID) { switch(pID) { case DIALOG_SHOW_SERVER_IP_ID: return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Server-Details") .setCancelable(false) .setMessage("The Name of your Server is:\n" + BluetoothAdapter.getDefaultAdapter().getName() + "\n" + "The MACAddress of your Server is:\n" + this.mServerMACAddress) .setPositiveButton(android.R.string.ok, null) .create(); case DIALOG_CHOOSE_SERVER_OR_CLIENT_ID: return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Be Server or Client ...") .setCancelable(false) .setPositiveButton("Client", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { final Intent intent = new Intent(MultiplayerBluetoothExample.this, BluetoothListDevicesActivity.class); MultiplayerBluetoothExample.this.startActivityForResult(intent, REQUESTCODE_BLUETOOTH_CONNECT); } }) .setNeutralButton("Server", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerBluetoothExample.this.toast("You can add and move sprites, which are only shown on the clients."); MultiplayerBluetoothExample.this.initServer(); MultiplayerBluetoothExample.this.showDialog(DIALOG_SHOW_SERVER_IP_ID); } }) .setNegativeButton("Both", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerBluetoothExample.this.toast("You can add sprites and move them, by dragging them."); MultiplayerBluetoothExample.this.initServerAndClient(); MultiplayerBluetoothExample.this.showDialog(DIALOG_SHOW_SERVER_IP_ID); } }) .create(); default: return super.onCreateDialog(pID); } } @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override protected void onDestroy() { if(this.mBluetoothSocketServer != null) { try { this.mBluetoothSocketServer.sendBroadcastServerMessage(new ConnectionCloseServerMessage()); } catch (final IOException e) { Debug.e(e); } this.mBluetoothSocketServer.terminate(); } if(this.mServerConnector != null) { this.mServerConnector.terminate(); } super.onDestroy(); } @Override public boolean onKeyUp(final int pKeyCode, final KeyEvent pEvent) { switch(pKeyCode) { case KeyEvent.KEYCODE_BACK: this.finish(); return true; } return super.onKeyUp(pKeyCode, pEvent); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* We allow only the server to actively send around messages. */ if(MultiplayerBluetoothExample.this.mBluetoothSocketServer != null) { scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pSceneTouchEvent.isActionDown()) { try { final AddFaceServerMessage addFaceServerMessage = (AddFaceServerMessage) MultiplayerBluetoothExample.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_ADD_FACE); addFaceServerMessage.set(MultiplayerBluetoothExample.this.mFaceIDCounter++, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); MultiplayerBluetoothExample.this.mBluetoothSocketServer.sendBroadcastServerMessage(addFaceServerMessage); MultiplayerBluetoothExample.this.mMessagePool.recycleMessage(addFaceServerMessage); } catch (final IOException e) { Debug.e(e); } return true; } else { return false; } } }); scene.setOnAreaTouchListener(new IOnAreaTouchListener() { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { try { final Sprite face = (Sprite)pTouchArea; final Integer faceID = (Integer)face.getUserData(); final MoveFaceServerMessage moveFaceServerMessage = (MoveFaceServerMessage) MultiplayerBluetoothExample.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_MOVE_FACE); moveFaceServerMessage.set(faceID, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); MultiplayerBluetoothExample.this.mBluetoothSocketServer.sendBroadcastServerMessage(moveFaceServerMessage); MultiplayerBluetoothExample.this.mMessagePool.recycleMessage(moveFaceServerMessage); } catch (final IOException e) { Debug.e(e); return false; } return true; } }); scene.setTouchAreaBindingEnabled(true); } return scene; } @Override public void onLoadComplete() { } @Override protected void onActivityResult(final int pRequestCode, final int pResultCode, final Intent pData) { switch(pRequestCode) { case REQUESTCODE_BLUETOOTH_ENABLE: this.showDialog(DIALOG_CHOOSE_SERVER_OR_CLIENT_ID); break; case REQUESTCODE_BLUETOOTH_CONNECT: this.mServerMACAddress = pData.getExtras().getString(BluetoothListDevicesActivity.EXTRA_DEVICE_ADDRESS); this.initClient(); break; default: super.onActivityResult(pRequestCode, pResultCode, pData); } } // =========================================================== // Methods // =========================================================== public void addFace(final int pID, final float pX, final float pY) { final Scene scene = this.mEngine.getScene(); /* Create the face and add it to the scene. */ final Sprite face = new Sprite(0, 0, this.mFaceTextureRegion); face.setPosition(pX - face.getWidth() * 0.5f, pY - face.getHeight() * 0.5f); face.setUserData(pID); this.mFaces.put(pID, face); scene.registerTouchArea(face); scene.attachChild(face); } public void moveFace(final int pID, final float pX, final float pY) { /* Find and move the face. */ final Sprite face = this.mFaces.get(pID); face.setPosition(pX - face.getWidth() * 0.5f, pY - face.getHeight() * 0.5f); } private void initServerAndClient() { this.initServer(); /* Wait some time after the server has been started, so it actually can start up. */ try { Thread.sleep(500); } catch (final Throwable t) { Debug.e(t); } this.initClient(); } private void initServer() { this.mServerMACAddress = BluetoothAdapter.getDefaultAdapter().getAddress(); try { this.mBluetoothSocketServer = new BluetoothSocketServer<BluetoothSocketConnectionClientConnector>(EXAMPLE_UUID, new ExampleClientConnectorListener(), new ExampleServerStateListener()) { @Override protected BluetoothSocketConnectionClientConnector newClientConnector(final BluetoothSocketConnection pBluetoothSocketConnection) throws IOException { try { return new BluetoothSocketConnectionClientConnector(pBluetoothSocketConnection); } catch (final BluetoothException e) { Debug.e(e); /* Actually cannot happen. */ return null; } } }; } catch (final BluetoothException e) { Debug.e(e); } this.mBluetoothSocketServer.start(); } private void initClient() { try { this.mServerConnector = new BluetoothSocketConnectionServerConnector(new BluetoothSocketConnection(this.mBluetoothAdapter, this.mServerMACAddress, EXAMPLE_UUID), new ExampleServerConnectorListener()); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_CONNECTION_CLOSE, ConnectionCloseServerMessage.class, new IServerMessageHandler<BluetoothSocketConnection>() { @Override public void onHandleMessage(final ServerConnector<BluetoothSocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { MultiplayerBluetoothExample.this.finish(); } }); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_ADD_FACE, AddFaceServerMessage.class, new IServerMessageHandler<BluetoothSocketConnection>() { @Override public void onHandleMessage(final ServerConnector<BluetoothSocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final AddFaceServerMessage addFaceServerMessage = (AddFaceServerMessage)pServerMessage; MultiplayerBluetoothExample.this.addFace(addFaceServerMessage.mID, addFaceServerMessage.mX, addFaceServerMessage.mY); } }); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_MOVE_FACE, MoveFaceServerMessage.class, new IServerMessageHandler<BluetoothSocketConnection>() { @Override public void onHandleMessage(final ServerConnector<BluetoothSocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final MoveFaceServerMessage moveFaceServerMessage = (MoveFaceServerMessage)pServerMessage; MultiplayerBluetoothExample.this.moveFace(moveFaceServerMessage.mID, moveFaceServerMessage.mX, moveFaceServerMessage.mY); } }); this.mServerConnector.getConnection().start(); } catch (final Throwable t) { Debug.e(t); } } private void log(final String pMessage) { Debug.d(pMessage); } private void toast(final String pMessage) { this.log(pMessage); this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MultiplayerBluetoothExample.this, pMessage, Toast.LENGTH_SHORT).show(); } }); } // =========================================================== // Inner and Anonymous Classes // =========================================================== public static class AddFaceServerMessage extends ServerMessage { private int mID; private float mX; private float mY; public AddFaceServerMessage() { } public AddFaceServerMessage(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } public void set(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } @Override public short getFlag() { return FLAG_MESSAGE_SERVER_ADD_FACE; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mID = pDataInputStream.readInt(); this.mX = pDataInputStream.readFloat(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mID); pDataOutputStream.writeFloat(this.mX); pDataOutputStream.writeFloat(this.mY); } } public static class MoveFaceServerMessage extends ServerMessage { private int mID; private float mX; private float mY; public MoveFaceServerMessage() { } public MoveFaceServerMessage(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } public void set(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } @Override public short getFlag() { return FLAG_MESSAGE_SERVER_MOVE_FACE; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mID = pDataInputStream.readInt(); this.mX = pDataInputStream.readFloat(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mID); pDataOutputStream.writeFloat(this.mX); pDataOutputStream.writeFloat(this.mY); } } private class ExampleServerConnectorListener implements IBluetoothSocketConnectionServerConnectorListener { @Override public void onStarted(final ServerConnector<BluetoothSocketConnection> pConnector) { MultiplayerBluetoothExample.this.toast("CLIENT: Connected to server."); } @Override public void onTerminated(final ServerConnector<BluetoothSocketConnection> pConnector) { MultiplayerBluetoothExample.this.toast("CLIENT: Disconnected from Server..."); MultiplayerBluetoothExample.this.finish(); } } private class ExampleServerStateListener implements IBluetoothSocketServerListener<BluetoothSocketConnectionClientConnector> { @Override public void onStarted(final BluetoothSocketServer<BluetoothSocketConnectionClientConnector> pBluetoothSocketServer) { MultiplayerBluetoothExample.this.toast("SERVER: Started."); } @Override public void onTerminated(final BluetoothSocketServer<BluetoothSocketConnectionClientConnector> pBluetoothSocketServer) { MultiplayerBluetoothExample.this.toast("SERVER: Terminated."); } @Override public void onException(final BluetoothSocketServer<BluetoothSocketConnectionClientConnector> pBluetoothSocketServer, final Throwable pThrowable) { Debug.e(pThrowable); MultiplayerBluetoothExample.this.toast("SERVER: Exception: " + pThrowable); } } private class ExampleClientConnectorListener implements IBluetoothSocketConnectionClientConnectorListener { @Override public void onStarted(final ClientConnector<BluetoothSocketConnection> pConnector) { MultiplayerBluetoothExample.this.toast("SERVER: Client connected: " + pConnector.getConnection().getBluetoothSocket().getRemoteDevice().getAddress()); } @Override public void onTerminated(final ClientConnector<BluetoothSocketConnection> pConnector) { MultiplayerBluetoothExample.this.toast("SERVER: Client disconnected: " + pConnector.getConnection().getBluetoothSocket().getRemoteDevice().getAddress()); } } }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.util.GLHelper; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 10:10:10 - 10.10.2010 */ public class Rotation3DExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); this.mCamera.setZClippingPlanes(-100, 100); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* Calculate the coordinates for the face, so its centered on the camera. */ final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; /* Create the face and add it to the scene. */ final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion) { @Override protected void applyRotation(final GL10 pGL) { /* Disable culling so we can see the backside of this sprite. */ GLHelper.disableCulling(pGL); final float rotation = this.mRotation; if(rotation != 0) { final float rotationCenterX = this.mRotationCenterX; final float rotationCenterY = this.mRotationCenterY; pGL.glTranslatef(rotationCenterX, rotationCenterY, 0); /* Note we are applying rotation around the y-axis and not the z-axis anymore! */ pGL.glRotatef(rotation, 0, 1, 0); pGL.glTranslatef(-rotationCenterX, -rotationCenterY, 0); } } @Override protected void drawVertices(final GL10 pGL, final Camera pCamera) { super.drawVertices(pGL, pCamera); /* Enable culling as 'normal' entities profit from culling. */ GLHelper.enableCulling(pGL); } }; face.registerEntityModifier(new LoopEntityModifier(new RotationModifier(6, 0, 360))); scene.attachChild(face); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.MathUtils; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 18:47:08 - 19.03.2010 */ public class BasePhysicsJointExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== protected static final int CAMERA_WIDTH = 720; protected static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private Scene mScene; protected TiledTextureRegion mBoxFaceTextureRegion; protected TiledTextureRegion mCircleFaceTextureRegion; protected PhysicsWorld mPhysicsWorld; private int mFaceCount = 0; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add objects.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new Engine(engineOptions); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mScene.setOnSceneTouchListener(this); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); return this.mScene; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } @Override public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) { final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX(), pAccelerometerData.getY()); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerometerSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerometerSensor(); } // =========================================================== // Methods // =========================================================== private void addFace(final float pX, final float pY) { this.mFaceCount++; Debug.d("Faces: " + this.mFaceCount); final AnimatedSprite face; final Body body; final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); if(this.mFaceCount % 2 == 0) { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); face.setScale(MathUtils.random(0.5f, 1.25f)); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } else { face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion); face.setScale(MathUtils.random(0.5f, 1.25f)); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } face.animate(200); this.mScene.attachChild(face); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.handler.IUpdateHandler; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.ParallelEntityModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.input.touch.controller.MultiTouch; import org.anddev.andengine.extension.input.touch.controller.MultiTouchController; import org.anddev.andengine.extension.input.touch.exception.MultiTouchException; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.MathUtils; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 00:06:23 - 11.07.2010 */ public class CollisionDetectionExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; private boolean mPlaceOnScreenControlsAtDifferentVerticalLocations = false; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); try { if(MultiTouch.isSupported(this)) { engine.setTouchController(new MultiTouchController()); if(MultiTouch.isSupportedDistinct(this)) { Toast.makeText(this, "MultiTouch detected --> Both controls will work properly!", Toast.LENGTH_SHORT).show(); } else { this.mPlaceOnScreenControlsAtDifferentVerticalLocations = true; Toast.makeText(this, "MultiTouch detected, but your device has problems distinguishing between fingers.\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } } catch (final MultiTouchException e) { Toast.makeText(this, "Sorry your Android Version does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)\n\nControls are placed at different vertical locations.", Toast.LENGTH_LONG).show(); } return engine; } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final LoopEntityModifier entityModifier = new LoopEntityModifier(new ParallelEntityModifier(new RotationModifier(6, 0, 360), new SequenceEntityModifier(new ScaleModifier(3, 1, 1.5f), new ScaleModifier(3, 1.5f, 1)))); /* Create A spinning rectangle and a line. */ final Rectangle centerRectangle = new Rectangle(centerX - 50, centerY - 16, 32, 32); centerRectangle.registerEntityModifier(entityModifier); scene.attachChild(centerRectangle); final Line line = new Line(centerX + 50 - 16, centerY, centerX + 50 + 16, centerY); line.registerEntityModifier(entityModifier.deepCopy()); scene.attachChild(line); final Sprite face = new Sprite(centerX, centerY + 42, this.mFaceTextureRegion); final PhysicsHandler physicsHandler = new PhysicsHandler(face); face.registerUpdateHandler(physicsHandler); scene.attachChild(face); /* Velocity control (left). */ final int x1 = 0; final int y1 = CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(); final AnalogOnScreenControl velocityOnScreenControl = new AnalogOnScreenControl(x1, y1, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { physicsHandler.setVelocity(pValueX * 100, pValueY * 100); } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); velocityOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); velocityOnScreenControl.getControlBase().setAlpha(0.5f); scene.setChildScene(velocityOnScreenControl); /* Rotation control (right). */ final int y2 = (this.mPlaceOnScreenControlsAtDifferentVerticalLocations) ? 0 : y1; final int x2 = CAMERA_WIDTH - this.mOnScreenControlBaseTextureRegion.getWidth(); final AnalogOnScreenControl rotationOnScreenControl = new AnalogOnScreenControl(x2, y2, this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { if(pValueX == x1 && pValueY == x1) { face.setRotation(x1); } else { face.setRotation(MathUtils.radToDeg((float)Math.atan2(pValueX, -pValueY))); } } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { /* Nothing. */ } }); rotationOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); rotationOnScreenControl.getControlBase().setAlpha(0.5f); velocityOnScreenControl.setChildScene(rotationOnScreenControl); /* The actual collision-checking. */ scene.registerUpdateHandler(new IUpdateHandler() { @Override public void reset() { } @Override public void onUpdate(final float pSecondsElapsed) { if(centerRectangle.collidesWith(face)) { centerRectangle.setColor(1, 0, 0); } else { centerRectangle.setColor(0, 1, 0); } if(line.collidesWith(face)){ line.setColor(1, 0, 0); } else { line.setColor(0, 1, 0); } if(!mCamera.isRectangularShapeVisible(face)) { centerRectangle.setColor(1, 0, 1); } } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.io.IOException; import org.anddev.andengine.audio.sound.Sound; import org.anddev.andengine.audio.sound.SoundFactory; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener; import org.anddev.andengine.entity.scene.Scene.ITouchArea; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.Debug; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 11.06.2010 */ public class SoundExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mTankTextureRegion; private Sound mExplosionSound; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the tank to hear an explosion sound.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera).setNeedsSound(true)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mTankTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "tank.png", 0, 0); SoundFactory.setAssetBasePath("mfx/"); try { this.mExplosionSound = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "explosion.ogg"); } catch (final IOException e) { Debug.e(e); } this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int x = (CAMERA_WIDTH - this.mTankTextureRegion.getWidth()) / 2; final int y = (CAMERA_HEIGHT - this.mTankTextureRegion.getHeight()) / 2; final Sprite tank = new Sprite(x, y, this.mTankTextureRegion); scene.attachChild(tank); scene.registerTouchArea(tank); scene.setOnAreaTouchListener(new IOnAreaTouchListener() { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { SoundExample.this.mExplosionSound.play(); } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.launcher; import org.anddev.andengine.examples.R; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.TextView; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:43:54 - 16.06.2010 */ class ExpandableExampleLauncherListAdapter extends BaseExpandableListAdapter { // =========================================================== // Constants // =========================================================== private static final ExampleGroup[] EXAMPLEGROUPS = { ExampleGroup.SIMPLE, ExampleGroup.MODIFIER_AND_ANIMATION, ExampleGroup.TOUCH, ExampleGroup.PARTICLESYSTEM, ExampleGroup.MULTIPLAYER, ExampleGroup.PHYSICS, ExampleGroup.TEXT, ExampleGroup.AUDIO, ExampleGroup.ADVANCED, ExampleGroup.BACKGROUND, ExampleGroup.OTHER, ExampleGroup.APP, ExampleGroup.GAME, ExampleGroup.BENCHMARK }; // =========================================================== // Fields // =========================================================== private final Context mContext; // =========================================================== // Constructors // =========================================================== public ExpandableExampleLauncherListAdapter(final Context pContext) { this.mContext = pContext; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Example getChild(final int pGroupPosition, final int pChildPosition) { return EXAMPLEGROUPS[pGroupPosition].mExamples[pChildPosition]; } @Override public long getChildId(final int pGroupPosition, final int pChildPosition) { return pChildPosition; } @Override public int getChildrenCount(final int pGroupPosition) { return EXAMPLEGROUPS[pGroupPosition].mExamples.length; } @Override public View getChildView(final int pGroupPosition, final int pChildPosition, final boolean pIsLastChild, final View pConvertView, final ViewGroup pParent) { final View childView; if (pConvertView != null){ childView = pConvertView; }else{ childView = LayoutInflater.from(this.mContext).inflate(R.layout.listrow_example, null); } ((TextView)childView.findViewById(R.id.tv_listrow_example_name)).setText(this.getChild(pGroupPosition, pChildPosition).NAMERESID); return childView; } @Override public View getGroupView(final int pGroupPosition, final boolean pIsExpanded, final View pConvertView, final ViewGroup pParent) { final View groupView; if (pConvertView != null){ groupView = pConvertView; }else{ groupView = LayoutInflater.from(this.mContext).inflate(R.layout.listrow_examplegroup, null); } ((TextView)groupView.findViewById(R.id.tv_listrow_examplegroup_name)).setText(this.getGroup(pGroupPosition).mNameResourceID); return groupView; } @Override public ExampleGroup getGroup(final int pGroupPosition) { return EXAMPLEGROUPS[pGroupPosition]; } @Override public int getGroupCount() { return EXAMPLEGROUPS.length; } @Override public long getGroupId(final int pGroupPosition) { return pGroupPosition; } @Override public boolean isChildSelectable(final int pGroupPosition, final int pChildPosition) { return true; } @Override public boolean hasStableIds() { return true; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.launcher; import org.anddev.andengine.examples.R; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:13:34 - 27.06.2010 */ public enum ExampleGroup { // =========================================================== // Elements // =========================================================== SIMPLE(R.string.examplegroup_simple, Example.LINE, Example.RECTANGLE, Example.SPRITE, Example.SPRITEREMOVE, Example.SPRITEBATCH), MODIFIER_AND_ANIMATION(R.string.examplegroup_modifier_and_animation, Example.MOVINGBALL, Example.ENTITYMODIFIER, Example.ENTITYMODIFIERIRREGULAR, Example.PATHMODIFIER, Example.ANIMATEDSPRITES, Example.EASEFUNCTION, Example.ROTATION3D ), TOUCH(R.string.examplegroup_touch, Example.TOUCHDRAG, Example.MULTITOUCH, Example.ANALOGONSCREENCONTROL, Example.DIGITALONSCREENCONTROL, Example.ANALOGONSCREENCONTROLS, Example.COORDINATECONVERSION, Example.PINCHZOOM), PARTICLESYSTEM(R.string.examplegroup_particlesystems, Example.PARTICLESYSTEMSIMPLE, Example.PARTICLESYSTEMCOOL, Example.PARTICLESYSTEMNEXUS), MULTIPLAYER(R.string.examplegroup_multiplayer, Example.MULTIPLAYER, Example.MULTIPLAYERSERVERDISCOVERY, Example.MULTIPLAYERBLUETOOTH), PHYSICS(R.string.examplegroup_physics, Example.COLLISIONDETECTION, Example.PHYSICS, Example.PHYSICSFIXEDSTEP, Example.PHYSICSCOLLISIONFILTERING, Example.PHYSICSJUMP, Example.PHYSICSREVOLUTEJOINT, Example.PHYSICSMOUSEJOINT, Example.PHYSICSREMOVE), TEXT(R.string.examplegroup_text, Example.TEXT, Example.TICKERTEXT, Example.CHANGEABLETEXT, Example.CUSTOMFONT, Example.STROKEFONT), AUDIO(R.string.examplegroup_audio, Example.SOUND, Example.MUSIC, Example.MODPLAYER), ADVANCED(R.string.examplegroup_advanced, Example.SPLITSCREEN, Example.BOUNDCAMERA ), // Example.AUGMENTEDREALITY, Example.AUGMENTEDREALITYHORIZON), BACKGROUND(R.string.examplegroup_background, Example.REPEATINGSPRITEBACKGROUND, Example.AUTOPARALLAXBACKGROUND, Example.TMXTILEDMAP), OTHER(R.string.examplegroup_other, Example.SCREENCAPTURE, Example.PAUSE, Example.MENU, Example.SUBMENU, Example.TEXTMENU, Example.ZOOM , Example.IMAGEFORMATS, Example.PVRTEXTURE, Example.PVRCCZTEXTURE, Example.PVRGZTEXTURE, Example.ETC1TEXTURE, Example.TEXTUREOPTIONS, Example.TEXTUREPACKER, Example.COLORKEYTEXTURESOURCEDECORATOR, Example.LOADTEXTURE, Example.UPDATETEXTURE, Example.RUNNABLEPOOLUPDATEHANDLER, Example.SVGTEXTUREREGION, Example.XMLLAYOUT, Example.LEVELLOADER), APP(R.string.examplegroup_app, Example.APP_CITYRADAR), GAME(R.string.examplegroup_game, Example.GAME_PONG, Example.GAME_SNAKE, Example.GAME_RACER), BENCHMARK(R.string.examplegroup_benchmark, Example.BENCHMARK_SPRITE, Example.BENCHMARK_ENTITYMODIFIER, Example.BENCHMARK_ANIMATION, Example.BENCHMARK_TICKERTEXT, Example.BENCHMARK_PARTICLESYSTEM, Example.BENCHMARK_PHYSICS); // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public final Example[] mExamples; public final int mNameResourceID; // =========================================================== // Constructors // =========================================================== private ExampleGroup(final int pNameResourceID, final Example ... pExamples) { this.mNameResourceID = pNameResourceID; this.mExamples = pExamples; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.launcher; import java.util.Arrays; import org.anddev.andengine.examples.R; import org.anddev.andengine.util.Debug; import android.app.AlertDialog; import android.app.Dialog; import android.app.ExpandableListActivity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ExpandableListView; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:56:46 - 16.06.2010 */ public class ExampleLauncher extends ExpandableListActivity { // =========================================================== // Constants // =========================================================== private static final String PREF_LAST_APP_LAUNCH_VERSIONCODE_ID = "last.app.launch.versioncode"; private static final int DIALOG_FIRST_APP_LAUNCH = 0; private static final int DIALOG_NEW_IN_THIS_VERSION = DIALOG_FIRST_APP_LAUNCH + 1; private static final int DIALOG_BENCHMARKS_SUBMIT_PLEASE = DIALOG_NEW_IN_THIS_VERSION + 1; // =========================================================== // Fields // =========================================================== private ExpandableExampleLauncherListAdapter mExpandableExampleLauncherListAdapter; private int mVersionCodeCurrent; private int mVersionCodeLastLaunch; // =========================================================== // Constructors // =========================================================== @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.list_examples); this.mExpandableExampleLauncherListAdapter = new ExpandableExampleLauncherListAdapter(this); this.setListAdapter(this.mExpandableExampleLauncherListAdapter); this.findViewById(R.id.btn_get_involved).setOnClickListener(new OnClickListener() { @Override public void onClick(final View pView) { ExampleLauncher.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.andengine.org"))); } }); final SharedPreferences prefs = this.getPreferences(Context.MODE_PRIVATE); this.mVersionCodeCurrent = this.getVersionCode(); this.mVersionCodeLastLaunch = prefs.getInt(PREF_LAST_APP_LAUNCH_VERSIONCODE_ID, -1); if(this.isFirstTime("first.app.launch")) { this.showDialog(DIALOG_FIRST_APP_LAUNCH); } else if(this.mVersionCodeLastLaunch != -1 && this.mVersionCodeLastLaunch < this.mVersionCodeCurrent){ this.showDialog(DIALOG_NEW_IN_THIS_VERSION); } else if(isFirstTime("please.submit.benchmarks")){ this.showDialog(DIALOG_BENCHMARKS_SUBMIT_PLEASE); } prefs.edit().putInt(PREF_LAST_APP_LAUNCH_VERSIONCODE_ID, this.mVersionCodeCurrent).commit(); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected Dialog onCreateDialog(final int pId) { switch(pId) { case DIALOG_FIRST_APP_LAUNCH: return new AlertDialog.Builder(this) .setTitle(R.string.dialog_first_app_launch_title) .setMessage(R.string.dialog_first_app_launch_message) .setIcon(android.R.drawable.ic_dialog_info) .setPositiveButton(android.R.string.ok, null) .create(); case DIALOG_BENCHMARKS_SUBMIT_PLEASE: return new AlertDialog.Builder(this) .setTitle(R.string.dialog_benchmarks_submit_please_title) .setMessage(R.string.dialog_benchmarks_submit_please_message) .setIcon(android.R.drawable.ic_dialog_info) .setPositiveButton(android.R.string.ok, null) .create(); case DIALOG_NEW_IN_THIS_VERSION: final int[] versionCodes = this.getResources().getIntArray(R.array.new_in_version_versioncode); final int versionDescriptionsStartIndex = Math.max(0, Arrays.binarySearch(versionCodes, this.mVersionCodeLastLaunch) + 1); final String[] versionDescriptions = this.getResources().getStringArray(R.array.new_in_version_changes); final StringBuilder sb = new StringBuilder(); for(int i = versionDescriptions.length - 1; i >= versionDescriptionsStartIndex; i--) { sb.append("--------------------------\n"); sb.append(">>> Version: " + versionCodes[i] + "\n"); sb.append("--------------------------\n"); sb.append(versionDescriptions[i]); if(i > versionDescriptionsStartIndex){ sb.append("\n\n"); } } return new AlertDialog.Builder(this) .setTitle(R.string.dialog_new_in_this_version_title) .setMessage(sb.toString()) .setIcon(android.R.drawable.ic_dialog_info) .setPositiveButton(android.R.string.ok, null) .create(); default: return super.onCreateDialog(pId); } } @Override public void onGroupExpand(int pGroupPosition) { switch(this.mExpandableExampleLauncherListAdapter.getGroup(pGroupPosition)){ case BENCHMARK: Toast.makeText(this, "When running a benchmark, a dialog with the results will appear after some seconds.", Toast.LENGTH_SHORT).show(); } super.onGroupExpand(pGroupPosition); } @Override public boolean onChildClick(final ExpandableListView pParent, final View pV, final int pGroupPosition, final int pChildPosition, final long pId) { final Example example = this.mExpandableExampleLauncherListAdapter.getChild(pGroupPosition, pChildPosition); this.startActivity(new Intent(this, example.CLASS)); return super.onChildClick(pParent, pV, pGroupPosition, pChildPosition, pId); } // =========================================================== // Methods // =========================================================== public boolean isFirstTime(final String pKey){ final SharedPreferences prefs = this.getPreferences(Context.MODE_PRIVATE); if(prefs.getBoolean(pKey, true)){ prefs.edit().putBoolean(pKey, false).commit(); return true; } return false; } public int getVersionCode() { try { final PackageInfo pi = this.getPackageManager().getPackageInfo(this.getPackageName(), 0); return pi.versionCode; } catch (final PackageManager.NameNotFoundException e) { Debug.e("Package name not found", e); return -1; } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.launcher; import org.anddev.andengine.examples.AnalogOnScreenControlExample; import org.anddev.andengine.examples.AnalogOnScreenControlsExample; import org.anddev.andengine.examples.AnimatedSpritesExample; import org.anddev.andengine.examples.AugmentedRealityExample; import org.anddev.andengine.examples.AugmentedRealityHorizonExample; import org.anddev.andengine.examples.AutoParallaxBackgroundExample; import org.anddev.andengine.examples.BoundCameraExample; import org.anddev.andengine.examples.ChangeableTextExample; import org.anddev.andengine.examples.CollisionDetectionExample; import org.anddev.andengine.examples.ColorKeyTextureSourceDecoratorExample; import org.anddev.andengine.examples.CoordinateConversionExample; import org.anddev.andengine.examples.CustomFontExample; import org.anddev.andengine.examples.DigitalOnScreenControlExample; import org.anddev.andengine.examples.ETC1TextureExample; import org.anddev.andengine.examples.EaseFunctionExample; import org.anddev.andengine.examples.EntityModifierExample; import org.anddev.andengine.examples.EntityModifierIrregularExample; import org.anddev.andengine.examples.ImageFormatsExample; import org.anddev.andengine.examples.LevelLoaderExample; import org.anddev.andengine.examples.LineExample; import org.anddev.andengine.examples.LoadTextureExample; import org.anddev.andengine.examples.MenuExample; import org.anddev.andengine.examples.ModPlayerExample; import org.anddev.andengine.examples.MovingBallExample; import org.anddev.andengine.examples.MultiTouchExample; import org.anddev.andengine.examples.MultiplayerBluetoothExample; import org.anddev.andengine.examples.MultiplayerExample; import org.anddev.andengine.examples.MultiplayerServerDiscoveryExample; import org.anddev.andengine.examples.MusicExample; import org.anddev.andengine.examples.PVRCCZTextureExample; import org.anddev.andengine.examples.PVRGZTextureExample; import org.anddev.andengine.examples.PVRTextureExample; import org.anddev.andengine.examples.ParticleSystemCoolExample; import org.anddev.andengine.examples.ParticleSystemNexusExample; import org.anddev.andengine.examples.ParticleSystemSimpleExample; import org.anddev.andengine.examples.PathModifierExample; import org.anddev.andengine.examples.PauseExample; import org.anddev.andengine.examples.PhysicsCollisionFilteringExample; import org.anddev.andengine.examples.PhysicsExample; import org.anddev.andengine.examples.PhysicsFixedStepExample; import org.anddev.andengine.examples.PhysicsJumpExample; import org.anddev.andengine.examples.PhysicsMouseJointExample; import org.anddev.andengine.examples.PhysicsRemoveExample; import org.anddev.andengine.examples.PhysicsRevoluteJointExample; import org.anddev.andengine.examples.PinchZoomExample; import org.anddev.andengine.examples.R; import org.anddev.andengine.examples.RectangleExample; import org.anddev.andengine.examples.RepeatingSpriteBackgroundExample; import org.anddev.andengine.examples.Rotation3DExample; import org.anddev.andengine.examples.RunnablePoolUpdateHandlerExample; import org.anddev.andengine.examples.SVGTextureRegionExample; import org.anddev.andengine.examples.ScreenCaptureExample; import org.anddev.andengine.examples.SoundExample; import org.anddev.andengine.examples.SplitScreenExample; import org.anddev.andengine.examples.SpriteBatchExample; import org.anddev.andengine.examples.SpriteExample; import org.anddev.andengine.examples.SpriteRemoveExample; import org.anddev.andengine.examples.StrokeFontExample; import org.anddev.andengine.examples.SubMenuExample; import org.anddev.andengine.examples.TMXTiledMapExample; import org.anddev.andengine.examples.TextExample; import org.anddev.andengine.examples.TextMenuExample; import org.anddev.andengine.examples.TextureOptionsExample; import org.anddev.andengine.examples.TexturePackerExample; import org.anddev.andengine.examples.TickerTextExample; import org.anddev.andengine.examples.TouchDragExample; import org.anddev.andengine.examples.UnloadResourcesExample; import org.anddev.andengine.examples.UpdateTextureExample; import org.anddev.andengine.examples.XMLLayoutExample; import org.anddev.andengine.examples.ZoomExample; import org.anddev.andengine.examples.app.cityradar.CityRadarActivity; import org.anddev.andengine.examples.benchmark.AnimationBenchmark; import org.anddev.andengine.examples.benchmark.EntityModifierBenchmark; import org.anddev.andengine.examples.benchmark.ParticleSystemBenchmark; import org.anddev.andengine.examples.benchmark.PhysicsBenchmark; import org.anddev.andengine.examples.benchmark.SpriteBenchmark; import org.anddev.andengine.examples.benchmark.TickerTextBenchmark; import org.anddev.andengine.examples.game.pong.PongGameActivity; import org.anddev.andengine.examples.game.racer.RacerGameActivity; import org.anddev.andengine.examples.game.snake.SnakeGameActivity; import org.anddev.andengine.ui.activity.BaseGameActivity; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 20:42:27 - 16.06.2010 */ enum Example { // =========================================================== // Elements // =========================================================== ANALOGONSCREENCONTROL(AnalogOnScreenControlExample.class, R.string.example_analogonscreencontrol), ANALOGONSCREENCONTROLS(AnalogOnScreenControlsExample.class, R.string.example_analogonscreencontrols), ANIMATEDSPRITES(AnimatedSpritesExample.class, R.string.example_animatedsprites), AUGMENTEDREALITY(AugmentedRealityExample.class, R.string.example_augmentedreality), AUGMENTEDREALITYHORIZON(AugmentedRealityHorizonExample.class, R.string.example_augmentedrealityhorizon), AUTOPARALLAXBACKGROUND(AutoParallaxBackgroundExample.class, R.string.example_autoparallaxbackground), BOUNDCAMERA(BoundCameraExample.class, R.string.example_boundcamera), CHANGEABLETEXT(ChangeableTextExample.class, R.string.example_changeabletext), COLLISIONDETECTION(CollisionDetectionExample.class, R.string.example_collisiondetection), COLORKEYTEXTURESOURCEDECORATOR(ColorKeyTextureSourceDecoratorExample.class, R.string.example_colorkeytexturesourcedecorator), COORDINATECONVERSION(CoordinateConversionExample.class, R.string.example_coordinateconversion), CUSTOMFONT(CustomFontExample.class, R.string.example_customfont), DIGITALONSCREENCONTROL(DigitalOnScreenControlExample.class, R.string.example_digitalonscreencontrol), EASEFUNCTION(EaseFunctionExample.class, R.string.example_easefunction), ENTITYMODIFIER(EntityModifierExample.class, R.string.example_entitymodifier), ENTITYMODIFIERIRREGULAR(EntityModifierIrregularExample.class, R.string.example_entitymodifierirregular), ETC1TEXTURE(ETC1TextureExample.class, R.string.example_etc1texture), IMAGEFORMATS(ImageFormatsExample.class, R.string.example_imageformats), LEVELLOADER(LevelLoaderExample.class, R.string.example_levelloader), LINE(LineExample.class, R.string.example_line), LOADTEXTURE(LoadTextureExample.class, R.string.example_loadtexture), MENU(MenuExample.class, R.string.example_menu), MODPLAYER(ModPlayerExample.class, R.string.example_modplayer), MOVINGBALL(MovingBallExample.class, R.string.example_movingball), MULTIPLAYER(MultiplayerExample.class, R.string.example_multiplayer), MULTIPLAYERSERVERDISCOVERY(MultiplayerServerDiscoveryExample.class, R.string.example_multiplayerserverdiscovery), MULTIPLAYERBLUETOOTH(MultiplayerBluetoothExample.class, R.string.example_multiplayerbluetooth), MULTITOUCH(MultiTouchExample.class, R.string.example_multitouch), MUSIC(MusicExample.class, R.string.example_music), PAUSE(PauseExample.class, R.string.example_pause), PATHMODIFIER(PathModifierExample.class, R.string.example_pathmodifier), PARTICLESYSTEMNEXUS(ParticleSystemNexusExample.class, R.string.example_particlesystemnexus), PARTICLESYSTEMCOOL(ParticleSystemCoolExample.class, R.string.example_particlesystemcool), PARTICLESYSTEMSIMPLE(ParticleSystemSimpleExample.class, R.string.example_particlesystemsimple), PHYSICSCOLLISIONFILTERING(PhysicsCollisionFilteringExample.class, R.string.example_physicscollisionfiltering), PHYSICS(PhysicsExample.class, R.string.example_physics), PHYSICSFIXEDSTEP(PhysicsFixedStepExample.class, R.string.example_physicsfixedstep), PHYSICSMOUSEJOINT(PhysicsMouseJointExample.class, R.string.example_physicsmousejoint), PHYSICSJUMP(PhysicsJumpExample.class, R.string.example_physicsjump), PHYSICSREVOLUTEJOINT(PhysicsRevoluteJointExample.class, R.string.example_physicsrevolutejoint), PHYSICSREMOVE(PhysicsRemoveExample.class, R.string.example_physicsremove), PINCHZOOM(PinchZoomExample.class, R.string.example_pinchzoom), PVRCCZTEXTURE(PVRCCZTextureExample.class, R.string.example_pvrccztexture), PVRGZTEXTURE(PVRGZTextureExample.class, R.string.example_pvrgztexture), PVRTEXTURE(PVRTextureExample.class, R.string.example_pvrtexture), RECTANGLE(RectangleExample.class, R.string.example_rectangle), REPEATINGSPRITEBACKGROUND(RepeatingSpriteBackgroundExample.class, R.string.example_repeatingspritebackground), ROTATION3D(Rotation3DExample.class, R.string.example_rotation3d), RUNNABLEPOOLUPDATEHANDLER(RunnablePoolUpdateHandlerExample.class, R.string.example_runnablepoolupdatehandler), SCREENCAPTURE(ScreenCaptureExample.class, R.string.example_screencapture), SOUND(SoundExample.class, R.string.example_sound), SPLITSCREEN(SplitScreenExample.class, R.string.example_splitscreen), SPRITEBATCH(SpriteBatchExample.class, R.string.example_spritebatch), SPRITE(SpriteExample.class, R.string.example_sprite), SPRITEREMOVE(SpriteRemoveExample.class, R.string.example_spriteremove), STROKEFONT(StrokeFontExample.class, R.string.example_strokefont), SUBMENU(SubMenuExample.class, R.string.example_submenu), SVGTEXTUREREGION(SVGTextureRegionExample.class, R.string.example_svgtextureregion), TEXT(TextExample.class, R.string.example_text), TEXTMENU(TextMenuExample.class, R.string.example_textmenu), TEXTUREOPTIONS(TextureOptionsExample.class, R.string.example_textureoptions), TEXTUREPACKER(TexturePackerExample.class, R.string.example_texturepacker), TMXTILEDMAP(TMXTiledMapExample.class, R.string.example_tmxtiledmap), TICKERTEXT(TickerTextExample.class, R.string.example_tickertext), TOUCHDRAG(TouchDragExample.class, R.string.example_touchdrag), UNLOADRESOURCES(UnloadResourcesExample.class, R.string.example_unloadresources), UPDATETEXTURE(UpdateTextureExample.class, R.string.example_updatetexture), XMLLAYOUT(XMLLayoutExample.class, R.string.example_xmllayout), ZOOM(ZoomExample.class, R.string.example_zoom), BENCHMARK_ANIMATION(AnimationBenchmark.class, R.string.example_benchmark_animation), BENCHMARK_PARTICLESYSTEM(ParticleSystemBenchmark.class, R.string.example_benchmark_particlesystem), BENCHMARK_PHYSICS(PhysicsBenchmark.class, R.string.example_benchmark_physics), BENCHMARK_ENTITYMODIFIER(EntityModifierBenchmark.class, R.string.example_benchmark_entitymodifier), BENCHMARK_SPRITE(SpriteBenchmark.class, R.string.example_benchmark_sprite), BENCHMARK_TICKERTEXT(TickerTextBenchmark.class, R.string.example_benchmark_tickertext), APP_CITYRADAR(CityRadarActivity.class, R.string.example_app_cityradar), GAME_PONG(PongGameActivity.class, R.string.example_game_pong), GAME_SNAKE(SnakeGameActivity.class, R.string.example_game_snake), GAME_RACER(RacerGameActivity.class, R.string.example_game_racer); // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public final Class<? extends BaseGameActivity> CLASS; public final int NAMERESID; // =========================================================== // Constructors // =========================================================== private Example(final Class<? extends BaseGameActivity> pExampleClass, final int pNameResID) { this.CLASS = pExampleClass; this.NAMERESID = pNameResID; } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.MoveModifier; import org.anddev.andengine.entity.scene.CameraScene; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.view.KeyEvent; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:33:33 - 01.04.2010 */ public class PauseExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private Scene mMainScene; private TextureRegion mFaceTextureRegion; private TextureRegion mPausedTextureRegion; private CameraScene mPauseScene; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mPausedTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "paused.png", 0, 0); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box_menu.png", 0, 50); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mPauseScene = new CameraScene(this.mCamera); /* Make the 'PAUSED'-label centered on the camera. */ final int x = CAMERA_WIDTH / 2 - this.mPausedTextureRegion.getWidth() / 2; final int y = CAMERA_HEIGHT / 2 - this.mPausedTextureRegion.getHeight() / 2; final Sprite pausedSprite = new Sprite(x, y, this.mPausedTextureRegion); this.mPauseScene.attachChild(pausedSprite); /* Makes the paused Game look through. */ this.mPauseScene.setBackgroundEnabled(false); /* Just a simple */ this.mMainScene = new Scene(); this.mMainScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final Sprite face = new Sprite(0, 0, this.mFaceTextureRegion); face.registerEntityModifier(new MoveModifier(30, 0, CAMERA_WIDTH - face.getWidth(), 0, CAMERA_HEIGHT - face.getHeight())); this.mMainScene.attachChild(face); return this.mMainScene; } @Override public void onLoadComplete() { } @Override public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) { if(pKeyCode == KeyEvent.KEYCODE_MENU && pEvent.getAction() == KeyEvent.ACTION_DOWN) { if(this.mEngine.isRunning()) { this.mMainScene.setChildScene(this.mPauseScene, false, true, true); this.mEngine.stop(); } else { this.mMainScene.clearChildScene(); this.mEngine.start(); } return true; } else { return super.onKeyDown(pKeyCode, pEvent); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.spritesheets; public interface TexturePackerExampleSpritesheet { public static final int FACE_BOX_ID = 0; public static final int FACE_CIRCLE_TILED_ID = 1; public static final int FACE_HEXAGON_TILED_ID = 2; public static final int FACE_TRIANGLE_TILED_ID = 3; }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.HUD; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.MoveModifier; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.text.ChangeableText; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.modifier.ease.EaseBackIn; import org.anddev.andengine.util.modifier.ease.EaseBackInOut; import org.anddev.andengine.util.modifier.ease.EaseBackOut; import org.anddev.andengine.util.modifier.ease.EaseBounceIn; import org.anddev.andengine.util.modifier.ease.EaseBounceInOut; import org.anddev.andengine.util.modifier.ease.EaseBounceOut; import org.anddev.andengine.util.modifier.ease.EaseCircularIn; import org.anddev.andengine.util.modifier.ease.EaseCircularInOut; import org.anddev.andengine.util.modifier.ease.EaseCircularOut; import org.anddev.andengine.util.modifier.ease.EaseCubicIn; import org.anddev.andengine.util.modifier.ease.EaseCubicInOut; import org.anddev.andengine.util.modifier.ease.EaseCubicOut; import org.anddev.andengine.util.modifier.ease.EaseElasticIn; import org.anddev.andengine.util.modifier.ease.EaseElasticInOut; import org.anddev.andengine.util.modifier.ease.EaseElasticOut; import org.anddev.andengine.util.modifier.ease.EaseExponentialIn; import org.anddev.andengine.util.modifier.ease.EaseExponentialInOut; import org.anddev.andengine.util.modifier.ease.EaseExponentialOut; import org.anddev.andengine.util.modifier.ease.EaseLinear; import org.anddev.andengine.util.modifier.ease.EaseQuadIn; import org.anddev.andengine.util.modifier.ease.EaseQuadInOut; import org.anddev.andengine.util.modifier.ease.EaseQuadOut; import org.anddev.andengine.util.modifier.ease.EaseQuartIn; import org.anddev.andengine.util.modifier.ease.EaseQuartInOut; import org.anddev.andengine.util.modifier.ease.EaseQuartOut; import org.anddev.andengine.util.modifier.ease.EaseQuintIn; import org.anddev.andengine.util.modifier.ease.EaseQuintInOut; import org.anddev.andengine.util.modifier.ease.EaseQuintOut; import org.anddev.andengine.util.modifier.ease.EaseSineIn; import org.anddev.andengine.util.modifier.ease.EaseSineInOut; import org.anddev.andengine.util.modifier.ease.EaseSineOut; import org.anddev.andengine.util.modifier.ease.EaseStrongIn; import org.anddev.andengine.util.modifier.ease.EaseStrongInOut; import org.anddev.andengine.util.modifier.ease.EaseStrongOut; import org.anddev.andengine.util.modifier.ease.IEaseFunction; import android.graphics.Color; import android.graphics.Typeface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 15:12:16 - 30.07.2010 */ public class EaseFunctionExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mFontTexture; private Font mFont; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mBadgeTextureRegion; private TextureRegion mNextTextureRegion; private static final IEaseFunction[][] EASEFUNCTIONS = new IEaseFunction[][]{ new IEaseFunction[] { EaseLinear.getInstance(), EaseLinear.getInstance(), EaseLinear.getInstance() }, new IEaseFunction[] { EaseBackIn.getInstance(), EaseBackOut.getInstance(), EaseBackInOut.getInstance() }, new IEaseFunction[] { EaseBounceIn.getInstance(), EaseBounceOut.getInstance(), EaseBounceInOut.getInstance() }, new IEaseFunction[] { EaseCircularIn.getInstance(), EaseCircularOut.getInstance(), EaseCircularInOut.getInstance() }, new IEaseFunction[] { EaseCubicIn.getInstance(), EaseCubicOut.getInstance(), EaseCubicInOut.getInstance() }, new IEaseFunction[] { EaseElasticIn.getInstance(), EaseElasticOut.getInstance(), EaseElasticInOut.getInstance() }, new IEaseFunction[] { EaseExponentialIn.getInstance(), EaseExponentialOut.getInstance(), EaseExponentialInOut.getInstance() }, new IEaseFunction[] { EaseQuadIn.getInstance(), EaseQuadOut.getInstance(), EaseQuadInOut.getInstance() }, new IEaseFunction[] { EaseQuartIn.getInstance(), EaseQuartOut.getInstance(), EaseQuartInOut.getInstance() }, new IEaseFunction[] { EaseQuintIn.getInstance(), EaseQuintOut.getInstance(), EaseQuintInOut.getInstance() }, new IEaseFunction[] { EaseSineIn.getInstance(), EaseSineOut.getInstance(), EaseSineInOut.getInstance() }, new IEaseFunction[] { EaseStrongIn.getInstance(), EaseStrongOut.getInstance(), EaseStrongInOut.getInstance() } }; private int mCurrentEaseFunctionSet = 0; private final Sprite[] mBadges = new Sprite[3]; private final ChangeableText[] mEaseFunctionNameTexts = new ChangeableText[3]; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { /* The font. */ this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 32, true, Color.WHITE); this.mEngine.getTextureManager().loadTexture(this.mFontTexture); this.getFontManager().loadFont(this.mFont); /* The textures. */ BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mNextTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "next.png", 0, 0); this.mBadgeTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "badge.png", 97, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final HUD hud = new HUD(); final Sprite nextSprite = new Sprite(CAMERA_WIDTH - 100 - this.mNextTextureRegion.getWidth(), 0, this.mNextTextureRegion){ @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { EaseFunctionExample.this.next(); } return true; }; }; final Sprite previousSprite = new Sprite(100, 0, this.mNextTextureRegion.deepCopy()){ @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { EaseFunctionExample.this.previous(); } return true; }; }; previousSprite.getTextureRegion().setFlippedHorizontal(true); hud.attachChild(nextSprite); hud.attachChild(previousSprite); hud.registerTouchArea(nextSprite); hud.registerTouchArea(previousSprite); this.mCamera.setHUD(hud); /* Create the sprites that will be moving. */ this.mBadges[0] = new Sprite(0, CAMERA_HEIGHT - 300, this.mBadgeTextureRegion); this.mBadges[1] = new Sprite(0, CAMERA_HEIGHT - 200, this.mBadgeTextureRegion); this.mBadges[2] = new Sprite(0, CAMERA_HEIGHT - 100, this.mBadgeTextureRegion); this.mEaseFunctionNameTexts[0] = new ChangeableText(0, CAMERA_HEIGHT - 250, this.mFont, "Function", 20); this.mEaseFunctionNameTexts[1] = new ChangeableText(0, CAMERA_HEIGHT - 150, this.mFont, "Function", 20); this.mEaseFunctionNameTexts[2] = new ChangeableText(0, CAMERA_HEIGHT - 50, this.mFont, "Function", 20); scene.attachChild(this.mBadges[0]); scene.attachChild(this.mBadges[1]); scene.attachChild(this.mBadges[2]); scene.attachChild(this.mEaseFunctionNameTexts[0]); scene.attachChild(this.mEaseFunctionNameTexts[1]); scene.attachChild(this.mEaseFunctionNameTexts[2]); scene.attachChild(new Line(0, CAMERA_HEIGHT - 110, CAMERA_WIDTH, CAMERA_HEIGHT - 110)); scene.attachChild(new Line(0, CAMERA_HEIGHT - 210, CAMERA_WIDTH, CAMERA_HEIGHT - 210)); scene.attachChild(new Line(0, CAMERA_HEIGHT - 310, CAMERA_WIDTH, CAMERA_HEIGHT - 310)); return scene; } @Override public void onLoadComplete() { this.reanimate(); } // =========================================================== // Methods // =========================================================== public void next() { this.mCurrentEaseFunctionSet++; this.mCurrentEaseFunctionSet %= EASEFUNCTIONS.length; this.reanimate(); } public void previous() { this.mCurrentEaseFunctionSet--; if(this.mCurrentEaseFunctionSet < 0) { this.mCurrentEaseFunctionSet += EASEFUNCTIONS.length; } this.reanimate(); } private void reanimate() { this.runOnUpdateThread(new Runnable() { @Override public void run() { final IEaseFunction[] currentEaseFunctionsSet = EASEFUNCTIONS[EaseFunctionExample.this.mCurrentEaseFunctionSet]; final ChangeableText[] easeFunctionNameTexts = EaseFunctionExample.this.mEaseFunctionNameTexts; final Sprite[] faces = EaseFunctionExample.this.mBadges; for(int i = 0; i < 3; i++) { easeFunctionNameTexts[i].setText(currentEaseFunctionsSet[i].getClass().getSimpleName()); final Sprite face = faces[i]; face.clearEntityModifiers(); final float y = face.getY(); face.setPosition(0, y); face.registerEntityModifier(new MoveModifier(3, 0, CAMERA_WIDTH - face.getWidth(), y, y, currentEaseFunctionsSet[i])); } } }); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.io.IOException; import java.io.InputStream; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.SmoothCamera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.ZoomState; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.ITexture; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.compressed.pvr.PVRGZTexture; import org.anddev.andengine.opengl.texture.compressed.pvr.PVRTexture.PVRTextureFormat; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TextureRegionFactory; import org.anddev.andengine.util.Debug; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 13:54:51 - 13.07.2011 */ public class PVRGZTextureExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private SmoothCamera mSmoothCamera; private ITexture mTexture; private TextureRegion mHouseTextureRegion; private ZoomState mZoomState = ZoomState.NONE; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Click the top half of the screen to zoom in or the bottom half to zoom out!", Toast.LENGTH_LONG); this.mSmoothCamera = new SmoothCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, 0, 0, 0.1f) { @Override public void onUpdate(final float pSecondsElapsed) { switch (PVRGZTextureExample.this.mZoomState) { case IN: this.setZoomFactor(this.getZoomFactor() + 0.1f * pSecondsElapsed); break; case OUT: this.setZoomFactor(this.getZoomFactor() - 0.1f * pSecondsElapsed); break; } super.onUpdate(pSecondsElapsed); } }; return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mSmoothCamera)); } @Override public void onLoadResources() { try { this.mTexture = new PVRGZTexture(PVRTextureFormat.RGBA_8888, TextureOptions.BILINEAR) { @Override protected InputStream onGetInputStream() throws IOException { return PVRGZTextureExample.this.getResources().openRawResource(R.raw.house_pvrgz_argb_8888); } }; this.mHouseTextureRegion = TextureRegionFactory.extractFromTexture(this.mTexture, 0, 0, 512, 512, true); this.mEngine.getTextureManager().loadTextures(this.mTexture); } catch (final Throwable e) { Debug.e(e); } } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mHouseTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mHouseTextureRegion.getHeight()) / 2; scene.attachChild(new Sprite(centerX, centerY, this.mHouseTextureRegion)); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if (pSceneTouchEvent.isActionDown() || pSceneTouchEvent.isActionMove()) { if(pSceneTouchEvent.getY() < CAMERA_HEIGHT / 2) { PVRGZTextureExample.this.mZoomState = ZoomState.IN; } else { PVRGZTextureExample.this.mZoomState = ZoomState.OUT; } } else { PVRGZTextureExample.this.mZoomState = ZoomState.NONE; } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.Scene.ITouchArea; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.messages.client.ClientMessageFlags; import org.anddev.andengine.examples.adt.messages.server.ConnectionCloseServerMessage; import org.anddev.andengine.examples.adt.messages.server.ServerMessageFlags; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.IMessage; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.IServerMessage; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; import org.anddev.andengine.extension.multiplayer.protocol.client.IServerMessageHandler; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.ServerConnector; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.SocketConnectionServerConnector; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.SocketConnectionServerConnector.ISocketConnectionServerConnectorListener; import org.anddev.andengine.extension.multiplayer.protocol.server.SocketServer; import org.anddev.andengine.extension.multiplayer.protocol.server.SocketServer.ISocketServerListener; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.ClientConnector; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.SocketConnectionClientConnector; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.SocketConnectionClientConnector.ISocketConnectionClientConnectorListener; import org.anddev.andengine.extension.multiplayer.protocol.shared.SocketConnection; import org.anddev.andengine.extension.multiplayer.protocol.util.MessagePool; import org.anddev.andengine.extension.multiplayer.protocol.util.WifiUtils; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.Debug; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.util.SparseArray; import android.view.KeyEvent; import android.widget.EditText; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 17:10:24 - 19.06.2010 */ public class MultiplayerExample extends BaseExample implements ClientMessageFlags, ServerMessageFlags { // =========================================================== // Constants // =========================================================== private static final String LOCALHOST_IP = "127.0.0.1"; private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int SERVER_PORT = 4444; private static final short FLAG_MESSAGE_SERVER_ADD_FACE = 1; private static final short FLAG_MESSAGE_SERVER_MOVE_FACE = FLAG_MESSAGE_SERVER_ADD_FACE + 1; private static final int DIALOG_CHOOSE_SERVER_OR_CLIENT_ID = 0; private static final int DIALOG_ENTER_SERVER_IP_ID = DIALOG_CHOOSE_SERVER_OR_CLIENT_ID + 1; private static final int DIALOG_SHOW_SERVER_IP_ID = DIALOG_ENTER_SERVER_IP_ID + 1; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private int mFaceIDCounter; private final SparseArray<Sprite> mFaces = new SparseArray<Sprite>(); private String mServerIP = LOCALHOST_IP; private SocketServer<SocketConnectionClientConnector> mSocketServer; private ServerConnector<SocketConnection> mServerConnector; private final MessagePool<IMessage> mMessagePool = new MessagePool<IMessage>(); // =========================================================== // Constructors // =========================================================== public MultiplayerExample() { this.initMessagePool(); } private void initMessagePool() { this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_ADD_FACE, AddFaceServerMessage.class); this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_MOVE_FACE, MoveFaceServerMessage.class); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.showDialog(DIALOG_CHOOSE_SERVER_OR_CLIENT_ID); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* We allow only the server to actively send around messages. */ if(MultiplayerExample.this.mSocketServer != null) { scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pSceneTouchEvent.isActionDown()) { try { final AddFaceServerMessage addFaceServerMessage = (AddFaceServerMessage) MultiplayerExample.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_ADD_FACE); addFaceServerMessage.set(MultiplayerExample.this.mFaceIDCounter++, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); MultiplayerExample.this.mSocketServer.sendBroadcastServerMessage(addFaceServerMessage); MultiplayerExample.this.mMessagePool.recycleMessage(addFaceServerMessage); } catch (final IOException e) { Debug.e(e); } return true; } else { return true; } } }); scene.setOnAreaTouchListener(new IOnAreaTouchListener() { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { try { final Sprite face = (Sprite)pTouchArea; final Integer faceID = (Integer)face.getUserData(); final MoveFaceServerMessage moveFaceServerMessage = (MoveFaceServerMessage) MultiplayerExample.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_MOVE_FACE); moveFaceServerMessage.set(faceID, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); MultiplayerExample.this.mSocketServer.sendBroadcastServerMessage(moveFaceServerMessage); MultiplayerExample.this.mMessagePool.recycleMessage(moveFaceServerMessage); } catch (final IOException e) { Debug.e(e); return false; } return true; } }); scene.setTouchAreaBindingEnabled(true); } return scene; } @Override public void onLoadComplete() { } @Override protected Dialog onCreateDialog(final int pID) { switch(pID) { case DIALOG_SHOW_SERVER_IP_ID: try { return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Your Server-IP ...") .setCancelable(false) .setMessage("The IP of your Server is:\n" + WifiUtils.getWifiIPv4Address(this)) .setPositiveButton(android.R.string.ok, null) .create(); } catch (final UnknownHostException e) { return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Your Server-IP ...") .setCancelable(false) .setMessage("Error retrieving IP of your Server: " + e) .setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerExample.this.finish(); } }) .create(); } case DIALOG_ENTER_SERVER_IP_ID: final EditText ipEditText = new EditText(this); return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Enter Server-IP ...") .setCancelable(false) .setView(ipEditText) .setPositiveButton("Connect", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerExample.this.mServerIP = ipEditText.getText().toString(); MultiplayerExample.this.initClient(); } }) .setNegativeButton(android.R.string.cancel, new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerExample.this.finish(); } }) .create(); case DIALOG_CHOOSE_SERVER_OR_CLIENT_ID: return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Be Server or Client ...") .setCancelable(false) .setPositiveButton("Client", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerExample.this.showDialog(DIALOG_ENTER_SERVER_IP_ID); } }) .setNeutralButton("Server", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerExample.this.toast("You can add and move sprites, which are only shown on the clients."); MultiplayerExample.this.initServer(); MultiplayerExample.this.showDialog(DIALOG_SHOW_SERVER_IP_ID); } }) .setNegativeButton("Both", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerExample.this.toast("You can add sprites and move them, by dragging them."); MultiplayerExample.this.initServerAndClient(); MultiplayerExample.this.showDialog(DIALOG_SHOW_SERVER_IP_ID); } }) .create(); default: return super.onCreateDialog(pID); } } @Override protected void onDestroy() { if(this.mSocketServer != null) { try { this.mSocketServer.sendBroadcastServerMessage(new ConnectionCloseServerMessage()); } catch (final IOException e) { Debug.e(e); } this.mSocketServer.terminate(); } if(this.mServerConnector != null) { this.mServerConnector.terminate(); } super.onDestroy(); } @Override public boolean onKeyUp(final int pKeyCode, final KeyEvent pEvent) { switch(pKeyCode) { case KeyEvent.KEYCODE_BACK: this.finish(); return true; } return super.onKeyUp(pKeyCode, pEvent); } // =========================================================== // Methods // =========================================================== public void addFace(final int pID, final float pX, final float pY) { final Scene scene = this.mEngine.getScene(); /* Create the face and add it to the scene. */ final Sprite face = new Sprite(0, 0, this.mFaceTextureRegion); face.setPosition(pX - face.getWidth() * 0.5f, pY - face.getHeight() * 0.5f); face.setUserData(pID); this.mFaces.put(pID, face); scene.registerTouchArea(face); scene.attachChild(face); } public void moveFace(final int pID, final float pX, final float pY) { /* Find and move the face. */ final Sprite face = this.mFaces.get(pID); face.setPosition(pX - face.getWidth() * 0.5f, pY - face.getHeight() * 0.5f); } private void initServerAndClient() { this.initServer(); /* Wait some time after the server has been started, so it actually can start up. */ try { Thread.sleep(500); } catch (final Throwable t) { Debug.e(t); } this.initClient(); } private void initServer() { this.mSocketServer = new SocketServer<SocketConnectionClientConnector>(SERVER_PORT, new ExampleClientConnectorListener(), new ExampleServerStateListener()) { @Override protected SocketConnectionClientConnector newClientConnector(final SocketConnection pSocketConnection) throws IOException { return new SocketConnectionClientConnector(pSocketConnection); } }; this.mSocketServer.start(); } private void initClient() { try { this.mServerConnector = new SocketConnectionServerConnector(new SocketConnection(new Socket(this.mServerIP, SERVER_PORT)), new ExampleServerConnectorListener()); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_CONNECTION_CLOSE, ConnectionCloseServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { MultiplayerExample.this.finish(); } }); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_ADD_FACE, AddFaceServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final AddFaceServerMessage addFaceServerMessage = (AddFaceServerMessage)pServerMessage; MultiplayerExample.this.addFace(addFaceServerMessage.mID, addFaceServerMessage.mX, addFaceServerMessage.mY); } }); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_MOVE_FACE, MoveFaceServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final MoveFaceServerMessage moveFaceServerMessage = (MoveFaceServerMessage)pServerMessage; MultiplayerExample.this.moveFace(moveFaceServerMessage.mID, moveFaceServerMessage.mX, moveFaceServerMessage.mY); } }); this.mServerConnector.getConnection().start(); } catch (final Throwable t) { Debug.e(t); } } private void log(final String pMessage) { Debug.d(pMessage); } private void toast(final String pMessage) { this.log(pMessage); this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MultiplayerExample.this, pMessage, Toast.LENGTH_SHORT).show(); } }); } // =========================================================== // Inner and Anonymous Classes // =========================================================== public static class AddFaceServerMessage extends ServerMessage { private int mID; private float mX; private float mY; public AddFaceServerMessage() { } public AddFaceServerMessage(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } public void set(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } @Override public short getFlag() { return FLAG_MESSAGE_SERVER_ADD_FACE; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mID = pDataInputStream.readInt(); this.mX = pDataInputStream.readFloat(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mID); pDataOutputStream.writeFloat(this.mX); pDataOutputStream.writeFloat(this.mY); } } public static class MoveFaceServerMessage extends ServerMessage { private int mID; private float mX; private float mY; public MoveFaceServerMessage() { } public MoveFaceServerMessage(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } public void set(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } @Override public short getFlag() { return FLAG_MESSAGE_SERVER_MOVE_FACE; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mID = pDataInputStream.readInt(); this.mX = pDataInputStream.readFloat(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mID); pDataOutputStream.writeFloat(this.mX); pDataOutputStream.writeFloat(this.mY); } } private class ExampleServerConnectorListener implements ISocketConnectionServerConnectorListener { @Override public void onStarted(final ServerConnector<SocketConnection> pConnector) { MultiplayerExample.this.toast("CLIENT: Connected to server."); } @Override public void onTerminated(final ServerConnector<SocketConnection> pConnector) { MultiplayerExample.this.toast("CLIENT: Disconnected from Server..."); MultiplayerExample.this.finish(); } } private class ExampleServerStateListener implements ISocketServerListener<SocketConnectionClientConnector> { @Override public void onStarted(final SocketServer<SocketConnectionClientConnector> pSocketServer) { MultiplayerExample.this.toast("SERVER: Started."); } @Override public void onTerminated(final SocketServer<SocketConnectionClientConnector> pSocketServer) { MultiplayerExample.this.toast("SERVER: Terminated."); } @Override public void onException(final SocketServer<SocketConnectionClientConnector> pSocketServer, final Throwable pThrowable) { Debug.e(pThrowable); MultiplayerExample.this.toast("SERVER: Exception: " + pThrowable); } } private class ExampleClientConnectorListener implements ISocketConnectionClientConnectorListener { @Override public void onStarted(final ClientConnector<SocketConnection> pConnector) { MultiplayerExample.this.toast("SERVER: Client connected: " + pConnector.getConnection().getSocket().getInetAddress().getHostAddress()); } @Override public void onTerminated(final ClientConnector<SocketConnection> pConnector) { MultiplayerExample.this.toast("SERVER: Client disconnected: " + pConnector.getConnection().getSocket().getInetAddress().getHostAddress()); } } }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.MoveModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.augmentedreality.BaseAugmentedRealityGameActivity; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class AugmentedRealityExample extends BaseAugmentedRealityGameActivity { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "If you don't see a sprite moving over the screen, try starting this while already being in Landscape orientation!!", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); // scene.setBackgroundEnabled(false); scene.setBackground(new ColorBackground(0.0f, 0.0f, 0.0f, 0.0f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion); face.registerEntityModifier(new MoveModifier(30, 0, CAMERA_WIDTH - face.getWidth(), 0, CAMERA_HEIGHT - face.getHeight())); scene.attachChild(face); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.benchmark; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.text.Text; import org.anddev.andengine.entity.text.TickerText; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.util.HorizontalAlign; import android.graphics.Color; import android.graphics.Typeface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 21:00:56 - 28.06.2010 */ public class TickerTextBenchmark extends BaseBenchmark { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int TEXT_COUNT = 200; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mFontTexture; private Font mFont; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getBenchmarkID() { return TICKERTEXTBENCHMARK_ID; } @Override protected float getBenchmarkStartOffset() { return 2; } @Override protected float getBenchmarkDuration() { return 10; } @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 22, true, Color.WHITE); this.mEngine.getTextureManager().loadTexture(this.mFontTexture); this.getFontManager().loadFont(this.mFont); } @Override public Scene onLoadScene() { final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); for(int i = 0; i < TEXT_COUNT; i++) { final Text text = new TickerText(this.mRandom.nextInt(30), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 20), this.mFont, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", HorizontalAlign.CENTER, 5 + 5 * this.mRandom.nextFloat()); text.setColor(this.mRandom.nextFloat(), this.mRandom.nextFloat(), this.mRandom.nextFloat()); scene.attachChild(text); } return scene; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.benchmark; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.Callable; import org.anddev.andengine.engine.handler.timer.ITimerCallback; import org.anddev.andengine.engine.handler.timer.TimerHandler; import org.anddev.andengine.entity.util.FPSCounter; import org.anddev.andengine.examples.R; import org.anddev.andengine.opengl.util.GLHelper; import org.anddev.andengine.ui.activity.BaseGameActivity; import org.anddev.andengine.util.Callback; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.StreamUtils; import org.anddev.andengine.util.SystemUtils; import org.anddev.andengine.util.SystemUtils.SystemUtilsException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import android.telephony.TelephonyManager; import android.util.DisplayMetrics; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 10:38:36 - 27.06.2010 */ public abstract class BaseBenchmark extends BaseGameActivity { // =========================================================== // Constants // =========================================================== /* Initializing the Random generator produces a comparable result over different versions. */ private static final long RANDOM_SEED = 1234567890; private static final int DIALOG_SHOW_RESULT = 1; private static final String SUBMIT_URL = "http://www.andengine.org/sys/benchmark/submit.php"; protected static final int ANIMATIONBENCHMARK_ID = 0; protected static final int PARTICLESYSTEMBENCHMARK_ID = ANIMATIONBENCHMARK_ID + 1; protected static final int PHYSICSBENCHMARK_ID = PARTICLESYSTEMBENCHMARK_ID + 1; protected static final int ENTITYMODIFIERBENCHMARK_ID = PHYSICSBENCHMARK_ID + 1; protected static final int SPRITEBENCHMARK_ID = ENTITYMODIFIERBENCHMARK_ID + 1; protected static final int TICKERTEXTBENCHMARK_ID = SPRITEBENCHMARK_ID + 1; // =========================================================== // Fields // =========================================================== private float mFPS; protected final Random mRandom = new Random(RANDOM_SEED); // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // ===========================================================; protected void showResult(final float pFPS) { this.mFPS = pFPS; this.runOnUiThread(new Runnable() { @Override public void run() { BaseBenchmark.this.showDialog(DIALOG_SHOW_RESULT); } }); } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract int getBenchmarkID(); protected abstract float getBenchmarkDuration(); protected abstract float getBenchmarkStartOffset(); @Override public void onLoadComplete() { this.mEngine.registerUpdateHandler(new TimerHandler(this.getBenchmarkStartOffset(), new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { BaseBenchmark.this.mEngine.unregisterUpdateHandler(pTimerHandler); System.gc(); BaseBenchmark.this.setUpBenchmarkHandling(); } })); } protected void setUpBenchmarkHandling() { final FPSCounter fpsCounter = new FPSCounter(); this.mEngine.registerUpdateHandler(fpsCounter); this.mEngine.registerUpdateHandler(new TimerHandler(this.getBenchmarkDuration(), new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { BaseBenchmark.this.showResult(fpsCounter.getFPS()); } })); } @Override protected Dialog onCreateDialog(final int pID) { switch(pID) { case DIALOG_SHOW_RESULT: return new AlertDialog.Builder(this) .setTitle(this.getClass().getSimpleName()) .setMessage(String.format("Result: %.2f FPS", this.mFPS)) .setPositiveButton("Submit (Please!)", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { BaseBenchmark.this.submitResults(); } }) .setNegativeButton(android.R.string.cancel, new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { BaseBenchmark.this.finish(); } }) .create(); default: return super.onCreateDialog(pID); } } // =========================================================== // Methods // =========================================================== private void submitResults() { this.doAsync(R.string.dialog_benchmark_submit_title, R.string.dialog_benchmark_submit_message, new Callable<Boolean>() { @Override public Boolean call() throws Exception { // Create a new HttpClient and Post Header final HttpClient httpClient = new DefaultHttpClient(); final HttpPost httpPost = new HttpPost(SUBMIT_URL); // Add your data final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(18); nameValuePairs.add(new BasicNameValuePair("benchmark_id", String.valueOf(BaseBenchmark.this.getBenchmarkID()))); nameValuePairs.add(new BasicNameValuePair("benchmark_versionname", BaseBenchmark.getVersionName(BaseBenchmark.this))); nameValuePairs.add(new BasicNameValuePair("benchmark_versioncode", String.valueOf(BaseBenchmark.getVersionCode(BaseBenchmark.this)))); nameValuePairs.add(new BasicNameValuePair("benchmark_fps", String.valueOf(BaseBenchmark.this.mFPS).replace(",", "."))); nameValuePairs.add(new BasicNameValuePair("device_model", Build.MODEL)); nameValuePairs.add(new BasicNameValuePair("device_android_version", Build.VERSION.RELEASE)); nameValuePairs.add(new BasicNameValuePair("device_sdk_version", String.valueOf(Build.VERSION.SDK_INT))); nameValuePairs.add(new BasicNameValuePair("device_manufacturer", Build.MANUFACTURER)); nameValuePairs.add(new BasicNameValuePair("device_brand", Build.BRAND)); nameValuePairs.add(new BasicNameValuePair("device_build_id", Build.ID)); nameValuePairs.add(new BasicNameValuePair("device_build", Build.DISPLAY)); nameValuePairs.add(new BasicNameValuePair("device_device", Build.DEVICE)); nameValuePairs.add(new BasicNameValuePair("device_product", Build.PRODUCT)); nameValuePairs.add(new BasicNameValuePair("device_cpuabi", Build.CPU_ABI)); nameValuePairs.add(new BasicNameValuePair("device_board", Build.BOARD)); nameValuePairs.add(new BasicNameValuePair("device_fingerprint", Build.FINGERPRINT)); nameValuePairs.add(new BasicNameValuePair("benchmark_extension_vbo", GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS ? "1" : "0")); nameValuePairs.add(new BasicNameValuePair("benchmark_extension_drawtexture", GLHelper.EXTENSIONS_DRAWTEXTURE ? "1" : "0")); final TelephonyManager telephonyManager = (TelephonyManager)BaseBenchmark.this.getSystemService(Context.TELEPHONY_SERVICE); nameValuePairs.add(new BasicNameValuePair("device_imei", telephonyManager.getDeviceId())); final DisplayMetrics displayMetrics = new DisplayMetrics(); BaseBenchmark.this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); nameValuePairs.add(new BasicNameValuePair("device_displaymetrics_widthpixels", String.valueOf(displayMetrics.widthPixels))); nameValuePairs.add(new BasicNameValuePair("device_displaymetrics_heightpixels", String.valueOf(displayMetrics.heightPixels))); nameValuePairs.add(new BasicNameValuePair("device_displaymetrics_xdpi", String.valueOf(displayMetrics.xdpi))); nameValuePairs.add(new BasicNameValuePair("device_displaymetrics_ydpi", String.valueOf(displayMetrics.ydpi))); try{ final float bogoMips = SystemUtils.getCPUBogoMips(); nameValuePairs.add(new BasicNameValuePair("device_cpuinfo_bogomips", String.valueOf(bogoMips))); }catch(IllegalStateException e) { Debug.e(e); } try{ final float memoryTotal = SystemUtils.getMemoryTotal(); final float memoryFree = SystemUtils.getMemoryFree(); nameValuePairs.add(new BasicNameValuePair("device_memoryinfo_total", String.valueOf(memoryTotal))); nameValuePairs.add(new BasicNameValuePair("device_memoryinfo_free", String.valueOf(memoryFree))); }catch(IllegalStateException e) { Debug.e(e); } try{ final int cpuFrequencyCurrent = SystemUtils.getCPUFrequencyCurrent(); final int cpuFrequencyMax = SystemUtils.getCPUFrequencyMax(); nameValuePairs.add(new BasicNameValuePair("device_cpuinfo_frequency_current", String.valueOf(cpuFrequencyCurrent))); nameValuePairs.add(new BasicNameValuePair("device_cpuinfo_frequency_max", String.valueOf(cpuFrequencyMax))); }catch(SystemUtilsException e) { Debug.e(e); } httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request final HttpResponse response = httpClient.execute(httpPost); final int statusCode = response.getStatusLine().getStatusCode(); Debug.d(StreamUtils.readFully(response.getEntity().getContent())); if(statusCode == HttpStatus.SC_OK) { return true; } else { throw new RuntimeException(); } } }, new Callback<Boolean>() { @Override public void onCallback(final Boolean pCallbackValue) { BaseBenchmark.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(BaseBenchmark.this, "Success", Toast.LENGTH_LONG).show(); BaseBenchmark.this.finish(); } }); } }, new Callback<Exception>() { @Override public void onCallback(final Exception pException) { Debug.e(pException); Toast.makeText(BaseBenchmark.this, "Exception occurred: " + pException.getClass().getSimpleName(), Toast.LENGTH_SHORT).show(); BaseBenchmark.this.finish(); } }); } public static String getVersionName(final Context ctx) { try { final PackageInfo pi = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0); return pi.versionName; } catch (final PackageManager.NameNotFoundException e) { Debug.e("Package name not found", e); return "?"; } } public static int getVersionCode(final Context ctx) { try { final PackageInfo pi = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0); return pi.versionCode; } catch (final PackageManager.NameNotFoundException e) { Debug.e("Package name not found", e); return -1; } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.benchmark; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.sprite.batch.SpriteGroup; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.opengl.vertex.RectangleVertexBuffer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:28:45 - 28.06.2010 */ public class AnimationBenchmark extends BaseBenchmark { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int SPRITE_COUNT = 250; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mSnapdragonTextureRegion; private TiledTextureRegion mHelicopterTextureRegion; private TiledTextureRegion mBananaTextureRegion; private TiledTextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getBenchmarkID() { return ANIMATIONBENCHMARK_ID; } @Override protected float getBenchmarkStartOffset() { return 2; } @Override protected float getBenchmarkDuration() { return 10; } @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera); // engineOptions.getRenderOptions().disableExtensionVertexBufferObjects(); return new Engine(engineOptions); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(512, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mSnapdragonTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "snapdragon_tiled.png", 0, 0, 4, 3); this.mHelicopterTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "helicopter_tiled.png", 400, 0, 2, 2); this.mBananaTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "banana_tiled.png", 0, 180, 4, 2); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 132, 180, 2, 1); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); this.drawUsingSprites(scene); // this.drawUsingSpritesWithSharedVertexBuffer(scene); // this.drawUsingSpriteBatch(scene); return scene; } private void drawUsingSprites(Scene pScene) { for(int i = 0; i < SPRITE_COUNT; i++) { /* Quickly twinkling face. */ final AnimatedSprite face = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 32), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32), this.mFaceTextureRegion.deepCopy()); face.animate(50 + this.mRandom.nextInt(100)); pScene.attachChild(face); /* Continuously flying helicopter. */ final AnimatedSprite helicopter = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 48), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 48), this.mHelicopterTextureRegion.deepCopy()); helicopter.animate(new long[] { 50 + this.mRandom.nextInt(100), 50 + this.mRandom.nextInt(100) }, 1, 2, true); pScene.attachChild(helicopter); /* Snapdragon. */ final AnimatedSprite snapdragon = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 100), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 60), this.mSnapdragonTextureRegion.deepCopy()); snapdragon.animate(50 + this.mRandom.nextInt(100)); pScene.attachChild(snapdragon); /* Funny banana. */ final AnimatedSprite banana = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 32), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32), this.mBananaTextureRegion.deepCopy()); banana.animate(50 + this.mRandom.nextInt(100)); pScene.attachChild(banana); } } private void drawUsingSpritesWithSharedVertexBuffer(Scene pScene) { /* As we are creating quite a lot of the same Sprites, we can let them share a VertexBuffer to significantly increase performance. */ final RectangleVertexBuffer faceSharedVertexBuffer = new RectangleVertexBuffer(GL11.GL_DYNAMIC_DRAW, true); faceSharedVertexBuffer.update(this.mFaceTextureRegion.getWidth(), this.mFaceTextureRegion.getHeight()); final RectangleVertexBuffer helicopterSharedVertexBuffer = new RectangleVertexBuffer(GL11.GL_DYNAMIC_DRAW, true); helicopterSharedVertexBuffer.update(this.mHelicopterTextureRegion.getWidth(), this.mHelicopterTextureRegion.getHeight()); final RectangleVertexBuffer snapdragonSharedVertexBuffer = new RectangleVertexBuffer(GL11.GL_DYNAMIC_DRAW, true); snapdragonSharedVertexBuffer.update(this.mSnapdragonTextureRegion.getWidth(), this.mSnapdragonTextureRegion.getHeight()); final RectangleVertexBuffer bananaSharedVertexBuffer = new RectangleVertexBuffer(GL11.GL_DYNAMIC_DRAW, true); bananaSharedVertexBuffer.update(this.mBananaTextureRegion.getWidth(), this.mBananaTextureRegion.getHeight()); for(int i = 0; i < SPRITE_COUNT; i++) { /* Quickly twinkling face. */ final AnimatedSprite face = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 32), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32), this.mFaceTextureRegion.deepCopy(), faceSharedVertexBuffer); face.animate(50 + this.mRandom.nextInt(100)); pScene.attachChild(face); /* Continuously flying helicopter. */ final AnimatedSprite helicopter = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 48), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 48), this.mHelicopterTextureRegion.deepCopy(), helicopterSharedVertexBuffer); helicopter.animate(new long[] { 50 + this.mRandom.nextInt(100), 50 + this.mRandom.nextInt(100) }, 1, 2, true); pScene.attachChild(helicopter); /* Snapdragon. */ final AnimatedSprite snapdragon = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 100), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 60), this.mSnapdragonTextureRegion.deepCopy(), snapdragonSharedVertexBuffer); snapdragon.animate(50 + this.mRandom.nextInt(100)); pScene.attachChild(snapdragon); /* Funny banana. */ final AnimatedSprite banana = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 32), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32), this.mBananaTextureRegion.deepCopy(), bananaSharedVertexBuffer); banana.animate(50 + this.mRandom.nextInt(100)); pScene.attachChild(banana); } } private void drawUsingSpriteBatch(Scene pScene) { final SpriteGroup spriteGroup = new SpriteGroup(this.mBitmapTextureAtlas, 4 * SPRITE_COUNT); for(int i = 0; i < SPRITE_COUNT; i++) { /* Quickly twinkling face. */ final AnimatedSprite face = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 32), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32), this.mFaceTextureRegion.deepCopy()); //, faceSharedVertexBuffer); face.animate(50 + this.mRandom.nextInt(100)); spriteGroup.attachChild(face); /* Continuously flying helicopter. */ final AnimatedSprite helicopter = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 48), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 48), this.mHelicopterTextureRegion.deepCopy()); //, helicopterSharedVertexBuffer); helicopter.animate(new long[] { 50 + this.mRandom.nextInt(100), 50 + this.mRandom.nextInt(100) }, 1, 2, true); spriteGroup.attachChild(helicopter); /* Snapdragon. */ final AnimatedSprite snapdragon = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 100), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 60), this.mSnapdragonTextureRegion.deepCopy()); //, snapdragonSharedVertexBuffer); snapdragon.animate(50 + this.mRandom.nextInt(100)); spriteGroup.attachChild(snapdragon); /* Funny banana. */ final AnimatedSprite banana = new AnimatedSprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 32), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32), this.mBananaTextureRegion.deepCopy()); //, bananaSharedVertexBuffer); banana.animate(50 + this.mRandom.nextInt(100)); spriteGroup.attachChild(banana); } pScene.attachChild(spriteGroup); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.benchmark; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.handler.timer.ITimerCallback; import org.anddev.andengine.engine.handler.timer.TimerHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.extension.physics.box2d.util.constants.PhysicsConstants; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import android.hardware.SensorManager; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 18:47:08 - 19.03.2010 */ public class PhysicsBenchmark extends BaseBenchmark implements IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int COUNT_HORIZONTAL = 17; private static final int COUNT_VERTICAL = 15; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private Scene mScene; private PhysicsWorld mPhysicsWorld; private int mFaceCount = 0; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getBenchmarkID() { return PHYSICSBENCHMARK_ID; } @Override protected float getBenchmarkStartOffset() { return 2; } @Override protected float getBenchmarkDuration() { return 20; } @Override public Engine onLoadEngine() { final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mScene.setOnSceneTouchListener(this); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, 2 * SensorManager.GRAVITY_EARTH / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT), false); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); for(int x = 1; x < COUNT_HORIZONTAL; x++) { for(int y = 1; y < COUNT_VERTICAL; y++) { final float pX = (((float)CAMERA_WIDTH) / COUNT_HORIZONTAL) * x + y; final float pY = (((float)CAMERA_HEIGHT) / COUNT_VERTICAL) * y; this.addFace(this.mScene, pX - 16, pY - 16); } } this.mScene.registerUpdateHandler(new TimerHandler(2, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { PhysicsBenchmark.this.mScene.unregisterUpdateHandler(pTimerHandler); PhysicsBenchmark.this.mScene.registerUpdateHandler(PhysicsBenchmark.this.mPhysicsWorld); PhysicsBenchmark.this.mScene.registerUpdateHandler(new TimerHandler(10, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { final Vector2 gravity = Vector2Pool.obtain(0, -SensorManager.GRAVITY_EARTH / 32); PhysicsBenchmark.this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } })); } })); return this.mScene; } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pScene, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } // =========================================================== // Methods // =========================================================== private void addFace(final Scene pScene, final float pX, final float pY) { this.mFaceCount++; final AnimatedSprite face; final Body body; final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); if(this.mFaceCount % 2 == 0) { face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } else { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } pScene.attachChild(face); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.benchmark; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.particle.ParticleSystem; import org.anddev.andengine.entity.particle.emitter.PointParticleEmitter; import org.anddev.andengine.entity.particle.initializer.AccelerationInitializer; import org.anddev.andengine.entity.particle.initializer.ColorInitializer; import org.anddev.andengine.entity.particle.initializer.RotationInitializer; import org.anddev.andengine.entity.particle.initializer.VelocityInitializer; import org.anddev.andengine.entity.particle.modifier.AlphaModifier; import org.anddev.andengine.entity.particle.modifier.ColorModifier; import org.anddev.andengine.entity.particle.modifier.ExpireModifier; import org.anddev.andengine.entity.particle.modifier.ScaleModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 09:27:21 - 29.06.2010 */ public class ParticleSystemBenchmark extends BaseBenchmark { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; private static final float RATE_MIN = 15; private static final float RATE_MAX = 20; private static final int PARTICLES_MAX = 200; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mParticleTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getBenchmarkID() { return PARTICLESYSTEMBENCHMARK_ID; } @Override protected float getBenchmarkStartOffset() { return 5; } @Override protected float getBenchmarkDuration() { return 15; } @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "particle_fire.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.0f, 0.0f, 0.0f)); /* LowerLeft to LowerRight Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(-32, CAMERA_HEIGHT - 32), RATE_MIN, RATE_MAX, PARTICLES_MAX, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(35, 45, 0, -10)); particleSystem.addParticleInitializer(new AccelerationInitializer(5, -11)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(1.0f, 1.0f, 0.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(6.5f)); particleSystem.addParticleModifier(new ColorModifier(1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 2.5f, 5.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 6.5f)); scene.attachChild(particleSystem); } /* LowerRight to LowerLeft Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(CAMERA_WIDTH, CAMERA_HEIGHT - 32), RATE_MIN, RATE_MAX, PARTICLES_MAX, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-35, -45, 0, -10)); particleSystem.addParticleInitializer(new AccelerationInitializer(-5, -11)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(0.0f, 1.0f, 0.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(6.5f)); particleSystem.addParticleModifier(new ColorModifier(0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 2.5f, 5.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 6.5f)); scene.attachChild(particleSystem); } /* UpperLeft to UpperRight Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(-32, 0), RATE_MIN, RATE_MAX, PARTICLES_MAX, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(35, 45, 0, 10)); particleSystem.addParticleInitializer(new AccelerationInitializer(5, 11)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(0.0f, 0.0f, 1.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(6.5f)); particleSystem.addParticleModifier(new ColorModifier(0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 2.5f, 5.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 6.5f)); scene.attachChild(particleSystem); } /* UpperRight to UpperLeft Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(CAMERA_WIDTH, 0), RATE_MIN, RATE_MAX, PARTICLES_MAX, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-35, -45, 0, 10)); particleSystem.addParticleInitializer(new AccelerationInitializer(-5, 12)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(1.0f, 0.0f, 0.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(6.5f)); particleSystem.addParticleModifier(new ColorModifier(1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 2.5f, 5.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 6.5f)); scene.attachChild(particleSystem); } return scene; } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.benchmark; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.sprite.batch.SpriteBatch; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.vertex.RectangleVertexBuffer; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 10:34:22 - 27.06.2010 */ public class SpriteBenchmark extends BaseBenchmark { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int SPRITE_COUNT = 1000; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getBenchmarkID() { return SPRITEBENCHMARK_ID; } @Override protected float getBenchmarkStartOffset() { return 2; } @Override protected float getBenchmarkDuration() { return 10; } @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); this.drawUsingSprites(scene); // this.drawUsingSpritesWithSharedVertexBuffer(scene); // this.drawUsingSpriteBatch(scene); return scene; } // =========================================================== // Methods // =========================================================== private void drawUsingSprites(final Scene scene) { for(int i = 0; i < SPRITE_COUNT; i++) { final Sprite face = new Sprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 32), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32), this.mFaceTextureRegion); face.setBlendFunction(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA); face.setIgnoreUpdate(true); scene.attachChild(face); } } private void drawUsingSpritesWithSharedVertexBuffer(final Scene scene) { /* As we are creating quite a lot of the same Sprites, we can let them share a VertexBuffer to significantly increase performance. */ final RectangleVertexBuffer sharedVertexBuffer = new RectangleVertexBuffer(GL11.GL_STATIC_DRAW, true); sharedVertexBuffer.update(this.mFaceTextureRegion.getWidth(), this.mFaceTextureRegion.getHeight()); for(int i = 0; i < SPRITE_COUNT; i++) { final Sprite face = new Sprite(this.mRandom.nextFloat() * (CAMERA_WIDTH - 32), this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32), this.mFaceTextureRegion, sharedVertexBuffer); face.setBlendFunction(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA); face.setIgnoreUpdate(true); scene.attachChild(face); } } private void drawUsingSpriteBatch(final Scene scene) { final int width = this.mFaceTextureRegion.getWidth(); final int height = this.mFaceTextureRegion.getHeight(); final SpriteBatch spriteBatch = new SpriteBatch(this.mBitmapTextureAtlas, SPRITE_COUNT); spriteBatch.setBlendFunction(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA); for(int i = 0; i < SPRITE_COUNT; i++) { final float x = this.mRandom.nextFloat() * (CAMERA_WIDTH - 32); final float y = this.mRandom.nextFloat() * (CAMERA_HEIGHT - 32); spriteBatch.draw(this.mFaceTextureRegion, x, y, width, height); } spriteBatch.submit(); scene.attachChild(spriteBatch); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.benchmark; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.AlphaModifier; import org.anddev.andengine.entity.modifier.DelayModifier; import org.anddev.andengine.entity.modifier.IEntityModifier; import org.anddev.andengine.entity.modifier.ParallelEntityModifier; import org.anddev.andengine.entity.modifier.RotationByModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.sprite.batch.SpriteGroup; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.vertex.RectangleVertexBuffer; import android.opengl.GLES20; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 20:24:17 - 27.06.2010 */ public class EntityModifierBenchmark extends BaseBenchmark { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int SPRITE_COUNT = 1000; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getBenchmarkID() { return ENTITYMODIFIERBENCHMARK_ID; } @Override protected float getBenchmarkStartOffset() { return 2; } @Override protected float getBenchmarkDuration() { return 10; } @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); // this.drawUsingSprites(scene); // this.drawUsingSpritesWithSharedVertexBuffer(scene); this.drawUsingSpriteBatch(scene); return scene; } // =========================================================== // Methods // =========================================================== private void drawUsingSprites(final Scene pScene) { final IEntityModifier faceEntityModifier = new SequenceEntityModifier( new RotationByModifier(2, 90), new AlphaModifier(1.5f, 1, 0), new AlphaModifier(1.5f, 0, 1), new ScaleModifier(2.5f, 1, 0.5f), new DelayModifier(0.5f), new ParallelEntityModifier( new ScaleModifier(2f, 0.5f, 5), new RotationByModifier(2, 90) ), new ParallelEntityModifier( new ScaleModifier(2f, 5, 1), new RotationModifier(2f, 180, 0) ) ); for(int i = 0; i < SPRITE_COUNT; i++) { final Sprite face = new Sprite((CAMERA_WIDTH - 32) * this.mRandom.nextFloat(), (CAMERA_HEIGHT - 32) * this.mRandom.nextFloat(), this.mFaceTextureRegion); face.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); face.registerEntityModifier(faceEntityModifier.deepCopy()); pScene.attachChild(face); } } private void drawUsingSpritesWithSharedVertexBuffer(final Scene pScene) { final IEntityModifier faceEntityModifier = new SequenceEntityModifier( new RotationByModifier(2, 90), new AlphaModifier(1.5f, 1, 0), new AlphaModifier(1.5f, 0, 1), new ScaleModifier(2.5f, 1, 0.5f), new DelayModifier(0.5f), new ParallelEntityModifier( new ScaleModifier(2f, 0.5f, 5), new RotationByModifier(2, 90) ), new ParallelEntityModifier( new ScaleModifier(2f, 5, 1), new RotationModifier(2f, 180, 0) ) ); /* As we are creating quite a lot of the same Sprites, we can let them share a VertexBuffer to significantly increase performance. */ final RectangleVertexBuffer sharedVertexBuffer = new RectangleVertexBuffer(GL11.GL_DYNAMIC_DRAW, true); sharedVertexBuffer.update(this.mFaceTextureRegion.getWidth(), this.mFaceTextureRegion.getHeight()); for(int i = 0; i < SPRITE_COUNT; i++) { final Sprite face = new Sprite((CAMERA_WIDTH - 32) * this.mRandom.nextFloat(), (CAMERA_HEIGHT - 32) * this.mRandom.nextFloat(), this.mFaceTextureRegion, sharedVertexBuffer); face.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); face.registerEntityModifier(faceEntityModifier.deepCopy()); pScene.attachChild(face); } } private void drawUsingSpriteBatch(final Scene pScene) { final IEntityModifier faceEntityModifier = new SequenceEntityModifier( new RotationByModifier(2, 90), // new AlphaModifier(1.5f, 1, 0), // new AlphaModifier(1.5f, 0, 1), new DelayModifier(1.5f + 1.5f), new ScaleModifier(2.5f, 1, 0.5f), new DelayModifier(0.5f), new ParallelEntityModifier( new ScaleModifier(2f, 0.5f, 5), new RotationByModifier(2, 90) ), new ParallelEntityModifier( new ScaleModifier(2f, 5, 1), new RotationModifier(2f, 180, 0) ) ); final IEntityModifier spriteBatchEntityModifier = new SequenceEntityModifier( new DelayModifier(2), new AlphaModifier(1.5f, 1, 0), new AlphaModifier(1.5f, 0, 1) ); final SpriteGroup spriteGroup = new SpriteGroup(this.mBitmapTextureAtlas, SPRITE_COUNT); spriteGroup.setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); for(int i = 0; i < SPRITE_COUNT; i++) { final Sprite face = new Sprite((CAMERA_WIDTH - 32) * this.mRandom.nextFloat(), (CAMERA_HEIGHT - 32) * this.mRandom.nextFloat(), this.mFaceTextureRegion); face.registerEntityModifier(faceEntityModifier.deepCopy()); spriteGroup.attachChild(face); } spriteGroup.registerEntityModifier(spriteBatchEntityModifier); pScene.attachChild(spriteGroup); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 12:14:22 - 30.06.2010 */ public class UpdateTextureExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mFaceTextureRegion; private boolean mToggleBox = true; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to update (redraw) an existing BitmapTextureAtlas with every touch!", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* Calculate the coordinates for the face, so its centered on the camera. */ final int x = (CAMERA_WIDTH - this.mFaceTextureRegion.getTileWidth()) / 2; final int y = (CAMERA_HEIGHT - this.mFaceTextureRegion.getTileHeight()) / 2; /* Create the face and add it to the scene. */ final AnimatedSprite face = new AnimatedSprite(x, y, this.mFaceTextureRegion); face.animate(100); scene.attachChild(face); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pSceneTouchEvent.isActionDown()) { UpdateTextureExample.this.toggle(); } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== private void toggle() { this.mBitmapTextureAtlas.clearTextureAtlasSources(); this.mToggleBox = !this.mToggleBox; BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, this.mToggleBox ? "face_box_tiled.png" : "face_circle_tiled.png", 0, 0, 2, 1); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.io.IOException; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.level.LevelLoader; import org.anddev.andengine.level.LevelLoader.IEntityLoader; import org.anddev.andengine.level.util.constants.LevelConstants; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.util.Debug; import org.anddev.andengine.util.SAXUtils; import org.xml.sax.Attributes; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 17:16:10 - 11.10.2010 */ public class LevelLoaderExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; private static final String TAG_ENTITY = "entity"; private static final String TAG_ENTITY_ATTRIBUTE_X = "x"; private static final String TAG_ENTITY_ATTRIBUTE_Y = "y"; private static final String TAG_ENTITY_ATTRIBUTE_WIDTH = "width"; private static final String TAG_ENTITY_ATTRIBUTE_HEIGHT = "height"; private static final String TAG_ENTITY_ATTRIBUTE_TYPE = "type"; private static final Object TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_BOX = "box"; private static final Object TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_CIRCLE = "circle"; private static final Object TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_TRIANGLE = "triangle"; private static final Object TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_HEXAGON = "hexagon"; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private TiledTextureRegion mTriangleFaceTextureRegion; private TiledTextureRegion mHexagonFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Loading level...", Toast.LENGTH_SHORT).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera)); } @Override public void onLoadResources() { /* Textures. */ this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); /* TextureRegions. */ this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mTriangleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_triangle_tiled.png", 0, 64, 2, 1); // 64x32 this.mHexagonFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_hexagon_tiled.png", 0, 96, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0, 0, 0)); final LevelLoader levelLoader = new LevelLoader(); levelLoader.setAssetBasePath("level/"); levelLoader.registerEntityLoader(LevelConstants.TAG_LEVEL, new IEntityLoader() { @Override public void onLoadEntity(final String pEntityName, final Attributes pAttributes) { final int width = SAXUtils.getIntAttributeOrThrow(pAttributes, LevelConstants.TAG_LEVEL_ATTRIBUTE_WIDTH); final int height = SAXUtils.getIntAttributeOrThrow(pAttributes, LevelConstants.TAG_LEVEL_ATTRIBUTE_HEIGHT); Toast.makeText(LevelLoaderExample.this, "Loaded level with width=" + width + " and height=" + height + ".", Toast.LENGTH_LONG).show(); } }); levelLoader.registerEntityLoader(TAG_ENTITY, new IEntityLoader() { @Override public void onLoadEntity(final String pEntityName, final Attributes pAttributes) { final int x = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_X); final int y = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_Y); final int width = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_WIDTH); final int height = SAXUtils.getIntAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_HEIGHT); final String type = SAXUtils.getAttributeOrThrow(pAttributes, TAG_ENTITY_ATTRIBUTE_TYPE); LevelLoaderExample.this.addFace(scene, x, y, width, height, type); } }); try { levelLoader.loadLevelFromAsset(this, "example.lvl"); } catch (final IOException e) { Debug.e(e); } return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== private void addFace(final Scene pScene, final float pX, final float pY, final int pWidth, final int pHeight, final String pType) { final AnimatedSprite face; if(pType.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_BOX)) { face = new AnimatedSprite(pX, pY, pWidth, pHeight, this.mBoxFaceTextureRegion); } else if(pType.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_CIRCLE)) { face = new AnimatedSprite(pX, pY, pWidth, pHeight, this.mCircleFaceTextureRegion); } else if(pType.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_TRIANGLE)) { face = new AnimatedSprite(pX, pY, pWidth, pHeight, this.mTriangleFaceTextureRegion); } else if(pType.equals(TAG_ENTITY_ATTRIBUTE_TYPE_VALUE_HEXAGON)) { face = new AnimatedSprite(pX, pY, pWidth, pHeight, this.mHexagonFaceTextureRegion); } else { throw new IllegalArgumentException(); } face.animate(200); pScene.attachChild(face); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import org.anddev.andengine.util.Debug; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 14:33:38 - 03.10.2010 */ public class PhysicsCollisionFilteringExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; /* The categories. */ public static final short CATEGORYBIT_WALL = 1; public static final short CATEGORYBIT_BOX = 2; public static final short CATEGORYBIT_CIRCLE = 4; /* And what should collide with what. */ public static final short MASKBITS_WALL = CATEGORYBIT_WALL + CATEGORYBIT_BOX + CATEGORYBIT_CIRCLE; public static final short MASKBITS_BOX = CATEGORYBIT_WALL + CATEGORYBIT_BOX; // Missing: CATEGORYBIT_CIRCLE public static final short MASKBITS_CIRCLE = CATEGORYBIT_WALL + CATEGORYBIT_CIRCLE; // Missing: CATEGORYBIT_BOX public static final FixtureDef WALL_FIXTURE_DEF = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f, false, CATEGORYBIT_WALL, MASKBITS_WALL, (short)0); public static final FixtureDef BOX_FIXTURE_DEF = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f, false, CATEGORYBIT_BOX, MASKBITS_BOX, (short)0); public static final FixtureDef CIRCLE_FIXTURE_DEF = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f, false, CATEGORYBIT_CIRCLE, MASKBITS_CIRCLE, (short)0); // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private Scene mScene; private PhysicsWorld mPhysicsWorld; private int mFaceCount = 0; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add objects.", Toast.LENGTH_LONG).show(); Toast.makeText(this, "Boxes will only collide with boxes.\nCircles will only collide with circles.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new Engine(engineOptions); } @Override public void onLoadResources() { /* Textures. */ this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); /* TextureRegions. */ this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mScene.setOnSceneTouchListener(this); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, WALL_FIXTURE_DEF); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, WALL_FIXTURE_DEF); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, WALL_FIXTURE_DEF); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, WALL_FIXTURE_DEF); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); return this.mScene; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } @Override public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) { final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX(), pAccelerometerData.getY()); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerometerSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerometerSensor(); } // =========================================================== // Methods // =========================================================== private void addFace(final float pX, final float pY) { this.mFaceCount++; Debug.d("Faces: " + this.mFaceCount); final AnimatedSprite face; final Body body; if(this.mFaceCount % 2 == 0) { face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, BOX_FIXTURE_DEF); } else { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, CIRCLE_FIXTURE_DEF); } face.animate(200); this.mScene.attachChild(face); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.util.HashMap; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.ZoomCamera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.card.Card; import org.anddev.andengine.extension.input.touch.controller.MultiTouch; import org.anddev.andengine.extension.input.touch.controller.MultiTouchController; import org.anddev.andengine.extension.input.touch.detector.PinchZoomDetector; import org.anddev.andengine.extension.input.touch.detector.PinchZoomDetector.IPinchZoomDetectorListener; import org.anddev.andengine.extension.input.touch.exception.MultiTouchException; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.input.touch.detector.ScrollDetector; import org.anddev.andengine.input.touch.detector.ScrollDetector.IScrollDetectorListener; import org.anddev.andengine.input.touch.detector.SurfaceScrollDetector; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TextureRegionFactory; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 15:44:58 - 05.11.2010 */ public class PinchZoomExample extends BaseExample implements IOnSceneTouchListener, IScrollDetectorListener, IPinchZoomDetectorListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private ZoomCamera mZoomCamera; private BitmapTextureAtlas mCardDeckTexture; private Scene mScene; private HashMap<Card, TextureRegion> mCardTotextureRegionMap; private SurfaceScrollDetector mScrollDetector; private PinchZoomDetector mPinchZoomDetector; private float mPinchZoomStartedCameraZoomFactor; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mZoomCamera = new ZoomCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mZoomCamera)); try { if(MultiTouch.isSupported(this)) { engine.setTouchController(new MultiTouchController()); } else { Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(No PinchZoom is possible!)", Toast.LENGTH_LONG).show(); } } catch (final MultiTouchException e) { Toast.makeText(this, "Sorry your Android Version does NOT support MultiTouch!\n\n(No PinchZoom is possible!)", Toast.LENGTH_LONG).show(); } return engine; } @Override public void onLoadResources() { this.mCardDeckTexture = new BitmapTextureAtlas(1024, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mCardDeckTexture, this, "carddeck_tiled.png", 0, 0); this.mCardTotextureRegionMap = new HashMap<Card, TextureRegion>(); /* Extract the TextureRegion of each card in the whole deck. */ for(final Card card : Card.values()) { final TextureRegion cardTextureRegion = TextureRegionFactory.extractFromTexture(this.mCardDeckTexture, card.getTexturePositionX(), card.getTexturePositionY(), Card.CARD_WIDTH, Card.CARD_HEIGHT, true); this.mCardTotextureRegionMap.put(card, cardTextureRegion); } this.mEngine.getTextureManager().loadTexture(this.mCardDeckTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setOnAreaTouchTraversalFrontToBack(); this.addCard(Card.CLUB_ACE, 200, 100); this.addCard(Card.HEART_ACE, 200, 260); this.addCard(Card.DIAMOND_ACE, 440, 100); this.addCard(Card.SPADE_ACE, 440, 260); this.mScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); this.mScrollDetector = new SurfaceScrollDetector(this); if(MultiTouch.isSupportedByAndroidVersion()) { try { this.mPinchZoomDetector = new PinchZoomDetector(this); } catch (final MultiTouchException e) { this.mPinchZoomDetector = null; } } else { this.mPinchZoomDetector = null; } this.mScene.setOnSceneTouchListener(this); this.mScene.setTouchAreaBindingEnabled(true); return this.mScene; } @Override public void onLoadComplete() { } @Override public void onScroll(final ScrollDetector pScollDetector, final TouchEvent pTouchEvent, final float pDistanceX, final float pDistanceY) { final float zoomFactor = this.mZoomCamera.getZoomFactor(); this.mZoomCamera.offsetCenter(-pDistanceX / zoomFactor, -pDistanceY / zoomFactor); } @Override public void onPinchZoomStarted(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent) { this.mPinchZoomStartedCameraZoomFactor = this.mZoomCamera.getZoomFactor(); } @Override public void onPinchZoom(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent, final float pZoomFactor) { this.mZoomCamera.setZoomFactor(this.mPinchZoomStartedCameraZoomFactor * pZoomFactor); } @Override public void onPinchZoomFinished(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent, final float pZoomFactor) { this.mZoomCamera.setZoomFactor(this.mPinchZoomStartedCameraZoomFactor * pZoomFactor); } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPinchZoomDetector != null) { this.mPinchZoomDetector.onTouchEvent(pSceneTouchEvent); if(this.mPinchZoomDetector.isZooming()) { this.mScrollDetector.setEnabled(false); } else { if(pSceneTouchEvent.isActionDown()) { this.mScrollDetector.setEnabled(true); } this.mScrollDetector.onTouchEvent(pSceneTouchEvent); } } else { this.mScrollDetector.onTouchEvent(pSceneTouchEvent); } return true; } // =========================================================== // Methods // =========================================================== private void addCard(final Card pCard, final int pX, final int pY) { final Sprite sprite = new Sprite(pX, pY, this.mCardTotextureRegionMap.get(pCard)) { boolean mGrabbed = false; @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { switch(pSceneTouchEvent.getAction()) { case TouchEvent.ACTION_DOWN: this.setScale(1.25f); this.mGrabbed = true; break; case TouchEvent.ACTION_MOVE: if(this.mGrabbed) { this.setPosition(pSceneTouchEvent.getX() - Card.CARD_WIDTH / 2, pSceneTouchEvent.getY() - Card.CARD_HEIGHT / 2); } break; case TouchEvent.ACTION_UP: if(this.mGrabbed) { this.mGrabbed = false; this.setScale(1.0f); } break; } return true; } }; this.mScene.attachChild(sprite); this.mScene.registerTouchArea(sprite); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.ITextureAtlas; import org.anddev.andengine.opengl.texture.atlas.ITextureAtlas.ITextureAtlasStateListener; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ImageFormatsExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mPNGTextureRegion; private TextureRegion mJPGTextureRegion; private TextureRegion mGIFTextureRegion; private TextureRegion mBMPTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "GIF is not supported yet. Use PNG instead, it's the better format anyway!", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA, new ITextureAtlasStateListener.TextureAtlasStateAdapter<IBitmapTextureAtlasSource>() { @Override public void onTextureAtlasSourceLoadExeption(final ITextureAtlas<IBitmapTextureAtlasSource> pTextureAtlas, final IBitmapTextureAtlasSource pBitmapTextureAtlasSource, final Throwable pThrowable) { ImageFormatsExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(ImageFormatsExample.this, "Failed loading TextureSource: " + pBitmapTextureAtlasSource.toString(), Toast.LENGTH_LONG).show(); } }); } }); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mPNGTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "imageformat_png.png", 0, 0); this.mJPGTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "imageformat_jpg.jpg", 49, 0); this.mGIFTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "imageformat_gif.gif", 0, 49); this.mBMPTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "imageformat_bmp.bmp", 49, 49); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* Create the icons and add them to the scene. */ scene.attachChild(new Sprite(160 - 24, 106 - 24, this.mPNGTextureRegion)); scene.attachChild(new Sprite(160 - 24, 213 - 24, this.mJPGTextureRegion)); scene.attachChild(new Sprite(320 - 24, 106 - 24, this.mGIFTextureRegion)); scene.attachChild(new Sprite(320 - 24, 213 - 24, this.mBMPTextureRegion)); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.MoveModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.scene.menu.MenuScene; import org.anddev.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener; import org.anddev.andengine.entity.scene.menu.item.IMenuItem; import org.anddev.andengine.entity.scene.menu.item.SpriteMenuItem; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.view.KeyEvent; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 01:30:15 - 02.04.2010 */ public class MenuExample extends BaseExample implements IOnMenuItemClickListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; protected static final int MENU_RESET = 0; protected static final int MENU_QUIT = MENU_RESET + 1; // =========================================================== // Fields // =========================================================== protected Camera mCamera; protected Scene mMainScene; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; protected MenuScene mMenuScene; private BitmapTextureAtlas mMenuTexture; protected TextureRegion mMenuResetTextureRegion; protected TextureRegion mMenuQuitTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box_menu.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); this.mMenuTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mMenuResetTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mMenuTexture, this, "menu_reset.png", 0, 0); this.mMenuQuitTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mMenuTexture, this, "menu_quit.png", 0, 50); this.mEngine.getTextureManager().loadTexture(this.mMenuTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.createMenuScene(); /* Just a simple scene with an animated face flying around. */ this.mMainScene = new Scene(); this.mMainScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final Sprite face = new Sprite(0, 0, this.mFaceTextureRegion); face.registerEntityModifier(new MoveModifier(30, 0, CAMERA_WIDTH - face.getWidth(), 0, CAMERA_HEIGHT - face.getHeight())); this.mMainScene.attachChild(face); return this.mMainScene; } @Override public void onLoadComplete() { } @Override public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) { if(pKeyCode == KeyEvent.KEYCODE_MENU && pEvent.getAction() == KeyEvent.ACTION_DOWN) { if(this.mMainScene.hasChildScene()) { /* Remove the menu and reset it. */ this.mMenuScene.back(); } else { /* Attach the menu. */ this.mMainScene.setChildScene(this.mMenuScene, false, true, true); } return true; } else { return super.onKeyDown(pKeyCode, pEvent); } } @Override public boolean onMenuItemClicked(final MenuScene pMenuScene, final IMenuItem pMenuItem, final float pMenuItemLocalX, final float pMenuItemLocalY) { switch(pMenuItem.getID()) { case MENU_RESET: /* Restart the animation. */ this.mMainScene.reset(); /* Remove the menu and reset it. */ this.mMainScene.clearChildScene(); this.mMenuScene.reset(); return true; case MENU_QUIT: /* End Activity. */ this.finish(); return true; default: return false; } } // =========================================================== // Methods // =========================================================== protected void createMenuScene() { this.mMenuScene = new MenuScene(this.mCamera); final SpriteMenuItem resetMenuItem = new SpriteMenuItem(MENU_RESET, this.mMenuResetTextureRegion); resetMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); this.mMenuScene.addMenuItem(resetMenuItem); final SpriteMenuItem quitMenuItem = new SpriteMenuItem(MENU_QUIT, this.mMenuQuitTextureRegion); quitMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); this.mMenuScene.addMenuItem(quitMenuItem); this.mMenuScene.buildAnimations(); this.mMenuScene.setBackgroundEnabled(false); this.mMenuScene.setOnMenuItemClickListener(this); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.util.Random; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.util.FPSLogger; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class LineExample extends BaseExample { // =========================================================== // Constants // =========================================================== /* Initializing the Random generator produces a comparable result over different versions. */ private static final long RANDOM_SEED = 1234567890; private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int LINE_COUNT = 100; // =========================================================== // Fields // =========================================================== private Camera mCamera; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final Random random = new Random(RANDOM_SEED); for(int i = 0; i < LINE_COUNT; i++) { final float x1 = random.nextFloat() * CAMERA_WIDTH; final float x2 = random.nextFloat() * CAMERA_WIDTH; final float y1 = random.nextFloat() * CAMERA_HEIGHT; final float y2 = random.nextFloat() * CAMERA_HEIGHT; final float lineWidth = random.nextFloat() * 5; final Line line = new Line(x1, y1, x2, y2, lineWidth); line.setColor(random.nextFloat(), random.nextFloat(), random.nextFloat()); scene.attachChild(line); } return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.io.IOException; import java.io.InputStream; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.SmoothCamera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.ZoomState; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.ITexture; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.compressed.pvr.PVRCCZTexture; import org.anddev.andengine.opengl.texture.compressed.pvr.PVRTexture.PVRTextureFormat; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TextureRegionFactory; import org.anddev.andengine.util.Debug; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 15:31:11 - 27.07.2011 */ public class PVRCCZTextureExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private SmoothCamera mSmoothCamera; private ITexture mTexture; private TextureRegion mHouseTextureRegion; private ZoomState mZoomState = ZoomState.NONE; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Click the top half of the screen to zoom in or the bottom half to zoom out!", Toast.LENGTH_LONG); this.mSmoothCamera = new SmoothCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, 0, 0, 0.1f) { @Override public void onUpdate(final float pSecondsElapsed) { switch (PVRCCZTextureExample.this.mZoomState) { case IN: this.setZoomFactor(this.getZoomFactor() + 0.1f * pSecondsElapsed); break; case OUT: this.setZoomFactor(this.getZoomFactor() - 0.1f * pSecondsElapsed); break; } super.onUpdate(pSecondsElapsed); } }; return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mSmoothCamera)); } @Override public void onLoadResources() { try { this.mTexture = new PVRCCZTexture(PVRTextureFormat.RGBA_8888, TextureOptions.BILINEAR) { @Override protected InputStream onGetInputStream() throws IOException { return PVRCCZTextureExample.this.getResources().openRawResource(R.raw.house_pvrccz_argb_8888); } }; this.mHouseTextureRegion = TextureRegionFactory.extractFromTexture(this.mTexture, 0, 0, 512, 512, true); this.mEngine.getTextureManager().loadTextures(this.mTexture); } catch (final Throwable e) { Debug.e(e); } } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mHouseTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mHouseTextureRegion.getHeight()) / 2; scene.attachChild(new Sprite(centerX, centerY, this.mHouseTextureRegion)); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if (pSceneTouchEvent.isActionDown() || pSceneTouchEvent.isActionMove()) { if(pSceneTouchEvent.getY() < CAMERA_HEIGHT / 2) { PVRCCZTextureExample.this.mZoomState = ZoomState.IN; } else { PVRCCZTextureExample.this.mZoomState = ZoomState.OUT; } } else { PVRCCZTextureExample.this.mZoomState = ZoomState.NONE; } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.SingleSceneSplitScreenEngine; import org.anddev.andengine.engine.camera.BoundCamera; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.HUD; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.sprite.TiledSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 18:08:29 - 27.07.2010 */ public class BoundCameraExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 400; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BoundCamera mBoundChaseCamera; private Scene mScene; private PhysicsWorld mPhysicsWorld; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private BitmapTextureAtlas mHUDTexture; private TiledTextureRegion mToggleButtonTextureRegion; private int mFaceCount; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add boxes.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); this.mBoundChaseCamera = new BoundCamera(0, 0, CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2, 0, CAMERA_WIDTH, 0, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH * 2, CAMERA_HEIGHT), this.mCamera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new SingleSceneSplitScreenEngine(engineOptions, this.mBoundChaseCamera); } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); this.mHUDTexture = new BitmapTextureAtlas(256, 128,TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mToggleButtonTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mHUDTexture, this, "toggle_button.png", 0, 0, 2, 1); // 256x128 this.mEngine.getTextureManager().loadTexture(this.mHUDTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setOnSceneTouchListener(this); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); final HUD hud = new HUD(); final TiledSprite toggleButton = new TiledSprite(CAMERA_WIDTH / 2 - this.mToggleButtonTextureRegion.getTileWidth(), CAMERA_HEIGHT / 2 - this.mToggleButtonTextureRegion.getTileHeight(), this.mToggleButtonTextureRegion){ @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { final boolean boundsEnabled = BoundCameraExample.this.mBoundChaseCamera.isBoundsEnabled(); if(boundsEnabled) { BoundCameraExample.this.mBoundChaseCamera.setBoundsEnabled(false); this.setCurrentTileIndex(1); BoundCameraExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(BoundCameraExample.this, "Bounds Disabled.", Toast.LENGTH_SHORT).show(); } }); } else { BoundCameraExample.this.mBoundChaseCamera.setBoundsEnabled(true); this.setCurrentTileIndex(0); BoundCameraExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(BoundCameraExample.this, "Bounds Enabled.", Toast.LENGTH_SHORT).show(); } }); } } return true; } }; hud.registerTouchArea(toggleButton); hud.attachChild(toggleButton); this.mBoundChaseCamera.setHUD(hud); return this.mScene; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } @Override public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) { final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX(), pAccelerometerData.getY()); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerometerSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerometerSensor(); } // =========================================================== // Methods // =========================================================== private void addFace(final float pX, final float pY) { final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); final AnimatedSprite face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion).animate(100); final Body body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); this.mScene.attachChild(face); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); if(this.mFaceCount == 0){ this.mBoundChaseCamera.setChaseEntity(face); } this.mFaceCount++; } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.text.Text; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.font.FontFactory; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import android.graphics.Color; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class CustomFontExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int FONT_SIZE = 48; // =========================================================== // Fields // =========================================================== private Camera mCamera; private Font mDroidFont; private Font mPlokFont; private Font mNeverwinterNightsFont; private Font mUnrealTournamenFont; private Font mKingdomOfHeartsFont; private BitmapTextureAtlas mDroidFontTexture; private BitmapTextureAtlas mPlokFontTexture; private BitmapTextureAtlas mNeverwinterNightsFontTexture; private BitmapTextureAtlas mUnrealTournamentFontTexture; private BitmapTextureAtlas mKingdomOfHeartsFontTexture; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { /* The custom fonts. */ this.mDroidFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mKingdomOfHeartsFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mNeverwinterNightsFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mPlokFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mUnrealTournamentFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); FontFactory.setAssetBasePath("font/"); this.mDroidFont = FontFactory.createFromAsset(this.mDroidFontTexture, this, "Droid.ttf", FONT_SIZE, true, Color.BLACK); this.mKingdomOfHeartsFont = FontFactory.createFromAsset(this.mKingdomOfHeartsFontTexture, this, "KingdomOfHearts.ttf", FONT_SIZE + 20, true, Color.BLACK); this.mNeverwinterNightsFont = FontFactory.createFromAsset(this.mNeverwinterNightsFontTexture, this, "NeverwinterNights.ttf", FONT_SIZE, true, Color.BLACK); this.mPlokFont = FontFactory.createFromAsset(this.mPlokFontTexture, this, "Plok.ttf", FONT_SIZE, true, Color.BLACK); this.mUnrealTournamenFont = FontFactory.createFromAsset(this.mUnrealTournamentFontTexture, this, "UnrealTournament.ttf", FONT_SIZE, true, Color.BLACK); this.mEngine.getTextureManager().loadTextures(this.mDroidFontTexture, this.mKingdomOfHeartsFontTexture, this.mNeverwinterNightsFontTexture, this.mPlokFontTexture, this.mUnrealTournamentFontTexture); this.getFontManager().loadFonts(this.mDroidFont, this.mKingdomOfHeartsFont, this.mNeverwinterNightsFont, this.mPlokFont, this.mUnrealTournamenFont); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); scene.attachChild(new Text(230, 30, this.mDroidFont, "Droid Font")); scene.attachChild(new Text(160, 120, this.mKingdomOfHeartsFont, "Kingdom Of Hearts Font")); scene.attachChild(new Text(110, 210, this.mNeverwinterNightsFont, "Neverwinter Nights Font")); scene.attachChild(new Text(140, 300, this.mPlokFont, "Plok Font")); scene.attachChild(new Text(25, 390, this.mUnrealTournamenFont, "Unreal Tournament Font")); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.util.HashMap; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.card.Card; import org.anddev.andengine.extension.input.touch.controller.MultiTouch; import org.anddev.andengine.extension.input.touch.controller.MultiTouchController; import org.anddev.andengine.extension.input.touch.exception.MultiTouchException; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TextureRegionFactory; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 18:20:40 - 18.06.2010 */ public class MultiTouchExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mCardDeckTexture; private Scene mScene; private HashMap<Card, TextureRegion> mCardTotextureRegionMap; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); try { if(MultiTouch.isSupported(this)) { engine.setTouchController(new MultiTouchController()); if(MultiTouch.isSupportedDistinct(this)) { Toast.makeText(this, "MultiTouch detected --> Drag multiple Sprites with multiple fingers!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "MultiTouch detected --> Drag multiple Sprites with multiple fingers!\n\n(Your device might have problems to distinguish between separate fingers.)", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, "Sorry your device does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)", Toast.LENGTH_LONG).show(); } } catch (final MultiTouchException e) { Toast.makeText(this, "Sorry your Android Version does NOT support MultiTouch!\n\n(Falling back to SingleTouch.)", Toast.LENGTH_LONG).show(); } return engine; } @Override public void onLoadResources() { this.mCardDeckTexture = new BitmapTextureAtlas(1024, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mCardDeckTexture, this, "carddeck_tiled.png", 0, 0); this.mCardTotextureRegionMap = new HashMap<Card, TextureRegion>(); /* Extract the TextureRegion of each card in the whole deck. */ for(final Card card : Card.values()) { final TextureRegion cardTextureRegion = TextureRegionFactory.extractFromTexture(this.mCardDeckTexture, card.getTexturePositionX(), card.getTexturePositionY(), Card.CARD_WIDTH, Card.CARD_HEIGHT, true); this.mCardTotextureRegionMap.put(card, cardTextureRegion); } this.mEngine.getTextureManager().loadTexture(this.mCardDeckTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setOnAreaTouchTraversalFrontToBack(); this.addCard(Card.CLUB_ACE, 200, 100); this.addCard(Card.HEART_ACE, 200, 260); this.addCard(Card.DIAMOND_ACE, 440, 100); this.addCard(Card.SPADE_ACE, 440, 260); this.mScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); this.mScene.setTouchAreaBindingEnabled(true); return this.mScene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== private void addCard(final Card pCard, final int pX, final int pY) { final Sprite sprite = new Sprite(pX, pY, this.mCardTotextureRegionMap.get(pCard)) { boolean mGrabbed = false; @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { switch(pSceneTouchEvent.getAction()) { case TouchEvent.ACTION_DOWN: this.setScale(1.25f); this.mGrabbed = true; break; case TouchEvent.ACTION_MOVE: if(this.mGrabbed) { this.setPosition(pSceneTouchEvent.getX() - Card.CARD_WIDTH / 2, pSceneTouchEvent.getY() - Card.CARD_HEIGHT / 2); } break; case TouchEvent.ACTION_UP: if(this.mGrabbed) { this.mGrabbed = false; this.setScale(1.0f); } break; } return true; } }; this.mScene.attachChild(sprite); this.mScene.registerTouchArea(sprite); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.handler.timer.ITimerCallback; import org.anddev.andengine.engine.handler.timer.TimerHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.text.ChangeableText; import org.anddev.andengine.entity.util.FPSCounter; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import android.graphics.Color; import android.graphics.Typeface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 20:06:15 - 08.07.2010 */ public class ChangeableTextExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mFontTexture; private Font mFont; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 48, true, Color.BLACK); this.mEngine.getTextureManager().loadTexture(this.mFontTexture); this.getFontManager().loadFont(this.mFont); } @Override public Scene onLoadScene() { final FPSCounter fpsCounter = new FPSCounter(); this.mEngine.registerUpdateHandler(fpsCounter); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final ChangeableText elapsedText = new ChangeableText(100, 160, this.mFont, "Seconds elapsed:", "Seconds elapsed: XXXXX".length()); final ChangeableText fpsText = new ChangeableText(250, 240, this.mFont, "FPS:", "FPS: XXXXX".length()); scene.attachChild(elapsedText); scene.attachChild(fpsText); scene.registerUpdateHandler(new TimerHandler(1 / 20.0f, true, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { elapsedText.setText("Seconds elapsed: " + ChangeableTextExample.this.mEngine.getSecondsElapsedTotal()); fpsText.setText("FPS: " + fpsCounter.getFPS()); } })); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.sprite.batch.DynamicSpriteBatch; import org.anddev.andengine.entity.sprite.batch.SpriteBatch; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 14:27:22 - 14.06.2011 */ public class SpriteBatchExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, SpriteBatchExample.CAMERA_WIDTH, SpriteBatchExample.CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(SpriteBatchExample.CAMERA_WIDTH, SpriteBatchExample.CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* Calculate the coordinates for the face, so its centered on the camera. */ final int centerX = (SpriteBatchExample.CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (SpriteBatchExample.CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite faceSprite1 = new Sprite(-50, 0, this.mFaceTextureRegion); final Sprite faceSprite2 = new Sprite(50, 0, this.mFaceTextureRegion); faceSprite1.setScale(2); faceSprite2.setRotation(45); /* Create the face and add it to the scene. */ final SpriteBatch dynamicSpriteBatch = new DynamicSpriteBatch(this.mBitmapTextureAtlas, 2) { @Override protected boolean onUpdateSpriteBatch() { this.draw(faceSprite1); this.draw(faceSprite2); return true; } }; final SpriteBatch staticSpriteBatch = new SpriteBatch(this.mBitmapTextureAtlas, 2); staticSpriteBatch.draw(this.mFaceTextureRegion, -50, 0, this.mFaceTextureRegion.getWidth(), this.mFaceTextureRegion.getHeight(), 2, 2); staticSpriteBatch.draw(this.mFaceTextureRegion, 50, 0, this.mFaceTextureRegion.getWidth(), this.mFaceTextureRegion.getHeight(), 45); staticSpriteBatch.submit(); dynamicSpriteBatch.setPosition(centerX, centerY - 50); staticSpriteBatch.setPosition(centerX, centerY + 50); scene.attachChild(dynamicSpriteBatch); scene.attachChild(staticSpriteBatch); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.text.Text; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.font.StrokeFont; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import android.graphics.Color; import android.graphics.Typeface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 22:49:43 - 26.07.2010 */ public class StrokeFontExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int FONT_SIZE = 48; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mFontTexture; private BitmapTextureAtlas mStrokeFontTexture; private BitmapTextureAtlas mStrokeOnlyFontTexture; private Font mFont; private StrokeFont mStrokeFont; private StrokeFont mStrokeOnlyFont; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mStrokeFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mStrokeOnlyFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), FONT_SIZE, true, Color.BLACK); this.mStrokeFont = new StrokeFont(this.mStrokeFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), FONT_SIZE, true, Color.BLACK, 2, Color.WHITE); this.mStrokeOnlyFont = new StrokeFont(this.mStrokeOnlyFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), FONT_SIZE, true, Color.BLACK, 2, Color.WHITE, true); this.mEngine.getTextureManager().loadTextures(this.mFontTexture, this.mStrokeFontTexture, this.mStrokeOnlyFontTexture); this.getFontManager().loadFonts(this.mFont, this.mStrokeFont, this.mStrokeOnlyFont); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final Text textNormal = new Text(100, 100, this.mFont, "Just some normal Text."); final Text textStroke = new Text(100, 200, this.mStrokeFont, "Text with fill and stroke."); final Text textStrokeOnly = new Text(100, 300, this.mStrokeOnlyFont, "Text with stroke only."); scene.attachChild(textNormal); scene.attachChild(textStroke); scene.attachChild(textStrokeOnly); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.Entity; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.entity.util.ScreenCapture; import org.anddev.andengine.entity.util.ScreenCapture.IScreenCaptureCallback; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.util.FileUtils; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class RectangleExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final ScreenCapture screenCapture = new ScreenCapture(); scene.attachChild(screenCapture); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pSceneTouchEvent.isActionDown()) { screenCapture.capture(180, 60, 360, 360, FileUtils.getAbsolutePathOnExternalStorage(RectangleExample.this, "Screen_" + System.currentTimeMillis() + ".png"), new IScreenCaptureCallback() { @Override public void onScreenCaptured(final String pFilePath) { RectangleExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(RectangleExample.this, "Screenshot: " + pFilePath + " taken!", Toast.LENGTH_SHORT).show(); } }); } @Override public void onScreenCaptureFailed(final String pFilePath, final Exception pException) { RectangleExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(RectangleExample.this, "FAILED capturing Screenshot: " + pFilePath + " !", Toast.LENGTH_SHORT).show(); } }); } }); } return true; } }); scene.setBackground(new ColorBackground(0, 0, 0)); /* Create the rectangles. */ final Rectangle rect1 = this.makeColoredRectangle(-180, -180, 1, 0, 0); final Rectangle rect2 = this.makeColoredRectangle(0, -180, 0, 1, 0); final Rectangle rect3 = this.makeColoredRectangle(0, 0, 0, 0, 1); final Rectangle rect4 = this.makeColoredRectangle(-180, 0, 1, 1, 0); final Entity rectangleGroup = new Entity(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2); rectangleGroup.attachChild(rect1); rectangleGroup.attachChild(rect2); rectangleGroup.attachChild(rect3); rectangleGroup.attachChild(rect4); scene.attachChild(rectangleGroup); return scene; } private Rectangle makeColoredRectangle(final float pX, final float pY, final float pRed, final float pGreen, final float pBlue) { final Rectangle coloredRect = new Rectangle(pX, pY, 180, 180); coloredRect.setColor(pRed, pGreen, pBlue); return coloredRect; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.augmentedreality.BaseAugmentedRealityGameActivity; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.sensor.orientation.IOrientationListener; import org.anddev.andengine.sensor.orientation.OrientationData; import org.anddev.andengine.util.Debug; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class AugmentedRealityHorizonExample extends BaseAugmentedRealityGameActivity implements IOrientationListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private Sprite mFace; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "If you don't see a sprite moving over the screen, try starting this while already being in Landscape orientation!!", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); // scene.setBackgroundEnabled(false); scene.setBackground(new ColorBackground(0.0f, 0.0f, 0.0f, 0.0f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; this.mFace = new Sprite(centerX, centerY, this.mFaceTextureRegion); scene.attachChild(this.mFace); return scene; } @Override public void onLoadComplete() { this.enableOrientationSensor(this); } @Override public void onOrientationChanged(final OrientationData pOrientationData) { final float roll = pOrientationData.getRoll(); Debug.d("Roll: " + pOrientationData.getRoll()); this.mFace.setPosition(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2 + (roll - 40) * 5); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.FixedStepPhysicsWorld; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import org.anddev.andengine.util.Debug; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 18:47:08 - 19.03.2010 */ public class PhysicsFixedStepExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private Scene mScene; private PhysicsWorld mPhysicsWorld; private int mFaceCount = 0; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add objects.", Toast.LENGTH_SHORT).show(); Toast.makeText(this, "The difference to the normal physics example is that here the simulation steps have a fixed size, which makes the simuation reproduceable.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new Engine(engineOptions); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mScene.setOnSceneTouchListener(this); this.mPhysicsWorld = new FixedStepPhysicsWorld(30, new Vector2(0, SensorManager.GRAVITY_EARTH), false, 3, 2); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); return this.mScene; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } @Override public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) { final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX(), pAccelerometerData.getY()); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerometerSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerometerSensor(); } // =========================================================== // Methods // =========================================================== private void addFace(final float pX, final float pY) { this.mFaceCount++; Debug.d("Faces: " + this.mFaceCount); final AnimatedSprite face; final Body body; final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); if(this.mFaceCount % 2 == 0) { face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } else { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, objectFixtureDef); } face.animate(200); this.mScene.attachChild(face); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.ui.activity.BaseGameActivity; import android.view.Menu; import android.view.MenuItem; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 22:10:28 - 11.04.2010 */ public abstract class BaseExample extends BaseGameActivity { // =========================================================== // Constants // =========================================================== private static final int MENU_TRACE = Menu.FIRST; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public boolean onCreateOptionsMenu(final Menu pMenu) { pMenu.add(Menu.NONE, MENU_TRACE, Menu.NONE, "Start Method Tracing"); return super.onCreateOptionsMenu(pMenu); } @Override public boolean onPrepareOptionsMenu(final Menu pMenu) { pMenu.findItem(MENU_TRACE).setTitle(this.mEngine.isMethodTracing() ? "Stop Method Tracing" : "Start Method Tracing"); return super.onPrepareOptionsMenu(pMenu); } @Override public boolean onMenuItemSelected(final int pFeatureId, final MenuItem pItem) { switch(pItem.getItemId()) { case MENU_TRACE: if(this.mEngine.isMethodTracing()) { this.mEngine.stopMethodTracing(); } else { this.mEngine.startMethodTracing("AndEngine_" + System.currentTimeMillis() + ".trace"); } return true; default: return super.onMenuItemSelected(pFeatureId, pItem); } } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.entity.primitive.Line; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.util.constants.PhysicsConstants; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.joints.RevoluteJointDef; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:47:08 - 19.03.2010 */ public class PhysicsRevoluteJointExample extends BasePhysicsJointExample { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Scene onLoadScene() { final Scene scene = super.onLoadScene(); this.initJoints(scene); Toast.makeText(this, "In this example, the revolute joints have their motor enabled.", Toast.LENGTH_LONG).show(); return scene; } // =========================================================== // Methods // =========================================================== private void initJoints(final Scene pScene) { final int centerX = CAMERA_WIDTH / 2; final int centerY = CAMERA_HEIGHT / 2; final int spriteWidth = this.mBoxFaceTextureRegion.getTileWidth(); final int spriteHeight = this.mBoxFaceTextureRegion.getTileHeight(); final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(10, 0.2f, 0.5f); for(int i = 0; i < 3; i++) { final float anchorFaceX = centerX - spriteWidth * 0.5f + 220 * (i - 1); final float anchorFaceY = centerY - spriteHeight * 0.5f; final AnimatedSprite anchorFace = new AnimatedSprite(anchorFaceX, anchorFaceY, this.mBoxFaceTextureRegion); final Body anchorBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, anchorFace, BodyType.StaticBody, objectFixtureDef); final AnimatedSprite movingFace = new AnimatedSprite(anchorFaceX, anchorFaceY + 90, this.mCircleFaceTextureRegion); final Body movingBody = PhysicsFactory.createCircleBody(this.mPhysicsWorld, movingFace, BodyType.DynamicBody, objectFixtureDef); anchorFace.animate(200); anchorFace.animate(200); final Line connectionLine = new Line(anchorFaceX + spriteWidth / 2, anchorFaceY + spriteHeight / 2, anchorFaceX + spriteWidth / 2, anchorFaceY + spriteHeight / 2); pScene.attachChild(connectionLine); pScene.attachChild(anchorFace); pScene.attachChild(movingFace); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(anchorFace, anchorBody, true, true){ @Override public void onUpdate(final float pSecondsElapsed) { super.onUpdate(pSecondsElapsed); final Vector2 movingBodyWorldCenter = movingBody.getWorldCenter(); connectionLine.setPosition(connectionLine.getX1(), connectionLine.getY1(), movingBodyWorldCenter.x * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT, movingBodyWorldCenter.y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT); } }); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(movingFace, movingBody, true, true)); final RevoluteJointDef revoluteJointDef = new RevoluteJointDef(); revoluteJointDef.initialize(anchorBody, movingBody, anchorBody.getWorldCenter()); revoluteJointDef.enableMotor = true; revoluteJointDef.motorSpeed = 10; revoluteJointDef.maxMotorTorque = 200; this.mPhysicsWorld.createJoint(revoluteJointDef); } } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.io.IOException; import java.io.InputStream; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.SmoothCamera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.ZoomState; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.ITexture; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.compressed.etc1.ETC1Texture; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TextureRegionFactory; import org.anddev.andengine.util.Debug; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ETC1TextureExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private SmoothCamera mSmoothCamera; private ITexture mTexture; private TextureRegion mHouseTextureRegion; private ZoomState mZoomState = ZoomState.NONE; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Click the top half of the screen to zoom in or the bottom half to zoom out!", Toast.LENGTH_LONG); this.mSmoothCamera = new SmoothCamera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT, 0, 0, 0.1f) { @Override public void onUpdate(final float pSecondsElapsed) { switch (ETC1TextureExample.this.mZoomState) { case IN: this.setZoomFactor(this.getZoomFactor() + 0.1f * pSecondsElapsed); break; case OUT: this.setZoomFactor(this.getZoomFactor() - 0.1f * pSecondsElapsed); break; } super.onUpdate(pSecondsElapsed); } }; return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mSmoothCamera)); } @Override public void onLoadResources() { try { this.mTexture = new ETC1Texture(TextureOptions.BILINEAR) { @Override protected InputStream getInputStream() throws IOException { return ETC1TextureExample.this.getResources().openRawResource(R.raw.house_etc1); } }; this.mHouseTextureRegion = TextureRegionFactory.extractFromTexture(this.mTexture, 0, 0, 512, 512, true); this.mEngine.getTextureManager().loadTextures(this.mTexture); } catch (final Throwable e) { Debug.e(e); } } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mHouseTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mHouseTextureRegion.getHeight()) / 2; scene.attachChild(new Sprite(centerX, centerY, this.mHouseTextureRegion)); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if (pSceneTouchEvent.isActionDown() || pSceneTouchEvent.isActionMove()) { if(pSceneTouchEvent.getY() < CAMERA_HEIGHT / 2) { ETC1TextureExample.this.mZoomState = ZoomState.IN; } else { ETC1TextureExample.this.mZoomState = ZoomState.OUT; } } else { ETC1TextureExample.this.mZoomState = ZoomState.NONE; } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.io.IOException; import org.anddev.andengine.audio.music.Music; import org.anddev.andengine.audio.music.MusicFactory; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener; import org.anddev.andengine.entity.scene.Scene.ITouchArea; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.Debug; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 15:51:47 - 13.06.2010 */ public class MusicExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mNotesTextureRegion; private Music mMusic; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the notes to hear some Music.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera).setNeedsMusic(true)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mNotesTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "notes.png", 0, 0); MusicFactory.setAssetBasePath("mfx/"); try { this.mMusic = MusicFactory.createMusicFromAsset(this.mEngine.getMusicManager(), this, "wagner_the_ride_of_the_valkyries.ogg"); this.mMusic.setLooping(true); } catch (final IOException e) { Debug.e(e); } this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int x = (CAMERA_WIDTH - this.mNotesTextureRegion.getWidth()) / 2; final int y = (CAMERA_HEIGHT - this.mNotesTextureRegion.getHeight()) / 2; final Sprite notes = new Sprite(x, y, this.mNotesTextureRegion); scene.attachChild(notes); scene.registerTouchArea(notes); scene.setOnAreaTouchListener(new IOnAreaTouchListener() { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { if(MusicExample.this.mMusic.isPlaying()) { MusicExample.this.mMusic.pause(); } else { MusicExample.this.mMusic.play(); } } return true; } }); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.Scene.ITouchArea; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.IShape; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.extension.physics.box2d.util.constants.PhysicsConstants; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import org.anddev.andengine.util.Debug; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.joints.MouseJoint; import com.badlogic.gdx.physics.box2d.joints.MouseJointDef; /** * @author albrandroid * @author Nicolas Gramlich * @since 10:35:23 - 28.02.2011 */ public class PhysicsMouseJointExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener, IOnAreaTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final FixtureDef FIXTURE_DEF = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private Scene mScene; private PhysicsWorld mPhysicsWorld; private int mFaceCount = 0; private MouseJoint mMouseJointActive; private Body mGroundBody; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add objects.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new Engine(engineOptions); } @Override public void onLoadResources() { /* Textures. */ this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); /* TextureRegions. */ this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mScene.setOnSceneTouchListener(this); this.mScene.setOnAreaTouchListener(this); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); this.mGroundBody = this.mPhysicsWorld.createBody(new BodyDef()); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); return this.mScene; } @Override public void onLoadComplete() { this.mEngine.enableVibrator(this); } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { switch(pSceneTouchEvent.getAction()) { case TouchEvent.ACTION_DOWN: this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; case TouchEvent.ACTION_MOVE: if(this.mMouseJointActive != null) { final Vector2 vec = Vector2Pool.obtain(pSceneTouchEvent.getX() / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT, pSceneTouchEvent.getY() / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT); this.mMouseJointActive.setTarget(vec); Vector2Pool.recycle(vec); } return true; case TouchEvent.ACTION_UP: if(this.mMouseJointActive != null) { this.mPhysicsWorld.destroyJoint(this.mMouseJointActive); this.mMouseJointActive = null; } return true; } return false; } return false; } @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(pSceneTouchEvent.isActionDown()) { final IShape face = (IShape) pTouchArea; /* * If we have a active MouseJoint, we are just moving it around * instead of creating a second one. */ if(this.mMouseJointActive == null) { this.mEngine.vibrate(100); this.mMouseJointActive = this.createMouseJoint(face, pTouchAreaLocalX, pTouchAreaLocalY); } return true; } return false; } @Override public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) { final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX(), pAccelerometerData.getY()); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerometerSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerometerSensor(); } // =========================================================== // Methods // =========================================================== public MouseJoint createMouseJoint(final IShape pFace, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { final Body body = (Body) pFace.getUserData(); final MouseJointDef mouseJointDef = new MouseJointDef(); final Vector2 localPoint = Vector2Pool.obtain((pTouchAreaLocalX - pFace.getWidth() * 0.5f) / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT, (pTouchAreaLocalY - pFace.getHeight() * 0.5f) / PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT); this.mGroundBody.setTransform(localPoint, 0); mouseJointDef.bodyA = this.mGroundBody; mouseJointDef.bodyB = body; mouseJointDef.dampingRatio = 0.95f; mouseJointDef.frequencyHz = 30; mouseJointDef.maxForce = (200.0f * body.getMass()); mouseJointDef.collideConnected = true; mouseJointDef.target.set(body.getWorldPoint(localPoint)); Vector2Pool.recycle(localPoint); return (MouseJoint) this.mPhysicsWorld.createJoint(mouseJointDef); } private void addFace(final float pX, final float pY) { this.mFaceCount++; Debug.d("Faces: " + this.mFaceCount); final AnimatedSprite face; final Body body; if(this.mFaceCount % 2 == 0) { face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF); } else { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF); } face.setUserData(body); face.animate(200); this.mScene.registerTouchArea(face); this.mScene.attachChild(face); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.buffer.BufferObjectManager; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class UnloadResourcesExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mClickToUnloadTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mClickToUnloadTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "click_to_unload.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int x = (CAMERA_WIDTH - this.mClickToUnloadTextureRegion.getWidth()) / 2; final int y = (CAMERA_HEIGHT - this.mClickToUnloadTextureRegion.getHeight()) / 2; final Sprite clickToUnload = new Sprite(x, y, this.mClickToUnloadTextureRegion) { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { /* Completely remove all resources associated with this sprite. */ BufferObjectManager.getActiveInstance().unloadBufferObject(this.getVertexBuffer()); BufferObjectManager.getActiveInstance().unloadBufferObject(UnloadResourcesExample.this.mClickToUnloadTextureRegion.getTextureBuffer()); UnloadResourcesExample.this.mEngine.getTextureManager().unloadTexture(UnloadResourcesExample.this.mBitmapTextureAtlas); /* And remove the sprite from the Scene. */ final Sprite thisRef = this; UnloadResourcesExample.this.runOnUiThread(new Runnable() { @Override public void run() { scene.detachChild(thisRef); } }); return true; } }; scene.attachChild(clickToUnload); scene.registerTouchArea(clickToUnload); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.modifier.IEntityModifier.IEntityModifierListener; import org.anddev.andengine.entity.modifier.ParallelEntityModifier; import org.anddev.andengine.entity.modifier.RotationByModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.util.modifier.IModifier; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 21:42:39 - 06.07.2010 */ public class EntityModifierIrregularExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Shapes can have variable rotation and scale centers.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final AnimatedSprite face1 = new AnimatedSprite(centerX - 100, centerY, this.mFaceTextureRegion); face1.setRotationCenter(0, 0); face1.setScaleCenter(0, 0); face1.animate(100); final AnimatedSprite face2 = new AnimatedSprite(centerX + 100, centerY, this.mFaceTextureRegion); face2.animate(100); final SequenceEntityModifier entityModifier = new SequenceEntityModifier( new IEntityModifierListener() { @Override public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) { EntityModifierIrregularExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierIrregularExample.this, "Sequence started.", Toast.LENGTH_LONG).show(); } }); } @Override public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) { EntityModifierIrregularExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierIrregularExample.this, "Sequence finished.", Toast.LENGTH_LONG).show(); } }); } }, new ScaleModifier(2, 1.0f, 0.75f, 1.0f, 2.0f), new ScaleModifier(2, 0.75f, 2.0f, 2.0f, 1.25f), new ParallelEntityModifier( new ScaleModifier(3, 2.0f, 5.0f, 1.25f, 5.0f), new RotationByModifier(3, 180) ), new ParallelEntityModifier( new ScaleModifier(3, 5, 1), new RotationModifier(3, 180, 0) ) ); face1.registerEntityModifier(entityModifier); face2.registerEntityModifier(entityModifier.deepCopy()); scene.attachChild(face1); scene.attachChild(face2); /* Create some not-modified sprites, that act as fixed references to the modified ones. */ final AnimatedSprite face1Reference = new AnimatedSprite(centerX - 100, centerY, this.mFaceTextureRegion); final AnimatedSprite face2Reference = new AnimatedSprite(centerX + 100, centerY, this.mFaceTextureRegion); scene.attachChild(face1Reference); scene.attachChild(face2Reference); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.util; import java.util.Set; import org.anddev.andengine.examples.R; import android.app.Activity; 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.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; /** * This Activity appears as a dialog. It lists any paired devices and * devices detected in the area after discovery. When a device is chosen * by the user, the MAC address of the device is sent back to the parent * Activity in the result Intent. * * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:19:52 - 06.03.2011 */ public class BluetoothListDevicesActivity extends Activity { // =========================================================== // Constants // =========================================================== public static String EXTRA_DEVICE_ADDRESS = "device_address"; // =========================================================== // Fields // =========================================================== private BluetoothAdapter mBluetoothAdapter; private ArrayAdapter<String> mPairedDevicesArrayAdapter; private ArrayAdapter<String> mNewDevicesArrayAdapter; private final OnItemClickListener mDeviceClickListener = new OnItemClickListener() { @Override public void onItemClick(final AdapterView<?> pAdapterView, final View pView, final int pPosition, final long pID) { // Cancel discovery because it's costly and we're about to connect BluetoothListDevicesActivity.this.mBluetoothAdapter.cancelDiscovery(); // Get the device MAC address, which is the last 17 chars in the View final String info = ((TextView) pView).getText().toString(); final String address = info.substring(info.length() - 17); // Create the result Intent and include the MAC address final Intent intent = new Intent(); intent.putExtra(EXTRA_DEVICE_ADDRESS, address); // Set result and finish this Activity BluetoothListDevicesActivity.this.setResult(Activity.RESULT_OK, intent); BluetoothListDevicesActivity.this.finish(); } }; // The BroadcastReceiver that listens for discovered devices and // changes the title when discovery is finished private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context pContext, final Intent pIntent) { final String action = pIntent.getAction(); if (action.equals(BluetoothDevice.ACTION_FOUND)) { final BluetoothDevice device = pIntent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device.getBondState() != BluetoothDevice.BOND_BONDED) { BluetoothListDevicesActivity.this.mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) { BluetoothListDevicesActivity.this.setProgressBarIndeterminateVisibility(false); BluetoothListDevicesActivity.this.setTitle("Select a device to connect..."); if (BluetoothListDevicesActivity.this.mNewDevicesArrayAdapter.getCount() == 0) { BluetoothListDevicesActivity.this.mNewDevicesArrayAdapter.add("No devices found!"); } } } }; // =========================================================== // Constructors // =========================================================== @Override protected void onCreate(final Bundle pSavedInstanceState) { super.onCreate(pSavedInstanceState); this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); this.setContentView(R.layout.list_bluetooth_devices); // Set result CANCELED in case the user backs out this.setResult(Activity.RESULT_CANCELED); final Button scanButton = (Button) this.findViewById(R.id.button_scan); scanButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { BluetoothListDevicesActivity.this.discoverBluetoothDevices(); v.setVisibility(View.GONE); } }); this.mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); this.mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); final ListView pairedListView = (ListView) this.findViewById(R.id.paired_devices); pairedListView.setAdapter(this.mPairedDevicesArrayAdapter); pairedListView.setOnItemClickListener(this.mDeviceClickListener); final ListView newDevicesListView = (ListView) this.findViewById(R.id.new_devices); newDevicesListView.setAdapter(this.mNewDevicesArrayAdapter); newDevicesListView.setOnItemClickListener(this.mDeviceClickListener); // Register for broadcasts when a device is discovered IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(this.mReceiver, filter); // Register for broadcasts when discovery has finished filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); this.registerReceiver(this.mReceiver, filter); this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // Get a set of currently paired devices final Set<BluetoothDevice> pairedDevices = this.mBluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { this.findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); for (final BluetoothDevice device : pairedDevices) { this.mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } } else { this.mPairedDevicesArrayAdapter.add("No devices have been paired!"); } } @Override protected void onDestroy() { super.onDestroy(); // Make sure we're not doing discovery anymore if (this.mBluetoothAdapter != null) { this.mBluetoothAdapter.cancelDiscovery(); } // Unregister broadcast listeners this.unregisterReceiver(this.mReceiver); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== private void discoverBluetoothDevices() { this.setProgressBarIndeterminateVisibility(true); this.setTitle("Scanning for devices..."); this.findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE); if (this.mBluetoothAdapter.isDiscovering()) { this.mBluetoothAdapter.cancelDiscovery(); } this.mBluetoothAdapter.startDiscovery(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.particle.ParticleSystem; import org.anddev.andengine.entity.particle.emitter.PointParticleEmitter; import org.anddev.andengine.entity.particle.initializer.AccelerationInitializer; import org.anddev.andengine.entity.particle.initializer.ColorInitializer; import org.anddev.andengine.entity.particle.initializer.RotationInitializer; import org.anddev.andengine.entity.particle.initializer.VelocityInitializer; import org.anddev.andengine.entity.particle.modifier.AlphaModifier; import org.anddev.andengine.entity.particle.modifier.ColorModifier; import org.anddev.andengine.entity.particle.modifier.ExpireModifier; import org.anddev.andengine.entity.particle.modifier.ScaleModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class ParticleSystemCoolExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mParticleTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "particle_fire.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.0f, 0.0f, 0.0f)); /* Left to right Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(0, CAMERA_HEIGHT), 6, 10, 200, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(15, 22, -60, -90)); particleSystem.addParticleInitializer(new AccelerationInitializer(5, 15)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(1.0f, 0.0f, 0.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(11.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 3.5f)); particleSystem.addParticleModifier(new AlphaModifier(0.0f, 1.0f, 3.5f, 4.5f)); particleSystem.addParticleModifier(new ColorModifier(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 11.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 4.5f, 11.5f)); scene.attachChild(particleSystem); } /* Right to left Particle System. */ { final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(CAMERA_WIDTH - 32, CAMERA_HEIGHT), 8, 12, 200, this.mParticleTextureRegion); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-15, -22, -60, -90)); particleSystem.addParticleInitializer(new AccelerationInitializer(-5, 15)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleInitializer(new ColorInitializer(0.0f, 0.0f, 1.0f)); particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ExpireModifier(11.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 3.5f)); particleSystem.addParticleModifier(new AlphaModifier(0.0f, 1.0f, 3.5f, 4.5f)); particleSystem.addParticleModifier(new ColorModifier(0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 11.5f)); particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 4.5f, 11.5f)); scene.attachChild(particleSystem); } return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class AnimatedSpritesExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mSnapdragonTextureRegion; private TiledTextureRegion mHelicopterTextureRegion; private TiledTextureRegion mBananaTextureRegion; private TiledTextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(512, 256, TextureOptions.BILINEAR); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mSnapdragonTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "snapdragon_tiled.png", 0, 0, 4, 3); this.mHelicopterTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "helicopter_tiled.png", 400, 0, 2, 2); this.mBananaTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "banana_tiled.png", 0, 180, 4, 2); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 132, 180, 2, 1); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* Quickly twinkling face. */ final AnimatedSprite face = new AnimatedSprite(100, 50, this.mFaceTextureRegion); face.animate(100); scene.attachChild(face); /* Continuously flying helicopter. */ final AnimatedSprite helicopter = new AnimatedSprite(320, 50, this.mHelicopterTextureRegion); helicopter.animate(new long[] { 100, 100 }, 1, 2, true); scene.attachChild(helicopter); /* Snapdragon. */ final AnimatedSprite snapdragon = new AnimatedSprite(300, 200, this.mSnapdragonTextureRegion); snapdragon.animate(100); scene.attachChild(snapdragon); /* Funny banana. */ final AnimatedSprite banana = new AnimatedSprite(100, 220, this.mBananaTextureRegion); banana.animate(100); scene.attachChild(banana); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.Scene.ITouchArea; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.messages.client.ClientMessageFlags; import org.anddev.andengine.examples.adt.messages.server.ConnectionCloseServerMessage; import org.anddev.andengine.examples.adt.messages.server.ServerMessageFlags; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.IMessage; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.IServerMessage; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; import org.anddev.andengine.extension.multiplayer.protocol.client.IServerMessageHandler; import org.anddev.andengine.extension.multiplayer.protocol.client.SocketServerDiscoveryClient; import org.anddev.andengine.extension.multiplayer.protocol.client.SocketServerDiscoveryClient.ISocketServerDiscoveryClientListener; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.ServerConnector; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.SocketConnectionServerConnector; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.SocketConnectionServerConnector.ISocketConnectionServerConnectorListener; import org.anddev.andengine.extension.multiplayer.protocol.server.SocketServer; import org.anddev.andengine.extension.multiplayer.protocol.server.SocketServer.ISocketServerListener; import org.anddev.andengine.extension.multiplayer.protocol.server.SocketServerDiscoveryServer; import org.anddev.andengine.extension.multiplayer.protocol.server.SocketServerDiscoveryServer.ISocketServerDiscoveryServerListener; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.ClientConnector; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.SocketConnectionClientConnector; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.SocketConnectionClientConnector.ISocketConnectionClientConnectorListener; import org.anddev.andengine.extension.multiplayer.protocol.shared.IDiscoveryData.DefaultDiscoveryData; import org.anddev.andengine.extension.multiplayer.protocol.shared.SocketConnection; import org.anddev.andengine.extension.multiplayer.protocol.util.IPUtils; import org.anddev.andengine.extension.multiplayer.protocol.util.MessagePool; import org.anddev.andengine.extension.multiplayer.protocol.util.WifiUtils; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.Debug; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.util.SparseArray; import android.view.KeyEvent; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 17:10:24 - 19.06.2010 */ public class MultiplayerServerDiscoveryExample extends BaseExample implements ClientMessageFlags, ServerMessageFlags { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final int SERVER_PORT = 4444; private static final int DISCOVERY_PORT = 4445; private static final int LOCAL_PORT = 4446; private static final short FLAG_MESSAGE_SERVER_ADD_FACE = 1; private static final short FLAG_MESSAGE_SERVER_MOVE_FACE = FLAG_MESSAGE_SERVER_ADD_FACE + 1; private static final int DIALOG_CHOOSE_SERVER_OR_CLIENT_ID = 0; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private int mFaceIDCounter; private final SparseArray<Sprite> mFaces = new SparseArray<Sprite>(); private SocketServer<SocketConnectionClientConnector> mSocketServer; private ServerConnector<SocketConnection> mServerConnector; private final MessagePool<IMessage> mMessagePool = new MessagePool<IMessage>(); private SocketServerDiscoveryServer<DefaultDiscoveryData> mSocketServerDiscoveryServer; private SocketServerDiscoveryClient<DefaultDiscoveryData> mSocketServerDiscoveryClient; // =========================================================== // Constructors // =========================================================== public MultiplayerServerDiscoveryExample() { this.initMessagePool(); } private void initMessagePool() { this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_ADD_FACE, AddFaceServerMessage.class); this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_MOVE_FACE, MoveFaceServerMessage.class); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.showDialog(DIALOG_CHOOSE_SERVER_OR_CLIENT_ID); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* We allow only the server to actively send around messages. */ if(MultiplayerServerDiscoveryExample.this.mSocketServer != null) { scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pSceneTouchEvent.isActionDown()) { try { final AddFaceServerMessage addFaceServerMessage = (AddFaceServerMessage) MultiplayerServerDiscoveryExample.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_ADD_FACE); addFaceServerMessage.set(MultiplayerServerDiscoveryExample.this.mFaceIDCounter++, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); MultiplayerServerDiscoveryExample.this.mSocketServer.sendBroadcastServerMessage(addFaceServerMessage); MultiplayerServerDiscoveryExample.this.mMessagePool.recycleMessage(addFaceServerMessage); } catch (final IOException e) { Debug.e(e); } return true; } else { return false; } } }); scene.setOnAreaTouchListener(new IOnAreaTouchListener() { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { try { final Sprite face = (Sprite)pTouchArea; final Integer faceID = (Integer)face.getUserData(); final MoveFaceServerMessage moveFaceServerMessage = (MoveFaceServerMessage) MultiplayerServerDiscoveryExample.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_MOVE_FACE); moveFaceServerMessage.set(faceID, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); MultiplayerServerDiscoveryExample.this.mSocketServer.sendBroadcastServerMessage(moveFaceServerMessage); MultiplayerServerDiscoveryExample.this.mMessagePool.recycleMessage(moveFaceServerMessage); } catch (final IOException e) { Debug.e(e); return false; } return true; } }); scene.setTouchAreaBindingEnabled(true); } return scene; } @Override public void onLoadComplete() { } @Override protected Dialog onCreateDialog(final int pID) { switch(pID) { case DIALOG_CHOOSE_SERVER_OR_CLIENT_ID: return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Be Server or Client ...") .setMessage("For automatic ServerDiscovery to work, all devices need to be on the same WiFi!") .setCancelable(false) .setPositiveButton("Client", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerServerDiscoveryExample.this.initServerDiscovery(); } }) .setNeutralButton("Server", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerServerDiscoveryExample.this.toast("You can add and move sprites, which are only shown on the clients."); MultiplayerServerDiscoveryExample.this.initServer(); } }) .setNegativeButton("Both", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerServerDiscoveryExample.this.toast("You can add sprites and move them, by dragging them."); MultiplayerServerDiscoveryExample.this.initServerAndClient(); } }) .create(); default: return super.onCreateDialog(pID); } } @Override protected void onDestroy() { if(this.mSocketServer != null) { try { this.mSocketServer.sendBroadcastServerMessage(new ConnectionCloseServerMessage()); } catch (final IOException e) { Debug.e(e); } this.mSocketServer.terminate(); } if(this.mSocketServerDiscoveryServer != null) { this.mSocketServerDiscoveryServer.terminate(); } if(this.mServerConnector != null) { this.mServerConnector.terminate(); } if(this.mSocketServerDiscoveryClient != null) { this.mSocketServerDiscoveryClient.terminate(); } super.onDestroy(); } @Override public boolean onKeyUp(final int pKeyCode, final KeyEvent pEvent) { switch(pKeyCode) { case KeyEvent.KEYCODE_BACK: this.finish(); return true; } return super.onKeyUp(pKeyCode, pEvent); } // =========================================================== // Methods // =========================================================== public void addFace(final int pID, final float pX, final float pY) { final Scene scene = this.mEngine.getScene(); /* Create the face and add it to the scene. */ final Sprite face = new Sprite(0, 0, this.mFaceTextureRegion); face.setPosition(pX - face.getWidth() * 0.5f, pY - face.getHeight() * 0.5f); face.setUserData(pID); this.mFaces.put(pID, face); scene.registerTouchArea(face); scene.attachChild(face); } public void moveFace(final int pID, final float pX, final float pY) { /* Find and move the face. */ final Sprite face = this.mFaces.get(pID); face.setPosition(pX - face.getWidth() * 0.5f, pY - face.getHeight() * 0.5f); } private void initServerAndClient() { this.initServer(); /* Wait some time after the server has been started, so it actually can start up. */ try { Thread.sleep(500); } catch (final Throwable t) { Debug.e(t); } this.initServerDiscovery(); } private void initServer() { this.mSocketServer = new SocketServer<SocketConnectionClientConnector>(SERVER_PORT, new ExampleClientConnectorListener(), new ExampleServerStateListener()) { @Override protected SocketConnectionClientConnector newClientConnector(final SocketConnection pSocketConnection) throws IOException { return new SocketConnectionClientConnector(pSocketConnection); } }; this.mSocketServer.start(); try { final byte[] wifiIPv4Address = WifiUtils.getWifiIPv4AddressRaw(this); this.mSocketServerDiscoveryServer = new SocketServerDiscoveryServer<DefaultDiscoveryData>(DISCOVERY_PORT, new ExampleSocketServerDiscoveryServerListener()) { @Override protected DefaultDiscoveryData onCreateDiscoveryResponse() { return new DefaultDiscoveryData(wifiIPv4Address, SERVER_PORT); } }; this.mSocketServerDiscoveryServer.start(); } catch (final Throwable t) { Debug.e(t); } } private void initServerDiscovery() { try { this.mSocketServerDiscoveryClient = new SocketServerDiscoveryClient<DefaultDiscoveryData>(WifiUtils.getBroadcastIPAddressRaw(this), DISCOVERY_PORT, LOCAL_PORT, DefaultDiscoveryData.class, new ISocketServerDiscoveryClientListener<DefaultDiscoveryData>() { @Override public void onDiscovery(final SocketServerDiscoveryClient<DefaultDiscoveryData> pSocketServerDiscoveryClient, final DefaultDiscoveryData pDiscoveryData) { try { final String ipAddressAsString = IPUtils.ipAddressToString(pDiscoveryData.getServerIP()); MultiplayerServerDiscoveryExample.this.toast("DiscoveryClient: Server discovered at: " + ipAddressAsString + ":" + pDiscoveryData.getServerPort()); MultiplayerServerDiscoveryExample.this.initClient(ipAddressAsString, pDiscoveryData.getServerPort()); } catch (final UnknownHostException e) { MultiplayerServerDiscoveryExample.this.toast("DiscoveryClient: IPException: " + e); } } @Override public void onTimeout(final SocketServerDiscoveryClient<DefaultDiscoveryData> pSocketServerDiscoveryClient, final SocketTimeoutException pSocketTimeoutException) { Debug.e(pSocketTimeoutException); MultiplayerServerDiscoveryExample.this.toast("DiscoveryClient: Timeout: " + pSocketTimeoutException); } @Override public void onException(final SocketServerDiscoveryClient<DefaultDiscoveryData> pSocketServerDiscoveryClient, final Throwable pThrowable) { Debug.e(pThrowable); MultiplayerServerDiscoveryExample.this.toast("DiscoveryClient: Exception: " + pThrowable); } }); this.mSocketServerDiscoveryClient.discoverAsync(); } catch (final Throwable t) { Debug.e(t); } } private void initClient(final String pIPAddress, final int pPort) { try { this.mServerConnector = new SocketConnectionServerConnector(new SocketConnection(new Socket(pIPAddress, pPort)), new ExampleServerConnectorListener()); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_CONNECTION_CLOSE, ConnectionCloseServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { MultiplayerServerDiscoveryExample.this.finish(); } }); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_ADD_FACE, AddFaceServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final AddFaceServerMessage addFaceServerMessage = (AddFaceServerMessage)pServerMessage; MultiplayerServerDiscoveryExample.this.addFace(addFaceServerMessage.mID, addFaceServerMessage.mX, addFaceServerMessage.mY); } }); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_MOVE_FACE, MoveFaceServerMessage.class, new IServerMessageHandler<SocketConnection>() { @Override public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final MoveFaceServerMessage moveFaceServerMessage = (MoveFaceServerMessage)pServerMessage; MultiplayerServerDiscoveryExample.this.moveFace(moveFaceServerMessage.mID, moveFaceServerMessage.mX, moveFaceServerMessage.mY); } }); this.mServerConnector.getConnection().start(); } catch (final Throwable t) { Debug.e(t); } } private void log(final String pMessage) { Debug.d(pMessage); } private void toast(final String pMessage) { this.log(pMessage); this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MultiplayerServerDiscoveryExample.this, pMessage, Toast.LENGTH_SHORT).show(); } }); } // =========================================================== // Inner and Anonymous Classes // =========================================================== public static class AddFaceServerMessage extends ServerMessage { private int mID; private float mX; private float mY; public AddFaceServerMessage() { } public AddFaceServerMessage(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } public void set(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } @Override public short getFlag() { return FLAG_MESSAGE_SERVER_ADD_FACE; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mID = pDataInputStream.readInt(); this.mX = pDataInputStream.readFloat(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mID); pDataOutputStream.writeFloat(this.mX); pDataOutputStream.writeFloat(this.mY); } } public static class MoveFaceServerMessage extends ServerMessage { private int mID; private float mX; private float mY; public MoveFaceServerMessage() { } public MoveFaceServerMessage(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } public void set(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } @Override public short getFlag() { return FLAG_MESSAGE_SERVER_MOVE_FACE; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mID = pDataInputStream.readInt(); this.mX = pDataInputStream.readFloat(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mID); pDataOutputStream.writeFloat(this.mX); pDataOutputStream.writeFloat(this.mY); } } private class ExampleServerConnectorListener implements ISocketConnectionServerConnectorListener { @Override public void onStarted(final ServerConnector<SocketConnection> pConnector) { MultiplayerServerDiscoveryExample.this.toast("Client: Connected to server."); } @Override public void onTerminated(final ServerConnector<SocketConnection> pConnector) { MultiplayerServerDiscoveryExample.this.toast("Client: Disconnected from Server..."); MultiplayerServerDiscoveryExample.this.finish(); } } private class ExampleServerStateListener implements ISocketServerListener<SocketConnectionClientConnector> { @Override public void onStarted(final SocketServer<SocketConnectionClientConnector> pSocketServer) { MultiplayerServerDiscoveryExample.this.toast("Server: Started."); } @Override public void onTerminated(final SocketServer<SocketConnectionClientConnector> pSocketServer) { MultiplayerServerDiscoveryExample.this.toast("Server: Terminated."); } @Override public void onException(final SocketServer<SocketConnectionClientConnector> pSocketServer, final Throwable pThrowable) { Debug.e(pThrowable); MultiplayerServerDiscoveryExample.this.toast("Server: Exception: " + pThrowable); } } private class ExampleClientConnectorListener implements ISocketConnectionClientConnectorListener { @Override public void onStarted(final ClientConnector<SocketConnection> pConnector) { MultiplayerServerDiscoveryExample.this.toast("Server: Client connected: " + pConnector.getConnection().getSocket().getInetAddress().getHostAddress()); } @Override public void onTerminated(final ClientConnector<SocketConnection> pConnector) { MultiplayerServerDiscoveryExample.this.toast("Server: Client disconnected: " + pConnector.getConnection().getSocket().getInetAddress().getHostAddress()); } } public class ExampleSocketServerDiscoveryServerListener implements ISocketServerDiscoveryServerListener<DefaultDiscoveryData> { @Override public void onStarted(final SocketServerDiscoveryServer<DefaultDiscoveryData> pSocketServerDiscoveryServer) { MultiplayerServerDiscoveryExample.this.toast("DiscoveryServer: Started."); } @Override public void onTerminated(final SocketServerDiscoveryServer<DefaultDiscoveryData> pSocketServerDiscoveryServer) { MultiplayerServerDiscoveryExample.this.toast("DiscoveryServer: Terminated."); } @Override public void onException(final SocketServerDiscoveryServer<DefaultDiscoveryData> pSocketServerDiscoveryServer, final Throwable pThrowable) { Debug.e(pThrowable); MultiplayerServerDiscoveryExample.this.toast("DiscoveryServer: Exception: " + pThrowable); } @Override public void onDiscovered(final SocketServerDiscoveryServer<DefaultDiscoveryData> pSocketServerDiscoveryServer, final InetAddress pInetAddress, final int pPort) { MultiplayerServerDiscoveryExample.this.toast("DiscoveryServer: Discovered by: " + pInetAddress.getHostAddress() + ":" + pPort); } } }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.PathModifier; import org.anddev.andengine.entity.modifier.PathModifier.IPathModifierListener; import org.anddev.andengine.entity.modifier.PathModifier.Path; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.RepeatingSpriteBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.atlas.bitmap.source.AssetBitmapTextureAtlasSource; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 13:58:48 - 19.07.2010 */ public class RepeatingSpriteBackgroundExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private RepeatingSpriteBackground mGrassBackground; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mPlayerTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.DEFAULT); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mPlayerTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "player.png", 0, 0, 3, 4); this.mGrassBackground = new RepeatingSpriteBackground(CAMERA_WIDTH, CAMERA_HEIGHT, this.mEngine.getTextureManager(), new AssetBitmapTextureAtlasSource(this, "background_grass.png")); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(this.mGrassBackground); /* Calculate the coordinates for the face, so its centered on the camera. */ final int centerX = (CAMERA_WIDTH - this.mPlayerTextureRegion.getTileWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mPlayerTextureRegion.getTileHeight()) / 2; /* Create the sprite and add it to the scene. */ final AnimatedSprite player = new AnimatedSprite(centerX, centerY, 48, 64, this.mPlayerTextureRegion); final Path path = new Path(5).to(10, 10).to(10, CAMERA_HEIGHT - 74).to(CAMERA_WIDTH - 58, CAMERA_HEIGHT - 74).to(CAMERA_WIDTH - 58, 10).to(10, 10); player.registerEntityModifier(new LoopEntityModifier(new PathModifier(30, path, null, new IPathModifierListener() { @Override public void onPathStarted(final PathModifier pPathModifier, final IEntity pEntity) { } @Override public void onPathWaypointStarted(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) { switch(pWaypointIndex) { case 0: player.animate(new long[]{200, 200, 200}, 6, 8, true); break; case 1: player.animate(new long[]{200, 200, 200}, 3, 5, true); break; case 2: player.animate(new long[]{200, 200, 200}, 0, 2, true); break; case 3: player.animate(new long[]{200, 200, 200}, 9, 11, true); break; } } @Override public void onPathWaypointFinished(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) { } @Override public void onPathFinished(final PathModifier pPathModifier, final IEntity pEntity) { } }))); scene.attachChild(player); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import static org.anddev.andengine.extension.physics.box2d.util.constants.PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.shape.Shape; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.physics.box2d.PhysicsConnector; import org.anddev.andengine.extension.physics.box2d.PhysicsFactory; import org.anddev.andengine.extension.physics.box2d.PhysicsWorld; import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.sensor.accelerometer.AccelerometerData; import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener; import org.anddev.andengine.util.Debug; import android.hardware.SensorManager; import android.widget.Toast; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.badlogic.gdx.physics.box2d.PolygonShape; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 18:47:08 - 19.03.2010 */ public class PhysicsExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final FixtureDef FIXTURE_DEF = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f); // =========================================================== // Fields // =========================================================== private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mBoxFaceTextureRegion; private TiledTextureRegion mCircleFaceTextureRegion; private TiledTextureRegion mTriangleFaceTextureRegion; private TiledTextureRegion mHexagonFaceTextureRegion; private Scene mScene; private PhysicsWorld mPhysicsWorld; private int mFaceCount = 0; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to add objects.", Toast.LENGTH_LONG).show(); final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera); engineOptions.getTouchOptions().setRunOnUpdateThread(true); return new Engine(engineOptions); } @Override public void onLoadResources() { /* Textures. */ this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); /* TextureRegions. */ this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32 this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32 this.mTriangleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_triangle_tiled.png", 0, 64, 2, 1); // 64x32 this.mHexagonFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_hexagon_tiled.png", 0, 96, 2, 1); // 64x32 this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.mScene = new Scene(); this.mScene.setBackground(new ColorBackground(0, 0, 0)); this.mScene.setOnSceneTouchListener(this); this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false); final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2); final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2); final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT); final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); return this.mScene; } @Override public void onLoadComplete() { } @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(this.mPhysicsWorld != null) { if(pSceneTouchEvent.isActionDown()) { this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } } return false; } @Override public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) { final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX(), pAccelerometerData.getY()); this.mPhysicsWorld.setGravity(gravity); Vector2Pool.recycle(gravity); } @Override public void onResumeGame() { super.onResumeGame(); this.enableAccelerometerSensor(this); } @Override public void onPauseGame() { super.onPauseGame(); this.disableAccelerometerSensor(); } // =========================================================== // Methods // =========================================================== private void addFace(final float pX, final float pY) { this.mFaceCount++; Debug.d("Faces: " + this.mFaceCount); final AnimatedSprite face; final Body body; if(this.mFaceCount % 4 == 0) { face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion); body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF); } else if (this.mFaceCount % 4 == 1) { face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion); body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF); } else if (this.mFaceCount % 4 == 2) { face = new AnimatedSprite(pX, pY, this.mTriangleFaceTextureRegion); body = PhysicsExample.createTriangleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF); } else { face = new AnimatedSprite(pX, pY, this.mHexagonFaceTextureRegion); body = PhysicsExample.createHexagonBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF); } face.animate(200); this.mScene.attachChild(face); this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true)); } /** * Creates a {@link Body} based on a {@link PolygonShape} in the form of a triangle: * <pre> * /\ * /__\ * </pre> */ private static Body createTriangleBody(final PhysicsWorld pPhysicsWorld, final Shape pShape, final BodyType pBodyType, final FixtureDef pFixtureDef) { /* Remember that the vertices are relative to the center-coordinates of the Shape. */ final float halfWidth = pShape.getWidthScaled() * 0.5f / PIXEL_TO_METER_RATIO_DEFAULT; final float halfHeight = pShape.getHeightScaled() * 0.5f / PIXEL_TO_METER_RATIO_DEFAULT; final float top = -halfHeight; final float bottom = halfHeight; final float left = -halfHeight; final float centerX = 0; final float right = halfWidth; final Vector2[] vertices = { new Vector2(centerX, top), new Vector2(right, bottom), new Vector2(left, bottom) }; return PhysicsFactory.createPolygonBody(pPhysicsWorld, pShape, vertices, pBodyType, pFixtureDef); } /** * Creates a {@link Body} based on a {@link PolygonShape} in the form of a hexagon: * <pre> * /\ * / \ * | | * | | * \ / * \/ * </pre> */ private static Body createHexagonBody(final PhysicsWorld pPhysicsWorld, final Shape pShape, final BodyType pBodyType, final FixtureDef pFixtureDef) { /* Remember that the vertices are relative to the center-coordinates of the Shape. */ final float halfWidth = pShape.getWidthScaled() * 0.5f / PIXEL_TO_METER_RATIO_DEFAULT; final float halfHeight = pShape.getHeightScaled() * 0.5f / PIXEL_TO_METER_RATIO_DEFAULT; /* The top and bottom vertex of the hexagon are on the bottom and top of hexagon-sprite. */ final float top = -halfHeight; final float bottom = halfHeight; final float centerX = 0; /* The left and right vertices of the heaxgon are not on the edge of the hexagon-sprite, so we need to inset them a little. */ final float left = -halfWidth + 2.5f / PIXEL_TO_METER_RATIO_DEFAULT; final float right = halfWidth - 2.5f / PIXEL_TO_METER_RATIO_DEFAULT; final float higher = top + 8.25f / PIXEL_TO_METER_RATIO_DEFAULT; final float lower = bottom - 8.25f / PIXEL_TO_METER_RATIO_DEFAULT; final Vector2[] vertices = { new Vector2(centerX, top), new Vector2(right, higher), new Vector2(right, lower), new Vector2(centerX, bottom), new Vector2(left, lower), new Vector2(left, higher) }; return PhysicsFactory.createPolygonBody(pPhysicsWorld, pShape, vertices, pBodyType, pFixtureDef); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched; public class Config { // General configuration public static final int CONFERENCE_YEAR = 2013; // OAuth 2.0 related config public static final String APP_NAME = "GoogleIO-Android"; // TODO: Add your Google API key here. public static final String API_KEY = "YOUR_API_KEY_HERE"; // Conference API-specific config public static final String EVENT_ID = "googleio2013"; public static final String CONFERENCE_IMAGE_PREFIX_URL = "https://developers.google.com"; // Announcements public static final String ANNOUNCEMENTS_PLUS_ID = "111395306401981598462"; // Static file host for the map data public static final String GET_MAP_URL = "http://2013.ioschedmap.appspot.com/map.json"; // YouTube API config // TODO: Add your YouTube API key here. public static final String YOUTUBE_API_KEY = "YOUR_API_KEY_HERE"; // YouTube share URL public static final String YOUTUBE_SHARE_URL_PREFIX = "http://youtu.be/"; // Livestream captions config public static final String PRIMARY_LIVESTREAM_CAPTIONS_URL = "http://io-captions.appspot.com/?event=e1&android=t"; public static final String SECONDARY_LIVESTREAM_CAPTIONS_URL = "http://io-captions.appspot.com/?event=e2&android=t"; public static final String PRIMARY_LIVESTREAM_TRACK = "android"; public static final String SECONDARY_LIVESTREAM_TRACK = "chrome"; // Conference public WiFi AP parameters public static final String WIFI_SSID = "Google5G"; public static final String WIFI_PASSPHRASE = "gomobileio"; // GCM config // TODO: Add your GCM information here. public static final String GCM_SERVER_URL = "https://YOUR_GCM_APP_ID_HERE.appspot.com"; public static final String GCM_SENDER_ID = "YOUR_GCM_SENDER_ID_HERE"; public static final String GCM_API_KEY = "YOUR_GCM_API_KEY_HERE"; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.service; import android.app.Service; import android.content.Intent; import android.os.*; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.gcm.ServerUtilities; import com.google.android.apps.iosched.sync.SyncHelper; import com.google.android.apps.iosched.util.AccountUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import com.turbomanage.httpclient.AsyncCallback; import com.turbomanage.httpclient.HttpResponse; import com.turbomanage.httpclient.ParameterMap; import com.turbomanage.httpclient.android.AndroidHttpClient; import static com.google.android.apps.iosched.util.LogUtils.*; /** * Background {@link android.app.Service} that adds or removes sessions from your calendar via the * Conference API. * * @see com.google.android.apps.iosched.sync.SyncHelper */ public class ScheduleUpdaterService extends Service { private static final String TAG = makeLogTag(ScheduleUpdaterService.class); public static final String EXTRA_SESSION_ID = "com.google.android.apps.iosched.extra.SESSION_ID"; public static final String EXTRA_IN_SCHEDULE = "com.google.android.apps.iosched.extra.IN_SCHEDULE"; private static final int SCHEDULE_UPDATE_DELAY_MILLIS = 5000; private volatile Looper mServiceLooper; private volatile ServiceHandler mServiceHandler; private final LinkedList<Intent> mScheduleUpdates = new LinkedList<Intent>(); // Handler pattern copied from IntentService private final class ServiceHandler extends Handler { public ServiceHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { processPendingScheduleUpdates(); int numRemainingUpdates; synchronized (mScheduleUpdates) { numRemainingUpdates = mScheduleUpdates.size(); } if (numRemainingUpdates == 0) { notifyGcmDevices(); stopSelf(); } else { // More updates were added since the current pending set was processed. Reschedule // another pass. removeMessages(0); sendEmptyMessageDelayed(0, SCHEDULE_UPDATE_DELAY_MILLIS); } } } // private static class NotifyGcmDevicesTask extends AsyncTask<String, Void, Void> { // // @Override // protected Void doInBackground(String... params) { // BasicHttp // String gPlusID = params[0]; // Uri uri = new Uri(Config.GCM_SERVER_URL + "/send/" + gPlusID + "/sync_user"); // connection = (HttpURLConnection) url.openConnection(); // connection.setDoOutput(true); // connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // connection.setRequestMethod("POST"); // // request = new OutputStreamWriter(connection.getOutputStream()); // request.write(parameters); // request.flush(); // request.close(); // // } // } private void notifyGcmDevices() { String plusID = AccountUtils.getPlusProfileId(getApplicationContext()); if (plusID != null) { LOGI(TAG, "Sending device sync notification"); AndroidHttpClient httpClient = new AndroidHttpClient(Config.GCM_SERVER_URL); httpClient.setMaxRetries(1); ParameterMap params = httpClient.newParams() .add("key", Config.GCM_API_KEY) .add("squelch", ServerUtilities.getGcmId(this)); String path = "/send/" + plusID + "/sync_user"; httpClient.post(path, params, new AsyncCallback() { @Override public void onComplete(HttpResponse httpResponse) { LOGI(TAG, "Device sync notification sent"); } @Override public void onError(Exception e) { LOGW(TAG, "Device sync notification failed", e); } }); } else { LOGI(TAG, "No gPlusID, skipping device sync notification"); } } public ScheduleUpdaterService() { } @Override public void onCreate() { super.onCreate(); HandlerThread thread = new HandlerThread(ScheduleUpdaterService.class.getSimpleName()); thread.start(); mServiceLooper = thread.getLooper(); mServiceHandler = new ServiceHandler(mServiceLooper); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // When receiving a new intent, delay the schedule until 5 seconds from now. mServiceHandler.removeMessages(0); mServiceHandler.sendEmptyMessageDelayed(0, SCHEDULE_UPDATE_DELAY_MILLIS); // Remove pending updates involving this session ID. String sessionId = intent.getStringExtra(EXTRA_SESSION_ID); Iterator<Intent> updatesIterator = mScheduleUpdates.iterator(); while (updatesIterator.hasNext()) { Intent existingIntent = updatesIterator.next(); if (sessionId.equals(existingIntent.getStringExtra(EXTRA_SESSION_ID))) { updatesIterator.remove(); } } // Queue this schedule update. synchronized (mScheduleUpdates) { mScheduleUpdates.add(intent); } return START_REDELIVER_INTENT; } @Override public void onDestroy() { mServiceLooper.quit(); } @Override public IBinder onBind(Intent intent) { return null; } void processPendingScheduleUpdates() { try { // Operate on a local copy of the schedule update list so as not to block // the main thread adding to this list List<Intent> scheduleUpdates = new ArrayList<Intent>(); synchronized (mScheduleUpdates) { scheduleUpdates.addAll(mScheduleUpdates); mScheduleUpdates.clear(); } SyncHelper syncHelper = new SyncHelper(this); for (Intent updateIntent : scheduleUpdates) { String sessionId = updateIntent.getStringExtra(EXTRA_SESSION_ID); boolean inSchedule = updateIntent.getBooleanExtra(EXTRA_IN_SCHEDULE, false); LOGI(TAG, "addOrRemoveSessionFromSchedule:" + " sessionId=" + sessionId + " inSchedule=" + inSchedule); syncHelper.addOrRemoveSessionFromSchedule(this, sessionId, inSchedule); } } catch (IOException e) { // TODO: do something useful here, like revert the changes locally in the // content provider to maintain client/server sync LOGE(TAG, "Error processing schedule update", e); } } }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.service; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.provider.BaseColumns; import android.text.TextUtils; import android.text.format.DateUtils; import com.google.android.apps.dashclock.api.ExtensionData; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.util.PrefUtils; import com.google.android.apps.iosched.util.UIUtils; import java.util.ArrayList; import java.util.Formatter; import java.util.List; import java.util.Locale; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * An I/O 2013 extension for DashClock. */ public class DashClockExtension extends com.google.android.apps.dashclock.api.DashClockExtension { private static final String TAG = makeLogTag(DashClockExtension.class); private static final long MINUTE_MILLIS = 60 * 1000; private static final long NOW_BUFFER_TIME_MILLIS = 15 * MINUTE_MILLIS; private static final int MAX_BLOCKS = 5; private static final long CONTENT_CHANGE_DELAY_MILLIS = 5 * 1000; private static long mLastChange = 0; @Override protected void onInitialize(boolean isReconnect) { super.onInitialize(isReconnect); setUpdateWhenScreenOn(true); addWatchContentUris(new String[]{ ScheduleContract.Sessions.CONTENT_URI.toString() }); } @Override protected void onUpdateData(int reason) { if (reason == DashClockExtension.UPDATE_REASON_CONTENT_CHANGED) { long time = System.currentTimeMillis(); if (time < mLastChange + CONTENT_CHANGE_DELAY_MILLIS) { return; } mLastChange = time; } long currentTime = UIUtils.getCurrentTime(this); if (currentTime >= UIUtils.CONFERENCE_END_MILLIS) { publishUpdate(new ExtensionData() .visible(true) .icon(R.drawable.dashclock_extension) .status(getString(R.string.whats_on_thank_you_short)) .expandedTitle(getString(R.string.whats_on_thank_you_title)) .expandedBody(getString(R.string.whats_on_thank_you_subtitle)) .clickIntent(new Intent(this, HomeActivity.class))); return; } Cursor cursor = tryOpenBlocksCursor(); if (cursor == null) { LOGE(TAG, "Null blocks cursor, short-circuiting."); return; } StringBuilder buffer = new StringBuilder(); Formatter formatter = new Formatter(buffer, Locale.getDefault()); String firstBlockStartTime = null; List<String> blocks = new ArrayList<String>(); long lastBlockStart = 0; while (cursor.moveToNext()) { if (blocks.size() >= MAX_BLOCKS) { break; } final String type = cursor.getString(BlocksQuery.BLOCK_TYPE); final String blockTitle = cursor.getString(BlocksQuery.BLOCK_TITLE); final String blockType = cursor.getString(BlocksQuery.BLOCK_TYPE); final long blockStart = cursor.getLong(BlocksQuery.BLOCK_START); buffer.setLength(0); boolean showWeekday = !DateUtils.isToday(blockStart) && !UIUtils.isSameDayDisplay(lastBlockStart, blockStart, this); String blockStartTime = DateUtils.formatDateRange(this, formatter, blockStart, blockStart, DateUtils.FORMAT_SHOW_TIME | (showWeekday ? DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY : 0), PrefUtils.getDisplayTimeZone(this).getID()).toString(); lastBlockStart = blockStart; if (firstBlockStartTime == null) { firstBlockStartTime = blockStartTime; } if (ScheduleContract.Blocks.BLOCK_TYPE_SESSION.equals(type) || ScheduleContract.Blocks.BLOCK_TYPE_CODELAB.equals(type) || ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS.equals(blockType)) { final int numStarredSessions = cursor.getInt(BlocksQuery.NUM_STARRED_SESSIONS); if (numStarredSessions == 1) { // exactly 1 session starred String title = cursor.getString(BlocksQuery.STARRED_SESSION_TITLE); String room = cursor.getString(BlocksQuery.STARRED_SESSION_ROOM_NAME); if (room == null) { room = getString(R.string.unknown_room); } blocks.add(blockStartTime + ", " + room + " — " + title); } else { // 2 or more sessions starred String title = getString(R.string.schedule_conflict_title, numStarredSessions); blocks.add(blockStartTime + " — " + title); } } else if (ScheduleContract.Blocks.BLOCK_TYPE_KEYNOTE.equals(type)) { final String title = cursor.getString(BlocksQuery.STARRED_SESSION_TITLE); blocks.add(blockStartTime + " — " + title); } else { blocks.add(blockStartTime + " — " + blockTitle); } } cursor.close(); LOGD(TAG, blocks.size() + " blocks"); if (blocks.size() > 0) { publishUpdate(new ExtensionData() .visible(true) .icon(R.drawable.dashclock_extension) .status(firstBlockStartTime) .expandedTitle(blocks.get(0)) .expandedBody(TextUtils.join("\n", blocks.subList(1, blocks.size()))) .clickIntent(new Intent(this, HomeActivity.class))); } else { publishUpdate(new ExtensionData().visible(false)); } } private Cursor tryOpenBlocksCursor() { try { String liveStreamedOnlyBlocksSelection = "(" + (UIUtils.shouldShowLiveSessionsOnly(this) ? ScheduleContract.Blocks.BLOCK_TYPE + " NOT IN ('" + ScheduleContract.Blocks.BLOCK_TYPE_SESSION + "','" + ScheduleContract.Blocks.BLOCK_TYPE_CODELAB + "','" + ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS + "','" + ScheduleContract.Blocks.BLOCK_TYPE_FOOD + "')" + " OR " + ScheduleContract.Blocks.NUM_LIVESTREAMED_SESSIONS + ">1 " : "1==1") + ")"; String onlyStarredSelection = "(" + ScheduleContract.Blocks.BLOCK_TYPE + " NOT IN ('" + ScheduleContract.Blocks.BLOCK_TYPE_SESSION + "','" + ScheduleContract.Blocks.BLOCK_TYPE_CODELAB + "','" + ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS + "') " + " OR " + ScheduleContract.Blocks.NUM_STARRED_SESSIONS + ">0)"; String excludeSandbox = ScheduleContract.Blocks.BLOCK_TYPE + " != '" + ScheduleContract.Blocks.BLOCK_TYPE_SANDBOX + "'"; return getContentResolver().query(ScheduleContract.Blocks.CONTENT_URI, BlocksQuery.PROJECTION, ScheduleContract.Blocks.BLOCK_START + " >= ? AND " + liveStreamedOnlyBlocksSelection + " AND " + onlyStarredSelection + " AND " + excludeSandbox, new String[]{ Long.toString(UIUtils.getCurrentTime(this) - NOW_BUFFER_TIME_MILLIS) }, ScheduleContract.Blocks.DEFAULT_SORT); } catch (Exception e) { LOGE(TAG, "Error querying I/O 2013 content provider", e); return null; } } public interface BlocksQuery { String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Blocks.BLOCK_TITLE, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_TYPE, ScheduleContract.Blocks.NUM_STARRED_SESSIONS, ScheduleContract.Blocks.STARRED_SESSION_TITLE, ScheduleContract.Blocks.STARRED_SESSION_ROOM_NAME, ScheduleContract.Blocks.NUM_LIVESTREAMED_SESSIONS, }; int _ID = 0; int BLOCK_TITLE = 1; int BLOCK_START = 2; int BLOCK_TYPE = 3; int NUM_STARRED_SESSIONS = 4; int STARRED_SESSION_TITLE = 5; int STARRED_SESSION_ROOM_NAME = 6; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.service; import android.graphics.Bitmap; import android.provider.BaseColumns; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.ui.MapFragment; import com.google.android.apps.iosched.util.PrefUtils; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import android.app.AlarmManager; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.support.v4.app.NotificationCompat; import android.support.v4.app.TaskStackBuilder; import java.util.ArrayList; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * Background service to handle scheduling of starred session notification via * {@link android.app.AlarmManager}. */ public class SessionAlarmService extends IntentService { private static final String TAG = makeLogTag(SessionAlarmService.class); public static final String ACTION_NOTIFY_SESSION = "com.google.android.apps.iosched.action.NOTIFY_SESSION"; public static final String ACTION_SCHEDULE_STARRED_BLOCK = "com.google.android.apps.iosched.action.SCHEDULE_STARRED_BLOCK"; public static final String ACTION_SCHEDULE_ALL_STARRED_BLOCKS = "com.google.android.apps.iosched.action.SCHEDULE_ALL_STARRED_BLOCKS"; public static final String EXTRA_SESSION_START = "com.google.android.apps.iosched.extra.SESSION_START"; public static final String EXTRA_SESSION_END = "com.google.android.apps.iosched.extra.SESSION_END"; public static final String EXTRA_SESSION_ALARM_OFFSET = "com.google.android.apps.iosched.extra.SESSION_ALARM_OFFSET"; private static final int NOTIFICATION_ID = 100; // pulsate every 1 second, indicating a relatively high degree of urgency private static final int NOTIFICATION_LED_ON_MS = 100; private static final int NOTIFICATION_LED_OFF_MS = 1000; private static final int NOTIFICATION_ARGB_COLOR = 0xff0088ff; // cyan private static final long MILLI_TEN_MINUTES = 600000; private static final long MILLI_ONE_MINUTE = 60000; private static final long UNDEFINED_ALARM_OFFSET = -1; private static final long UNDEFINED_VALUE = -1; public SessionAlarmService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { final String action = intent.getAction(); if (ACTION_SCHEDULE_ALL_STARRED_BLOCKS.equals(action)) { scheduleAllStarredBlocks(); return; } final long sessionStart = intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_START, UNDEFINED_VALUE); if (sessionStart == UNDEFINED_VALUE) return; final long sessionEnd = intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_END, UNDEFINED_VALUE); if (sessionEnd == UNDEFINED_VALUE) return; final long sessionAlarmOffset = intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, UNDEFINED_ALARM_OFFSET); if (ACTION_NOTIFY_SESSION.equals(action)) { notifySession(sessionStart, sessionEnd, sessionAlarmOffset); } else if (ACTION_SCHEDULE_STARRED_BLOCK.equals(action)) { scheduleAlarm(sessionStart, sessionEnd, sessionAlarmOffset); } } private void scheduleAlarm(final long sessionStart, final long sessionEnd, final long alarmOffset) { NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.cancel(NOTIFICATION_ID); final long currentTime = UIUtils.getCurrentTime(this); // If the session is already started, do not schedule system notification. if (currentTime > sessionStart) return; // By default, sets alarm to go off at 10 minutes before session start time. If alarm // offset is provided, alarm is set to go off by that much time from now. long alarmTime; if (alarmOffset == UNDEFINED_ALARM_OFFSET) { alarmTime = sessionStart - MILLI_TEN_MINUTES; } else { alarmTime = currentTime + alarmOffset; } final Intent notifIntent = new Intent( ACTION_NOTIFY_SESSION, null, this, SessionAlarmService.class); // Setting data to ensure intent's uniqueness for different session start times. notifIntent.setData( new Uri.Builder().authority("com.google.android.apps.iosched") .path(String.valueOf(sessionStart)).build()); notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart); notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd); notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, alarmOffset); PendingIntent pi = PendingIntent.getService(this, 0, notifIntent, PendingIntent.FLAG_CANCEL_CURRENT); final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); // Schedule an alarm to be fired to notify user of added sessions are about to begin. am.set(AlarmManager.RTC_WAKEUP, alarmTime, pi); } // Starred sessions are about to begin. Constructs and triggers system notification. private void notifySession(final long sessionStart, final long sessionEnd, final long alarmOffset) { long currentTime; if (sessionStart < (currentTime = UIUtils.getCurrentTime(this))) return; // Avoid repeated notifications. if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock( this, ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd))) { return; } final ContentResolver cr = getContentResolver(); final Uri starredBlockUri = ScheduleContract.Blocks.buildStarredSessionsUri( ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd) ); Cursor c = cr.query(starredBlockUri, SessionDetailQuery.PROJECTION, null, null, null); int starredCount = 0; ArrayList<String> starredSessionTitles = new ArrayList<String>(); ArrayList<String> starredSessionRoomIds = new ArrayList<String>(); String sessionId = null; // needed to get session track icon while (c.moveToNext()) { sessionId = c.getString(SessionDetailQuery.SESSION_ID); starredCount = c.getInt(SessionDetailQuery.NUM_STARRED_SESSIONS); starredSessionTitles.add(c.getString(SessionDetailQuery.SESSION_TITLE)); starredSessionRoomIds.add(c.getString(SessionDetailQuery.ROOM_ID)); } if (starredCount < 1) { return; } // Generates the pending intent which gets fired when the user taps on the notification. // NOTE: Use TaskStackBuilder to comply with Android's design guidelines // related to navigation from notifications. PendingIntent pi = TaskStackBuilder.create(this) .addNextIntent(new Intent(this, HomeActivity.class)) .addNextIntent(new Intent(Intent.ACTION_VIEW, starredBlockUri)) .getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT); final Resources res = getResources(); String contentText; int minutesLeft = (int) (sessionStart - currentTime + 59000) / 60000; if (minutesLeft < 1) { minutesLeft = 1; } if (starredCount == 1) { contentText = res.getString(R.string.session_notification_text_1, minutesLeft); } else { contentText = res.getQuantityString(R.plurals.session_notification_text, starredCount - 1, minutesLeft, starredCount - 1); } NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this) .setContentTitle(starredSessionTitles.get(0)) .setContentText(contentText) .setTicker(res.getQuantityString(R.plurals.session_notification_ticker, starredCount, starredCount)) .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE) .setLights( SessionAlarmService.NOTIFICATION_ARGB_COLOR, SessionAlarmService.NOTIFICATION_LED_ON_MS, SessionAlarmService.NOTIFICATION_LED_OFF_MS) .setSmallIcon(R.drawable.ic_stat_notification) .setContentIntent(pi) .setPriority(Notification.PRIORITY_MAX) .setAutoCancel(true); if (starredCount == 1) { // get the track icon to show as the notification big picture Uri tracksUri = ScheduleContract.Sessions.buildTracksDirUri(sessionId); Cursor tracksCursor = cr.query(tracksUri, SessionTrackQuery.PROJECTION, null, null, null); if (tracksCursor.moveToFirst()) { String trackName = tracksCursor.getString(SessionTrackQuery.TRACK_NAME); int trackColour = tracksCursor.getInt(SessionTrackQuery.TRACK_COLOR); Bitmap trackIcon = UIUtils.getTrackIconSync(getApplicationContext(), trackName, trackColour); if (trackIcon != null) { notifBuilder.setLargeIcon(trackIcon); } } } if (minutesLeft > 5) { notifBuilder.addAction(R.drawable.ic_alarm_holo_dark, String.format(res.getString(R.string.snooze_x_min), 5), createSnoozeIntent(sessionStart, sessionEnd, 5)); } if (starredCount == 1 && PrefUtils.isAttendeeAtVenue(this)) { notifBuilder.addAction(R.drawable.ic_map_holo_dark, res.getString(R.string.title_map), createRoomMapIntent(starredSessionRoomIds.get(0))); } NotificationCompat.InboxStyle richNotification = new NotificationCompat.InboxStyle( notifBuilder) .setBigContentTitle(res.getQuantityString(R.plurals.session_notification_title, starredCount, minutesLeft, starredCount)); // Adds starred sessions starting at this time block to the notification. for (int i = 0; i < starredCount; i++) { richNotification.addLine(starredSessionTitles.get(i)); } NotificationManager nm = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); nm.notify(NOTIFICATION_ID, richNotification.build()); } private PendingIntent createSnoozeIntent(final long sessionStart, final long sessionEnd, final int snoozeMinutes) { Intent scheduleIntent = new Intent( SessionAlarmService.ACTION_SCHEDULE_STARRED_BLOCK, null, this, SessionAlarmService.class); scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart); scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd); scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, snoozeMinutes * MILLI_ONE_MINUTE); return PendingIntent.getService(this, 0, scheduleIntent, PendingIntent.FLAG_CANCEL_CURRENT); } private PendingIntent createRoomMapIntent(final String roomId) { Intent mapIntent = new Intent(getApplicationContext(), UIUtils.getMapActivityClass(getApplicationContext())); mapIntent.putExtra(MapFragment.EXTRA_ROOM, roomId); return PendingIntent.getActivity(this, 0, mapIntent, 0); } private void scheduleAllStarredBlocks() { final ContentResolver cr = getContentResolver(); final Cursor c = cr.query(ScheduleContract.Sessions.CONTENT_STARRED_URI, new String[]{"distinct " + ScheduleContract.Sessions.BLOCK_START, ScheduleContract.Sessions.BLOCK_END}, null, null, null); if (c == null) { return; } while (c.moveToNext()) { final long sessionStart = c.getLong(0); final long sessionEnd = c.getLong(1); scheduleAlarm(sessionStart, sessionEnd, UNDEFINED_ALARM_OFFSET); } } public interface SessionDetailQuery { String[] PROJECTION = { ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Blocks.NUM_STARRED_SESSIONS, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.ROOM_ID }; int SESSION_ID = 0; int NUM_STARRED_SESSIONS = 1; int SESSION_TITLE = 2; int ROOM_ID = 3; } public interface SessionTrackQuery { String[] PROJECTION = { ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_COLOR }; int TRACK_ID = 0; int TRACK_NAME = 1; int TRACK_COLOR = 2; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.google.android.apps.iosched.service.SessionAlarmService; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * {@link BroadcastReceiver} to reinitialize {@link android.app.AlarmManager} for all starred * session blocks. */ public class SessionAlarmReceiver extends BroadcastReceiver { public static final String TAG = makeLogTag(SessionAlarmReceiver.class); @Override public void onReceive(Context context, Intent intent) { Intent scheduleIntent = new Intent( SessionAlarmService.ACTION_SCHEDULE_ALL_STARRED_BLOCKS, null, context, SessionAlarmService.class); context.startService(scheduleIntent); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.sync; import android.accounts.Account; import android.content.*; import android.database.Cursor; import android.net.ConnectivityManager; import android.os.Bundle; import android.os.RemoteException; import android.preference.PreferenceManager; import com.google.analytics.tracking.android.GAServiceManager; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.io.*; import com.google.android.apps.iosched.io.map.model.Tile; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.*; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.googledevelopers.Googledevelopers; import java.io.*; import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.Collection; import java.util.List; import com.larvalabs.svgandroid.SVG; import com.larvalabs.svgandroid.SVGParseException; import com.larvalabs.svgandroid.SVGParser; import com.turbomanage.httpclient.BasicHttpClient; import com.turbomanage.httpclient.ConsoleRequestLogger; import com.turbomanage.httpclient.HttpResponse; import com.turbomanage.httpclient.RequestLogger; import static com.google.android.apps.iosched.util.LogUtils.*; /** * A helper class for dealing with sync and other remote persistence operations. * All operations occur on the thread they're called from, so it's best to wrap * calls in an {@link android.os.AsyncTask}, or better yet, a * {@link android.app.Service}. */ public class SyncHelper { private static final String TAG = makeLogTag(SyncHelper.class); public static final int FLAG_SYNC_LOCAL = 0x1; public static final int FLAG_SYNC_REMOTE = 0x2; private static final int LOCAL_VERSION_CURRENT = 25; private static final String LOCAL_MAPVERSION_CURRENT = "\"vlh7Ig\""; private Context mContext; public SyncHelper(Context context) { mContext = context; } public static void requestManualSync(Account mChosenAccount) { Bundle b = new Bundle(); b.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); ContentResolver.requestSync( mChosenAccount, ScheduleContract.CONTENT_AUTHORITY, b); } /** * Loads conference information (sessions, rooms, tracks, speakers, etc.) * from a local static cache data and then syncs down data from the * Conference API. * * @param syncResult Optional {@link SyncResult} object to populate. * @throws IOException */ public void performSync(SyncResult syncResult, int flags) throws IOException { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); final int localVersion = prefs.getInt("local_data_version", 0); // Bulk of sync work, performed by executing several fetches from // local and online sources. final ContentResolver resolver = mContext.getContentResolver(); ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); LOGI(TAG, "Performing sync"); if ((flags & FLAG_SYNC_LOCAL) != 0) { final long startLocal = System.currentTimeMillis(); final boolean localParse = localVersion < LOCAL_VERSION_CURRENT; LOGD(TAG, "found localVersion=" + localVersion + " and LOCAL_VERSION_CURRENT=" + LOCAL_VERSION_CURRENT); // Only run local sync if there's a newer version of data available // than what was last locally-sync'd. if (localParse) { // Load static local data LOGI(TAG, "Local syncing rooms"); batch.addAll(new RoomsHandler(mContext).parse( JSONHandler.parseResource(mContext, R.raw.rooms))); LOGI(TAG, "Local syncing blocks"); batch.addAll(new BlocksHandler(mContext).parse( JSONHandler.parseResource(mContext, R.raw.common_slots))); LOGI(TAG, "Local syncing tracks"); batch.addAll(new TracksHandler(mContext).parse( JSONHandler.parseResource(mContext, R.raw.tracks))); LOGI(TAG, "Local syncing speakers"); batch.addAll(new SpeakersHandler(mContext).parseString( JSONHandler.parseResource(mContext, R.raw.speakers))); LOGI(TAG, "Local syncing sessions"); batch.addAll(new SessionsHandler(mContext).parseString( JSONHandler.parseResource(mContext, R.raw.sessions), JSONHandler.parseResource(mContext, R.raw.session_tracks))); LOGI(TAG, "Local syncing search suggestions"); batch.addAll(new SearchSuggestHandler(mContext).parse( JSONHandler.parseResource(mContext, R.raw.search_suggest))); LOGI(TAG, "Local syncing map"); MapPropertyHandler mapHandler = new MapPropertyHandler(mContext); batch.addAll(mapHandler.parse( JSONHandler.parseResource(mContext, R.raw.map))); //need to sync tile files before data is updated in content provider syncMapTiles(mapHandler.getTiles()); prefs.edit().putInt("local_data_version", LOCAL_VERSION_CURRENT).commit(); prefs.edit().putString("local_mapdata_version", LOCAL_MAPVERSION_CURRENT).commit(); if (syncResult != null) { ++syncResult.stats.numUpdates; // TODO: better way of indicating progress? ++syncResult.stats.numEntries; } } LOGD(TAG, "Local sync took " + (System.currentTimeMillis() - startLocal) + "ms"); try { // Apply all queued up batch operations for local data. resolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, batch); } catch (RemoteException e) { throw new RuntimeException("Problem applying batch operation", e); } catch (OperationApplicationException e) { throw new RuntimeException("Problem applying batch operation", e); } batch = new ArrayList<ContentProviderOperation>(); } if ((flags & FLAG_SYNC_REMOTE) != 0 && isOnline()) { try { Googledevelopers conferenceAPI = getConferenceAPIClient(); final long startRemote = System.currentTimeMillis(); LOGI(TAG, "Remote syncing announcements"); batch.addAll(new AnnouncementsFetcher(mContext).fetchAndParse()); LOGI(TAG, "Remote syncing speakers"); batch.addAll(new SpeakersHandler(mContext).fetchAndParse(conferenceAPI)); LOGI(TAG, "Remote syncing sessions"); batch.addAll(new SessionsHandler(mContext).fetchAndParse(conferenceAPI)); // Map sync batch.addAll(remoteSyncMapData(Config.GET_MAP_URL,prefs)); LOGD(TAG, "Remote sync took " + (System.currentTimeMillis() - startRemote) + "ms"); if (syncResult != null) { ++syncResult.stats.numUpdates; // TODO: better way of indicating progress? ++syncResult.stats.numEntries; } GAServiceManager.getInstance().dispatch(); // Sync feedback stuff LOGI(TAG, "Syncing session feedback"); batch.addAll(new FeedbackHandler(mContext).uploadNew(conferenceAPI)); } catch (GoogleJsonResponseException e) { if (e.getStatusCode() == 401) { LOGI(TAG, "Unauthorized; getting a new auth token.", e); if (syncResult != null) { ++syncResult.stats.numAuthExceptions; } AccountUtils.refreshAuthToken(mContext); } } // all other IOExceptions are thrown LOGI(TAG, "Sync complete"); } try { // Apply all queued up remaining batch operations (only remote content at this point). resolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, batch); // Update search index resolver.update(ScheduleContract.SearchIndex.CONTENT_URI, new ContentValues(), null, null); // Delete empty blocks Cursor emptyBlocksCursor = resolver.query(ScheduleContract.Blocks.CONTENT_URI, new String[]{ScheduleContract.Blocks.BLOCK_ID,ScheduleContract.Blocks.SESSIONS_COUNT}, ScheduleContract.Blocks.EMPTY_SESSIONS_SELECTION, null, null); batch = new ArrayList<ContentProviderOperation>(); int numDeletedEmptyBlocks = 0; while (emptyBlocksCursor.moveToNext()) { batch.add(ContentProviderOperation .newDelete(ScheduleContract.Blocks.buildBlockUri( emptyBlocksCursor.getString(0))) .build()); ++numDeletedEmptyBlocks; } emptyBlocksCursor.close(); resolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, batch); LOGD(TAG, "Deleted " + numDeletedEmptyBlocks + " empty session blocks."); } catch (RemoteException e) { throw new RuntimeException("Problem applying batch operation", e); } catch (OperationApplicationException e) { throw new RuntimeException("Problem applying batch operation", e); } } public void addOrRemoveSessionFromSchedule(Context context, String sessionId, boolean inSchedule) throws IOException { LOGI(TAG, "Updating session on user schedule: " + sessionId); Googledevelopers conferenceAPI = getConferenceAPIClient(); try { sendScheduleUpdate(conferenceAPI, context, sessionId, inSchedule); } catch (GoogleJsonResponseException e) { if (e.getDetails().getCode() == 401) { LOGI(TAG, "Unauthorized; getting a new auth token.", e); AccountUtils.refreshAuthToken(mContext); // Try request one more time with new credentials before giving up conferenceAPI = getConferenceAPIClient(); sendScheduleUpdate(conferenceAPI, context, sessionId, inSchedule); } } } private void sendScheduleUpdate(Googledevelopers conferenceAPI, Context context, String sessionId, boolean inSchedule) throws IOException { if (inSchedule) { conferenceAPI.users().events().sessions().update(Config.EVENT_ID, sessionId, null).execute(); } else { conferenceAPI.users().events().sessions().delete(Config.EVENT_ID, sessionId).execute(); } } private ArrayList<ContentProviderOperation> remoteSyncMapData(String urlString, SharedPreferences preferences) throws IOException { final String localVersion = preferences.getString("local_mapdata_version", null); ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); BasicHttpClient httpClient = new BasicHttpClient(); httpClient.setRequestLogger(mQuietLogger); httpClient.addHeader("If-None-Match", localVersion); LOGD(TAG,"Local map version: "+localVersion); HttpResponse response = httpClient.get(urlString, null); final int status = response.getStatus(); if (status == HttpURLConnection.HTTP_OK) { // Data has been updated, otherwise would have received HTTP_NOT_MODIFIED LOGI(TAG, "Remote syncing map data"); final List<String> etag = response.getHeaders().get("ETag"); if (etag != null && etag.size() > 0) { MapPropertyHandler handler = new MapPropertyHandler(mContext); batch.addAll(handler.parse(response.getBodyAsString())); syncMapTiles(handler.getTiles()); // save new etag as version preferences.edit().putString("local_mapdata_version", etag.get(0)).commit(); } } //else: no update return batch; } private boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService( Context.CONNECTIVITY_SERVICE); return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting(); } /** * Synchronise the map overlay files either from the local assets (if available) or from a remote url. * * @param collection Set of tiles containing a local filename and remote url. * @throws IOException */ private void syncMapTiles(Collection<Tile> collection) throws IOException, SVGParseException { //keep track of used files, unused files are removed ArrayList<String> usedTiles = Lists.newArrayList(); for(Tile tile : collection){ final String filename = tile.filename; final String url = tile.url; usedTiles.add(filename); if (!MapUtils.hasTile(mContext, filename)) { // copy or download the tile if it is not stored yet if (MapUtils.hasTileAsset(mContext, filename)) { // file already exists as an asset, copy it MapUtils.copyTileAsset(mContext, filename); } else { // download the file File tileFile = MapUtils.getTileFile(mContext, filename); BasicHttpClient httpClient = new BasicHttpClient(); httpClient.setRequestLogger(mQuietLogger); HttpResponse httpResponse = httpClient.get(url, null); writeFile(httpResponse.getBody(), tileFile); // ensure the file is valid SVG InputStream is = new FileInputStream(tileFile); SVG svg = SVGParser.getSVGFromInputStream(is); is.close(); } } } MapUtils.removeUnusedTiles(mContext, usedTiles); } /** * Write the byte array directly to a file. * @throws IOException */ private void writeFile(byte[] data, File file) throws IOException { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, false)); bos.write(data); bos.close(); } /** * A type of ConsoleRequestLogger that does not log requests and responses. */ private RequestLogger mQuietLogger = new ConsoleRequestLogger(){ @Override public void logRequest(HttpURLConnection uc, Object content) throws IOException { } @Override public void logResponse(HttpResponse res) { } }; private Googledevelopers getConferenceAPIClient() { HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new GsonFactory(); GoogleCredential credential = new GoogleCredential().setAccessToken(AccountUtils.getAuthToken(mContext)); // Note: The Googledevelopers API is unique, in that it requires an API key in addition to the client // ID normally embedded an an OAuth token. Most apps will use one or the other. return new Googledevelopers.Builder(httpTransport, jsonFactory, null) .setApplicationName(NetUtils.getUserAgent(mContext)) .setGoogleClientRequestInitializer(new CommonGoogleClientRequestInitializer(Config.API_KEY)) .setHttpRequestInitializer(credential) .build(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.sync; import android.app.Service; import android.content.Intent; import android.os.IBinder; /** * Service that handles sync. It simply instantiates a SyncAdapter and returns its IBinder. */ public class SyncService extends Service { private static final Object sSyncAdapterLock = new Object(); private static SyncAdapter sSyncAdapter = null; @Override public void onCreate() { synchronized (sSyncAdapterLock) { if (sSyncAdapter == null) { sSyncAdapter = new SyncAdapter(getApplicationContext(), false); } } } @Override public IBinder onBind(Intent intent) { return sSyncAdapter.getSyncAdapterBinder(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.sync; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.gms.auth.GoogleAuthUtil; import android.accounts.Account; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; /** * A simple {@link BroadcastReceiver} that triggers a sync. This is used by the GCM code to trigger * jittered syncs using {@link android.app.AlarmManager}. */ public class TriggerSyncReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String accountName = AccountUtils.getChosenAccountName(context); if (TextUtils.isEmpty(accountName)) { return; } ContentResolver.requestSync( AccountUtils.getChosenAccount(context), ScheduleContract.CONTENT_AUTHORITY, new Bundle()); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.sync; import com.google.android.apps.iosched.BuildConfig; import com.google.android.apps.iosched.util.AccountUtils; import android.accounts.Account; import android.content.AbstractThreadedSyncAdapter; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.Context; import android.content.SyncResult; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import android.widget.Toast; import java.io.IOException; import java.util.regex.Pattern; import static com.google.android.apps.iosched.util.LogUtils.*; /** * Sync adapter for Google I/O data */ public class SyncAdapter extends AbstractThreadedSyncAdapter { private static final String TAG = makeLogTag(SyncAdapter.class); private static final Pattern sSanitizeAccountNamePattern = Pattern.compile("(.).*?(.?)@"); private final Context mContext; private SyncHelper mSyncHelper; public SyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); mContext = context; //noinspection ConstantConditions,PointlessBooleanExpression if (!BuildConfig.DEBUG) { Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable throwable) { LOGE(TAG, "Uncaught sync exception, suppressing UI in release build.", throwable); } }); } } @Override public void onPerformSync(final Account account, Bundle extras, String authority, final ContentProviderClient provider, final SyncResult syncResult) { final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false); final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false); final boolean initialize = extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false); final String logSanitizedAccountName = sSanitizeAccountNamePattern .matcher(account.name).replaceAll("$1...$2@"); if (uploadOnly) { return; } LOGI(TAG, "Beginning sync for account " + logSanitizedAccountName + "," + " uploadOnly=" + uploadOnly + " manualSync=" + manualSync + " initialize=" + initialize); String chosenAccountName = AccountUtils.getChosenAccountName(mContext); boolean isAccountSet = !TextUtils.isEmpty(chosenAccountName); boolean isChosenAccount = isAccountSet && chosenAccountName.equals(account.name); if (isAccountSet) { ContentResolver.setIsSyncable(account, authority, isChosenAccount ? 1 : 0); } if (!isChosenAccount) { LOGW(TAG, "Tried to sync account " + logSanitizedAccountName + " but the chosen " + "account is actually " + chosenAccountName); ++syncResult.stats.numAuthExceptions; return; } // Perform a sync using SyncHelper if (mSyncHelper == null) { mSyncHelper = new SyncHelper(mContext); } try { mSyncHelper.performSync(syncResult, SyncHelper.FLAG_SYNC_LOCAL | SyncHelper.FLAG_SYNC_REMOTE); } catch (IOException e) { ++syncResult.stats.numIoExceptions; LOGE(TAG, "Error syncing data for I/O 2013.", e); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.appwidget; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.ui.SessionLivestreamActivity; import com.google.android.apps.iosched.ui.SimpleSectionedListAdapter; import com.google.android.apps.iosched.ui.SimpleSectionedListAdapter.Section; import com.google.android.apps.iosched.ui.TaskStackBuilderProxyActivity; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.apps.iosched.util.PrefUtils; import com.google.android.apps.iosched.util.UIUtils; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.os.Build; import android.provider.BaseColumns; import android.text.TextUtils; import android.text.format.DateUtils; import android.util.SparseBooleanArray; import android.util.SparseIntArray; import android.view.View; import android.widget.RemoteViews; import android.widget.RemoteViewsService; import java.util.ArrayList; import java.util.Formatter; import java.util.List; import java.util.Locale; import static com.google.android.apps.iosched.util.LogUtils.LOGV; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * This is the service that provides the factory to be bound to the collection service. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class ScheduleWidgetRemoteViewsService extends RemoteViewsService { @Override public RemoteViewsFactory onGetViewFactory(Intent intent) { return new WidgetRemoveViewsFactory(this.getApplicationContext()); } /** * This is the factory that will provide data to the collection widget. */ private static class WidgetRemoveViewsFactory implements RemoteViewsService.RemoteViewsFactory { private static final String TAG = makeLogTag(WidgetRemoveViewsFactory.class); private Context mContext; private Cursor mCursor; private SparseIntArray mPMap; private List<SimpleSectionedListAdapter.Section> mSections; private SparseBooleanArray mHeaderPositionMap; StringBuilder mBuffer = new StringBuilder(); Formatter mFormatter = new Formatter(mBuffer, Locale.getDefault()); public WidgetRemoveViewsFactory(Context context) { mContext = context; } public void onCreate() { // Since we reload the cursor in onDataSetChanged() which gets called immediately after // onCreate(), we do nothing here. } public void onDestroy() { if (mCursor != null) { mCursor.close(); } } public int getCount() { if (mCursor == null || !AccountUtils.isAuthenticated(mContext)) { return 0; } int size = mCursor.getCount() + mSections.size(); if (size < 10) { init(); size = mCursor.getCount() + mSections.size(); } LOGV(TAG, "size returned:" + size); return size; } public RemoteViews getViewAt(int position) { RemoteViews rv; boolean isSectionHeader = mHeaderPositionMap.get(position); int offset = mPMap.get(position); Intent homeIntent = new Intent(mContext, HomeActivity.class); if (isSectionHeader) { rv = new RemoteViews(mContext.getPackageName(), R.layout.list_item_schedule_header); Section section = mSections.get(offset - 1); rv.setTextViewText(R.id.list_item_schedule_header_textview, section.getTitle()); } else { int cursorPosition = position - offset; mCursor.moveToPosition(cursorPosition); rv = new RemoteViews(mContext.getPackageName(), R.layout.list_item_schedule_block_widget); final String type = mCursor.getString(BlocksQuery.BLOCK_TYPE); final String blockId = mCursor.getString(BlocksQuery.BLOCK_ID); final String blockTitle = mCursor.getString(BlocksQuery.BLOCK_TITLE); final String blockType = mCursor.getString(BlocksQuery.BLOCK_TYPE); final String blockMeta = mCursor.getString(BlocksQuery.BLOCK_META); final long blockStart = mCursor.getLong(BlocksQuery.BLOCK_START); final long blockEnd = mCursor.getLong(BlocksQuery.BLOCK_END); final Resources res = mContext.getResources(); rv.setTextViewText(R.id.block_endtime, null); if (ScheduleContract.Blocks.BLOCK_TYPE_SESSION.equals(type) || ScheduleContract.Blocks.BLOCK_TYPE_CODELAB.equals(type) || ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS.equals(blockType)) { final int numStarredSessions = mCursor.getInt(BlocksQuery.NUM_STARRED_SESSIONS); final String starredSessionId = mCursor .getString(BlocksQuery.STARRED_SESSION_ID); if (numStarredSessions == 0) { // No sessions starred rv.setTextViewText(R.id.block_title, mContext.getString( R.string.schedule_empty_slot_title_template, TextUtils.isEmpty(blockTitle) ? "" : (" " + blockTitle.toLowerCase()))); rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1_positive)); rv.setTextViewText(R.id.block_subtitle, mContext.getString( R.string.schedule_empty_slot_subtitle)); rv.setViewVisibility(R.id.extra_button, View.GONE); Intent fillIntent = TaskStackBuilderProxyActivity.getFillIntent( homeIntent, new Intent(Intent.ACTION_VIEW, ScheduleContract.Blocks .buildSessionsUri(blockId))); rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillIntent); } else if (numStarredSessions == 1) { // exactly 1 session starred final String starredSessionTitle = mCursor.getString(BlocksQuery.STARRED_SESSION_TITLE); String starredSessionSubtitle = mCursor.getString(BlocksQuery.STARRED_SESSION_ROOM_NAME); if (starredSessionSubtitle == null) { starredSessionSubtitle = mContext.getString(R.string.unknown_room); } // Determine if the session is in the past long currentTimeMillis = UIUtils.getCurrentTime(mContext); boolean conferenceEnded = currentTimeMillis > UIUtils.CONFERENCE_END_MILLIS; boolean blockEnded = currentTimeMillis > blockEnd; if (blockEnded && !conferenceEnded) { starredSessionSubtitle = mContext.getString(R.string.session_finished); } rv.setTextViewText(R.id.block_title, starredSessionTitle); rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1)); rv.setTextViewText(R.id.block_subtitle, starredSessionSubtitle); rv.setViewVisibility(R.id.extra_button, View.VISIBLE); Intent fillIntent = TaskStackBuilderProxyActivity.getFillIntent( homeIntent, new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions .buildSessionUri(starredSessionId))); rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillIntent); fillIntent = TaskStackBuilderProxyActivity.getFillIntent( homeIntent, new Intent(Intent.ACTION_VIEW, ScheduleContract.Blocks .buildSessionsUri(blockId))); rv.setOnClickFillInIntent(R.id.extra_button, fillIntent); } else { // 2 or more sessions starred rv.setTextViewText(R.id.block_title, mContext.getString(R.string.schedule_conflict_title, numStarredSessions)); rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1)); rv.setTextViewText(R.id.block_subtitle, mContext.getString(R.string.schedule_conflict_subtitle)); rv.setViewVisibility(R.id.extra_button, View.VISIBLE); Intent fillIntent = TaskStackBuilderProxyActivity.getFillIntent( homeIntent, new Intent(Intent.ACTION_VIEW, ScheduleContract.Blocks .buildStarredSessionsUri(blockId))); rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillIntent); fillIntent = TaskStackBuilderProxyActivity.getFillIntent( homeIntent, new Intent(Intent.ACTION_VIEW, ScheduleContract.Blocks .buildSessionsUri(blockId))); rv.setOnClickFillInIntent(R.id.extra_button, fillIntent); } rv.setTextColor(R.id.block_subtitle, res.getColor(R.color.body_text_2)); } else if (ScheduleContract.Blocks.BLOCK_TYPE_KEYNOTE.equals(type)) { long currentTimeMillis = UIUtils.getCurrentTime(mContext); boolean past = (currentTimeMillis > blockEnd && currentTimeMillis < UIUtils.CONFERENCE_END_MILLIS); boolean present = !past && (currentTimeMillis >= blockStart); boolean canViewStream = present && UIUtils.hasHoneycomb(); final String starredSessionId = mCursor .getString(BlocksQuery.STARRED_SESSION_ID); final String starredSessionTitle = mCursor.getString(BlocksQuery.STARRED_SESSION_TITLE); rv.setTextViewText(R.id.block_title, starredSessionTitle); rv.setTextViewText(R.id.block_subtitle, res.getString(R.string.keynote_room)); rv.setTextColor(R.id.block_title, canViewStream ? res.getColor(R.color.body_text_1) : res.getColor(R.color.body_text_disabled)); rv.setTextColor(R.id.block_subtitle, canViewStream ? res.getColor(R.color.body_text_2) : res.getColor(R.color.body_text_disabled)); rv.setViewVisibility(R.id.extra_button, View.GONE); if (canViewStream) { Intent fillIntent = TaskStackBuilderProxyActivity.getFillIntent( homeIntent, new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions .buildSessionUri(starredSessionId)) .setClass(mContext, SessionLivestreamActivity.class)); rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillIntent); } else { rv.setOnClickFillInIntent(R.id.list_item_middle_container, new Intent()); } } else { rv.setTextViewText(R.id.block_title, blockTitle); rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_disabled)); rv.setTextViewText(R.id.block_subtitle, blockMeta); rv.setTextColor(R.id.block_subtitle, res.getColor(R.color.body_text_disabled)); rv.setViewVisibility(R.id.extra_button, View.GONE); mBuffer.setLength(0); rv.setTextViewText(R.id.block_endtime, DateUtils.formatDateRange(mContext, mFormatter, blockEnd, blockEnd, DateUtils.FORMAT_SHOW_TIME, PrefUtils.getDisplayTimeZone(mContext).getID()).toString()); rv.setOnClickFillInIntent(R.id.list_item_middle_container, new Intent()); } mBuffer.setLength(0); rv.setTextViewText(R.id.block_time, DateUtils.formatDateRange(mContext, mFormatter, blockStart, blockStart, DateUtils.FORMAT_SHOW_TIME, PrefUtils.getDisplayTimeZone(mContext).getID()).toString()); } return rv; } public RemoteViews getLoadingView() { return null; } public int getViewTypeCount() { return 2; } public long getItemId(int position) { return position; } public boolean hasStableIds() { return true; } public void onDataSetChanged() { init(); } private void init() { if (mCursor != null) { mCursor.close(); } String liveStreamedOnlyBlocksSelection = "(" + (UIUtils.shouldShowLiveSessionsOnly(mContext) ? ScheduleContract.Blocks.BLOCK_TYPE + " NOT IN ('" + ScheduleContract.Blocks.BLOCK_TYPE_SESSION + "','" + ScheduleContract.Blocks.BLOCK_TYPE_CODELAB + "','" + ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS + "','" + ScheduleContract.Blocks.BLOCK_TYPE_FOOD + "')" + " OR " + ScheduleContract.Blocks.NUM_LIVESTREAMED_SESSIONS + ">1 " : "1==1") + ")"; String onlyStarredOfficeHoursSelection = "(" + ScheduleContract.Blocks.BLOCK_TYPE + " != '" + ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS + "' OR " + ScheduleContract.Blocks.NUM_STARRED_SESSIONS + ">0)"; String excludeSandbox = "("+ScheduleContract.Blocks.BLOCK_TYPE + " != '" + ScheduleContract.Blocks.BLOCK_TYPE_SANDBOX +"')"; mCursor = mContext.getContentResolver().query(ScheduleContract.Blocks.CONTENT_URI, BlocksQuery.PROJECTION, ScheduleContract.Blocks.BLOCK_END + " >= ? AND " + liveStreamedOnlyBlocksSelection + " AND " + onlyStarredOfficeHoursSelection + " AND " + excludeSandbox, new String[]{ Long.toString(UIUtils.getCurrentTime(mContext)) }, ScheduleContract.Blocks.DEFAULT_SORT); String displayTimeZone = PrefUtils.getDisplayTimeZone(mContext).getID(); mSections = new ArrayList<SimpleSectionedListAdapter.Section>(); mCursor.moveToFirst(); long previousTime = -1; long time; mPMap = new SparseIntArray(); mHeaderPositionMap = new SparseBooleanArray(); int offset = 0; int globalPosition = 0; while (!mCursor.isAfterLast()) { time = mCursor.getLong(BlocksQuery.BLOCK_START); if (!UIUtils.isSameDayDisplay(previousTime, time, mContext)) { mBuffer.setLength(0); mSections.add(new SimpleSectionedListAdapter.Section(mCursor.getPosition(), DateUtils.formatDateRange( mContext, mFormatter, time, time, DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY, displayTimeZone).toString())); ++offset; mHeaderPositionMap.put(globalPosition, true); mPMap.put(globalPosition, offset); ++globalPosition; } mHeaderPositionMap.put(globalPosition, false); mPMap.put(globalPosition, offset); ++globalPosition; previousTime = time; mCursor.moveToNext(); } LOGV(TAG, "Leaving init()"); } } public interface BlocksQuery { String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Blocks.BLOCK_ID, ScheduleContract.Blocks.BLOCK_TITLE, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Blocks.BLOCK_TYPE, ScheduleContract.Blocks.BLOCK_META, ScheduleContract.Blocks.NUM_STARRED_SESSIONS, ScheduleContract.Blocks.NUM_LIVESTREAMED_SESSIONS, ScheduleContract.Blocks.STARRED_SESSION_ID, ScheduleContract.Blocks.STARRED_SESSION_TITLE, ScheduleContract.Blocks.STARRED_SESSION_ROOM_NAME, }; int _ID = 0; int BLOCK_ID = 1; int BLOCK_TITLE = 2; int BLOCK_START = 3; int BLOCK_END = 4; int BLOCK_TYPE = 5; int BLOCK_META = 6; int NUM_STARRED_SESSIONS = 7; int NUM_LIVESTREAMED_SESSIONS = 8; int STARRED_SESSION_ID = 9; int STARRED_SESSION_TITLE = 10; int STARRED_SESSION_ROOM_NAME = 11; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.appwidget; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.sync.SyncHelper; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.ui.TaskStackBuilderProxyActivity; import com.google.android.apps.iosched.util.AccountUtils; import android.accounts.Account; import android.annotation.TargetApi; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.ContentObserver; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.os.HandlerThread; import android.widget.RemoteViews; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * The app widget's AppWidgetProvider. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class ScheduleWidgetProvider extends AppWidgetProvider { private static final String TAG = makeLogTag(ScheduleWidgetProvider.class); private static final String REFRESH_ACTION = "com.google.android.apps.iosched.appwidget.action.REFRESH"; private static final String EXTRA_PERFORM_SYNC = "com.google.android.apps.iosched.appwidget.extra.PERFORM_SYNC"; public static Intent getRefreshBroadcastIntent(Context context, boolean performSync) { return new Intent(REFRESH_ACTION) .setComponent(new ComponentName(context, ScheduleWidgetProvider.class)) .putExtra(EXTRA_PERFORM_SYNC, performSync); } @Override public void onReceive(final Context context, Intent widgetIntent) { final String action = widgetIntent.getAction(); if (REFRESH_ACTION.equals(action)) { final boolean shouldSync = widgetIntent.getBooleanExtra(EXTRA_PERFORM_SYNC, false); // Trigger sync Account chosenAccount = AccountUtils.getChosenAccount(context); if (shouldSync && chosenAccount != null) { SyncHelper.requestManualSync(chosenAccount); } // Notify the widget that the list view needs to be updated. final AppWidgetManager mgr = AppWidgetManager.getInstance(context); final ComponentName cn = new ComponentName(context, ScheduleWidgetProvider.class); mgr.notifyAppWidgetViewDataChanged(mgr.getAppWidgetIds(cn), R.id.widget_schedule_list); } super.onReceive(context, widgetIntent); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { final boolean isAuthenticated = AccountUtils.isAuthenticated(context); for (int appWidgetId : appWidgetIds) { // Specify the service to provide data for the collection widget. Note that we need to // embed the appWidgetId via the data otherwise it will be ignored. final Intent intent = new Intent(context, ScheduleWidgetRemoteViewsService.class) .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); final RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget); rv.setRemoteAdapter(appWidgetId, R.id.widget_schedule_list, intent); // Set the empty view to be displayed if the collection is empty. It must be a sibling // view of the collection view. rv.setEmptyView(R.id.widget_schedule_list, android.R.id.empty); rv.setTextViewText(android.R.id.empty, context.getResources().getString(isAuthenticated ? R.string.empty_widget_text : R.string.empty_widget_text_signed_out)); final PendingIntent refreshPendingIntent = PendingIntent.getBroadcast(context, 0, getRefreshBroadcastIntent(context, true), PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.widget_refresh_button, refreshPendingIntent); final Intent onClickIntent = TaskStackBuilderProxyActivity.getTemplate(context); final PendingIntent onClickPendingIntent = PendingIntent.getActivity(context, 0, onClickIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setPendingIntentTemplate(R.id.widget_schedule_list, onClickPendingIntent); final Intent openAppIntent = new Intent(context, HomeActivity.class) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); final PendingIntent openAppPendingIntent = PendingIntent.getActivity(context, 0, openAppIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setOnClickPendingIntent(R.id.widget_logo, openAppPendingIntent); appWidgetManager.updateAppWidget(appWidgetId, rv); } super.onUpdate(context, appWidgetManager, appWidgetIds); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm; import com.google.android.gcm.GCMBroadcastReceiver; import android.content.Context; /** * @author trevorjohns@google.com (Trevor Johns) */ public class GCMRedirectedBroadcastReceiver extends GCMBroadcastReceiver { /** * Gets the class name of the intent service that will handle GCM messages. * * Used to override class name, so that GCMIntentService can live in a * subpackage. */ @Override protected String getGCMIntentServiceClassName(Context context) { return GCMIntentService.class.getCanonicalName(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm; import android.util.Log; import com.google.android.apps.iosched.Config; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import com.google.android.apps.iosched.util.AccountUtils; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.Map.Entry; import static com.google.android.apps.iosched.util.LogUtils.*; /** * Helper class used to communicate with the demo server. */ public final class ServerUtilities { private static final String TAG = makeLogTag("GCMs"); private static final String PREFERENCES = "com.google.android.apps.iosched.gcm"; private static final String PROPERTY_REGISTERED_TS = "registered_ts"; private static final String PROPERTY_REG_ID = "reg_id"; private static final int MAX_ATTEMPTS = 5; private static final int BACKOFF_MILLI_SECONDS = 2000; private static final Random sRandom = new Random(); /** * Register this account/device pair within the server. * * @param context Current context * @param gcmId The GCM registration ID for this device * @return whether the registration succeeded or not. */ public static boolean register(final Context context, final String gcmId) { LOGI(TAG, "registering device (gcm_id = " + gcmId + ")"); String serverUrl = Config.GCM_SERVER_URL + "/register"; String plusProfileId = AccountUtils.getPlusProfileId(context); if (plusProfileId == null) { LOGW(TAG, "Profile ID: null"); } else { LOGI(TAG, "Profile ID: " + plusProfileId); } Map<String, String> params = new HashMap<String, String>(); params.put("gcm_id", gcmId); params.put("gplus_id", plusProfileId); long backoff = BACKOFF_MILLI_SECONDS + sRandom.nextInt(1000); // Once GCM returns a registration id, we need to register it in the // demo server. As the server might be down, we will retry it a couple // times. for (int i = 1; i <= MAX_ATTEMPTS; i++) { LOGV(TAG, "Attempt #" + i + " to register"); try { post(serverUrl, params); setRegisteredOnServer(context, true, gcmId); return true; } catch (IOException e) { // Here we are simplifying and retrying on any error; in a real // application, it should retry only on unrecoverable errors // (like HTTP error code 503). LOGE(TAG, "Failed to register on attempt " + i, e); if (i == MAX_ATTEMPTS) { break; } try { LOGV(TAG, "Sleeping for " + backoff + " ms before retry"); Thread.sleep(backoff); } catch (InterruptedException e1) { // Activity finished before we complete - exit. LOGD(TAG, "Thread interrupted: abort remaining retries!"); Thread.currentThread().interrupt(); return false; } // increase backoff exponentially backoff *= 2; } } return false; } /** * Unregister this account/device pair within the server. * * @param context Current context * @param gcmId The GCM registration ID for this device */ static void unregister(final Context context, final String gcmId) { LOGI(TAG, "unregistering device (gcmId = " + gcmId + ")"); String serverUrl = Config.GCM_SERVER_URL + "/unregister"; Map<String, String> params = new HashMap<String, String>(); params.put("gcm_id", gcmId); try { post(serverUrl, params); setRegisteredOnServer(context, false, gcmId); } catch (IOException e) { // At this point the device is unregistered from GCM, but still // registered in the server. // We could try to unregister again, but it is not necessary: // if the server tries to send a message to the device, it will get // a "NotRegistered" error message and should unregister the device. LOGD(TAG, "Unable to unregister from application server", e); } finally { // Regardless of server success, clear local preferences setRegisteredOnServer(context, false, null); } } /** * Sets whether the device was successfully registered in the server side. * * @param context Current context * @param flag True if registration was successful, false otherwise * @param gcmId True if registration was successful, false otherwise */ private static void setRegisteredOnServer(Context context, boolean flag, String gcmId) { final SharedPreferences prefs = context.getSharedPreferences( PREFERENCES, Context.MODE_PRIVATE); LOGD(TAG, "Setting registered on server status as: " + flag); Editor editor = prefs.edit(); if (flag) { editor.putLong(PROPERTY_REGISTERED_TS, new Date().getTime()); editor.putString(PROPERTY_REG_ID, gcmId); } else { editor.remove(PROPERTY_REG_ID); } editor.commit(); } /** * Checks whether the device was successfully registered in the server side. * * @param context Current context * @return True if registration was successful, false otherwise */ public static boolean isRegisteredOnServer(Context context) { final SharedPreferences prefs = context.getSharedPreferences( PREFERENCES, Context.MODE_PRIVATE); // Find registration threshold Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1); long yesterdayTS = cal.getTimeInMillis(); long regTS = prefs.getLong(PROPERTY_REGISTERED_TS, 0); if (regTS > yesterdayTS) { LOGV(TAG, "GCM registration current. regTS=" + regTS + " yesterdayTS=" + yesterdayTS); return true; } else { LOGV(TAG, "GCM registration expired. regTS=" + regTS + " yesterdayTS=" + yesterdayTS); return false; } } public static String getGcmId(Context context) { final SharedPreferences prefs = context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE); return prefs.getString(PROPERTY_REG_ID, null); } /** * Unregister the current GCM ID when we sign-out * * @param context Current context */ public static void onSignOut(Context context) { String gcmId = getGcmId(context); if (gcmId != null) { unregister(context, gcmId); } } /** * Issue a POST request to the server. * * @param endpoint POST address. * @param params request parameters. * @throws java.io.IOException propagated from POST. */ private static void post(String endpoint, Map<String, String> params) throws IOException { URL url; try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=') .append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); LOGV(TAG, "Posting '" + body + "' to " + url); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setChunkedStreamingMode(0); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); conn.setRequestProperty("Content-Length", Integer.toString(body.length())); // post the request OutputStream out = conn.getOutputStream(); out.write(body.getBytes()); out.close(); // handle the response int status = conn.getResponseCode(); if (status != 200) { throw new IOException("Post failed with error code " + status); } } finally { if (conn != null) { conn.disconnect(); } } } }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.command; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import com.google.android.apps.iosched.gcm.GCMCommand; import com.google.android.apps.iosched.sync.TriggerSyncReceiver; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.util.Random; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class SyncCommand extends GCMCommand { private static final String TAG = makeLogTag("SyncCommand"); private static final int DEFAULT_TRIGGER_SYNC_MAX_JITTER_MILLIS = 15 * 60 * 1000; // 15 minutes private static final Random RANDOM = new Random(); @Override public void execute(Context context, String type, String extraData) { LOGI(TAG, "Received GCM message: " + type); int syncJitter; SyncData syncData = null; if (extraData != null) { try { Gson gson = new Gson(); syncData = gson.fromJson(extraData, SyncData.class); } catch (JsonSyntaxException e) { LOGI(TAG, "Error while decoding extraData: " + e.toString()); } } if (syncData != null && syncData.sync_jitter != 0) { syncJitter = syncData.sync_jitter; } else { syncJitter = DEFAULT_TRIGGER_SYNC_MAX_JITTER_MILLIS; } scheduleSync(context, syncJitter); } private void scheduleSync(Context context, int syncJitter) { int jitterMillis = (int) (RANDOM.nextFloat() * syncJitter); final String debugMessage = "Scheduling next sync for " + jitterMillis + "ms"; LOGI(TAG, debugMessage); ((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)) .set( AlarmManager.RTC, System.currentTimeMillis() + jitterMillis, PendingIntent.getBroadcast( context, 0, new Intent(context, TriggerSyncReceiver.class), PendingIntent.FLAG_CANCEL_CURRENT)); } class SyncData { private int sync_jitter; SyncData() {} } }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.command; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.gcm.GCMCommand; import com.google.android.apps.iosched.ui.HomeActivity; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class AnnouncementCommand extends GCMCommand { private static final String TAG = makeLogTag("AnnouncementCommand"); @Override public void execute(Context context, String type, String extraData) { LOGI(TAG, "Received GCM message: " + type); displayNotification(context, extraData); } private void displayNotification(Context context, String message) { LOGI(TAG, "Displaying notification: " + message); ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)) .notify(0, new NotificationCompat.Builder(context) .setWhen(System.currentTimeMillis()) .setSmallIcon(R.drawable.ic_stat_notification) .setTicker(message) .setContentTitle(context.getString(R.string.app_name)) .setContentText(message) .setContentIntent( PendingIntent.getActivity(context, 0, new Intent(context, HomeActivity.class) .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP), 0)) .setAutoCancel(true) .build()); } }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.command; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import com.google.android.apps.iosched.gcm.GCMCommand; import com.google.android.apps.iosched.sync.TriggerSyncReceiver; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import java.util.Random; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class SyncUserCommand extends GCMCommand { private static final String TAG = makeLogTag("TestCommand"); private static final int DEFAULT_TRIGGER_SYNC_DELAY = 60 * 1000; // 60 seconds private static final Random RANDOM = new Random(); @Override public void execute(Context context, String type, String extraData) { LOGI(TAG, "Received GCM message: " + type); int syncJitter; SyncData syncData = null; if (extraData != null) { try { Gson gson = new Gson(); syncData = gson.fromJson(extraData, SyncData.class); } catch (JsonSyntaxException e) { LOGI(TAG, "Error while decoding extraData: " + e.toString()); } } // TODO(trevorjohns): Make this so there's a configurable sync and jitter. // TODO(trevorjohns): Also, use superclass to reduce duplcated code between this and SyncCommand if (syncData != null && syncData.sync_jitter != 0) { syncJitter = syncData.sync_jitter; } else { syncJitter = DEFAULT_TRIGGER_SYNC_DELAY; } scheduleSync(context, syncJitter); } private void scheduleSync(Context context, int syncDelay) { // Use delay instead of jitter, since we're trying to squelch messages int jitterMillis = syncDelay; final String debugMessage = "Scheduling next sync for " + jitterMillis + "ms"; LOGI(TAG, debugMessage); ((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)) .set( AlarmManager.RTC, System.currentTimeMillis() + jitterMillis, PendingIntent.getBroadcast( context, 0, new Intent(context, TriggerSyncReceiver.class), PendingIntent.FLAG_CANCEL_CURRENT)); } class SyncData { private int sync_jitter; SyncData() {} } }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm.command; import android.content.Context; import com.google.android.apps.iosched.gcm.GCMCommand; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class TestCommand extends GCMCommand { private static final String TAG = makeLogTag("TestCommand"); @Override public void execute(Context context, String type, String extraData) { LOGI(TAG, "Received GCM message: " + type); } }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm; import android.content.Context; public abstract class GCMCommand { public abstract void execute(Context context, String type, String extraData); }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.gcm; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.gcm.command.AnnouncementCommand; import com.google.android.apps.iosched.gcm.command.SyncCommand; import com.google.android.apps.iosched.gcm.command.SyncUserCommand; import com.google.android.apps.iosched.gcm.command.TestCommand; import com.google.android.gcm.GCMBaseIntentService; import android.content.Context; import android.content.Intent; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * {@link android.app.IntentService} responsible for handling GCM messages. */ public class GCMIntentService extends GCMBaseIntentService { private static final String TAG = makeLogTag("GCM"); private static final Map<String, GCMCommand> MESSAGE_RECEIVERS; static { // Known messages and their GCM message receivers Map <String, GCMCommand> receivers = new HashMap<String, GCMCommand>(); receivers.put("test", new TestCommand()); receivers.put("announcement", new AnnouncementCommand()); receivers.put("sync_schedule", new SyncCommand()); receivers.put("sync_user", new SyncUserCommand()); MESSAGE_RECEIVERS = Collections.unmodifiableMap(receivers); } public GCMIntentService() { super(Config.GCM_SENDER_ID); } @Override protected void onRegistered(Context context, String regId) { LOGI(TAG, "Device registered: regId=" + regId); ServerUtilities.register(context, regId); } @Override protected void onUnregistered(Context context, String regId) { LOGI(TAG, "Device unregistered"); if (ServerUtilities.isRegisteredOnServer(context)) { ServerUtilities.unregister(context, regId); } else { // This callback results from the call to unregister made on // ServerUtilities when the registration to the server failed. LOGD(TAG, "Ignoring unregister callback"); } } @Override protected void onMessage(Context context, Intent intent) { String action = intent.getStringExtra("action"); String extraData = intent.getStringExtra("extraData"); if (action == null) { LOGE(TAG, "Message received without command action"); return; } action = action.toLowerCase(); GCMCommand command = MESSAGE_RECEIVERS.get(action); if (command == null) { LOGE(TAG, "Unknown command received: " + action); } else { command.execute(this, action, extraData); } } @Override public void onError(Context context, String errorId) { LOGE(TAG, "Received error: " + errorId); } @Override protected boolean onRecoverableError(Context context, String errorId) { // log message LOGW(TAG, "Received recoverable error: " + errorId); return super.onRecoverableError(context, errorId); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.provider.BaseColumns; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.support.v7.app.ActionBarActivity; import android.support.v7.view.ActionMode; import android.text.TextUtils; import android.text.format.DateUtils; import android.util.SparseArray; import android.view.*; import android.view.View.OnLongClickListener; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.tablet.SessionsSandboxMultiPaneActivity; import com.google.android.apps.iosched.util.PrefUtils; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import java.util.ArrayList; import java.util.Formatter; import java.util.List; import java.util.Locale; import static com.google.android.apps.iosched.util.LogUtils.LOGW; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class ScheduleFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>, ActionMode.Callback { private static final String TAG = makeLogTag(ScheduleFragment.class); private static final String STATE_ACTION_MODE = "actionMode"; private SimpleSectionedListAdapter mAdapter; private MyScheduleAdapter mScheduleAdapter; private SparseArray<String> mSelectedItemData; private View mLongClickedView; private ActionMode mActionMode; private boolean mScrollToNow; private boolean mActionModeStarted = false; private Bundle mViewDestroyedInstanceState; private StringBuilder mBuffer = new StringBuilder(); private Formatter mFormatter = new Formatter(mBuffer, Locale.getDefault()); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mScheduleAdapter = new MyScheduleAdapter(getActivity()); mAdapter = new SimpleSectionedListAdapter(getActivity(), R.layout.list_item_schedule_header, mScheduleAdapter); setListAdapter(mAdapter); if (savedInstanceState == null) { mScrollToNow = true; } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); persistActionModeState(outState); } private void persistActionModeState(Bundle outState) { if (outState != null && mActionModeStarted && mSelectedItemData != null) { outState.putStringArray(STATE_ACTION_MODE, new String[]{ mSelectedItemData.get(BlocksQuery.STARRED_SESSION_ID), mSelectedItemData.get(BlocksQuery.STARRED_SESSION_TITLE), mSelectedItemData.get(BlocksQuery.STARRED_SESSION_HASHTAGS), mSelectedItemData.get(BlocksQuery.STARRED_SESSION_URL), mSelectedItemData.get(BlocksQuery.STARRED_SESSION_ROOM_ID), }); } } private void loadActionModeState(Bundle state) { if (state != null && state.containsKey(STATE_ACTION_MODE)) { mActionModeStarted = true; mActionMode = ((ActionBarActivity) getActivity()).startSupportActionMode(this); String[] data = state.getStringArray(STATE_ACTION_MODE); if (data != null) { mSelectedItemData = new SparseArray<String>(); mSelectedItemData.put(BlocksQuery.STARRED_SESSION_ID, data[0]); mSelectedItemData.put(BlocksQuery.STARRED_SESSION_TITLE, data[1]); mSelectedItemData.put(BlocksQuery.STARRED_SESSION_HASHTAGS, data[2]); mSelectedItemData.put(BlocksQuery.STARRED_SESSION_URL, data[3]); mSelectedItemData.put(BlocksQuery.STARRED_SESSION_ROOM_ID, data[4]); } } } @Override public void setMenuVisibility(boolean menuVisible) { super.setMenuVisibility(menuVisible); // Hide the action mode when the fragment becomes invisible if (!menuVisible) { if (mActionModeStarted && mActionMode != null && mSelectedItemData != null) { mViewDestroyedInstanceState = new Bundle(); persistActionModeState(mViewDestroyedInstanceState); mActionMode.finish(); } } else if (mViewDestroyedInstanceState != null) { loadActionModeState(mViewDestroyedInstanceState); mViewDestroyedInstanceState = null; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate( R.layout.fragment_list_with_empty_container, container, false); inflater.inflate(R.layout.empty_waiting_for_sync, (ViewGroup) root.findViewById(android.R.id.empty), true); root.setBackgroundColor(Color.WHITE); ListView listView = (ListView) root.findViewById(android.R.id.list); listView.setItemsCanFocus(true); listView.setCacheColorHint(Color.WHITE); listView.setSelector(android.R.color.transparent); return root; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); loadActionModeState(savedInstanceState); // In support library r8, calling initLoader for a fragment in a FragmentPagerAdapter in // the fragment's onCreate may cause the same LoaderManager to be dealt to multiple // fragments because their mIndex is -1 (haven't been added to the activity yet). Thus, // we do this in onActivityCreated. getLoaderManager().initLoader(0, null, this); } private final SharedPreferences.OnSharedPreferenceChangeListener mPrefChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sp, String key) { if (isAdded() && mAdapter != null) { if (PrefUtils.PREF_LOCAL_TIMES.equals(key)) { PrefUtils.isUsingLocalTime(getActivity(), true); // force update mAdapter.notifyDataSetInvalidated(); } else if (PrefUtils.PREF_ATTENDEE_AT_VENUE.equals(key)) { PrefUtils.isAttendeeAtVenue(getActivity(), true); // force update getLoaderManager().restartLoader(0, null, ScheduleFragment.this); } } } }; private final ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (!isAdded()) { return; } getLoaderManager().restartLoader(0, null, ScheduleFragment.this); } }; @Override public void onAttach(Activity activity) { super.onAttach(activity); activity.getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mObserver); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity); sp.registerOnSharedPreferenceChangeListener(mPrefChangeListener); } @Override public void onDetach() { super.onDetach(); getActivity().getContentResolver().unregisterContentObserver(mObserver); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); sp.unregisterOnSharedPreferenceChangeListener(mPrefChangeListener); } // LoaderCallbacks @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { String liveStreamedOnlyBlocksSelection = "(" + (UIUtils.shouldShowLiveSessionsOnly(getActivity()) ? ScheduleContract.Blocks.BLOCK_TYPE + " NOT IN ('" + ScheduleContract.Blocks.BLOCK_TYPE_SESSION + "','" + ScheduleContract.Blocks.BLOCK_TYPE_CODELAB + "','" + ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS + "','" + ScheduleContract.Blocks.BLOCK_TYPE_FOOD + "')" + " OR " + ScheduleContract.Blocks.NUM_LIVESTREAMED_SESSIONS + ">1 " : "1==1") + ")"; String onlyStarredOfficeHoursSelection = "(" + ScheduleContract.Blocks.BLOCK_TYPE + " != '" + ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS + "' OR " + ScheduleContract.Blocks.NUM_STARRED_SESSIONS + ">0)"; String excludeSandbox = "("+ScheduleContract.Blocks.BLOCK_TYPE + " != '" + ScheduleContract.Blocks.BLOCK_TYPE_SANDBOX +"')"; return new CursorLoader(getActivity(), ScheduleContract.Blocks.CONTENT_URI, BlocksQuery.PROJECTION, liveStreamedOnlyBlocksSelection + " AND " + onlyStarredOfficeHoursSelection + " AND " + excludeSandbox, null, ScheduleContract.Blocks.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (!isAdded()) { return; } Context context = getActivity(); long currentTime = UIUtils.getCurrentTime(getActivity()); int firstNowPosition = ListView.INVALID_POSITION; String displayTimeZone = PrefUtils.getDisplayTimeZone(context).getID(); List<SimpleSectionedListAdapter.Section> sections = new ArrayList<SimpleSectionedListAdapter.Section>(); cursor.moveToFirst(); long previousBlockStart = -1; long blockStart, blockEnd; while (!cursor.isAfterLast()) { blockStart = cursor.getLong(BlocksQuery.BLOCK_START); blockEnd = cursor.getLong(BlocksQuery.BLOCK_END); if (!UIUtils.isSameDayDisplay(previousBlockStart, blockStart, context)) { mBuffer.setLength(0); sections.add(new SimpleSectionedListAdapter.Section(cursor.getPosition(), DateUtils.formatDateRange( context, mFormatter, blockStart, blockStart, DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY, displayTimeZone).toString())); } if (mScrollToNow && firstNowPosition == ListView.INVALID_POSITION // if we're currently in this block, or we're not in a block // and this block is in the future, then this is the scroll position && ((blockStart < currentTime && currentTime < blockEnd) || blockStart > currentTime)) { firstNowPosition = cursor.getPosition(); } previousBlockStart = blockStart; cursor.moveToNext(); } mScheduleAdapter.swapCursor(cursor); SimpleSectionedListAdapter.Section[] dummy = new SimpleSectionedListAdapter.Section[sections.size()]; mAdapter.setSections(sections.toArray(dummy)); if (mScrollToNow && firstNowPosition != ListView.INVALID_POSITION) { firstNowPosition = mAdapter.positionToSectionedPosition(firstNowPosition); getListView().setSelectionFromTop(firstNowPosition, getResources().getDimensionPixelSize(R.dimen.list_scroll_top_offset)); mScrollToNow = false; } } @Override public void onLoaderReset(Loader<Cursor> loader) { } private class MyScheduleAdapter extends CursorAdapter { public MyScheduleAdapter(Context context) { super(context, null, 0); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return LayoutInflater.from(context).inflate(R.layout.list_item_schedule_block, parent, false); } @Override public void bindView(View view, Context context, final Cursor cursor) { final String type = cursor.getString(BlocksQuery.BLOCK_TYPE); final String blockId = cursor.getString(BlocksQuery.BLOCK_ID); final String blockTitle = cursor.getString(BlocksQuery.BLOCK_TITLE); final long blockStart = cursor.getLong(BlocksQuery.BLOCK_START); final long blockEnd = cursor.getLong(BlocksQuery.BLOCK_END); final String blockMeta = cursor.getString(BlocksQuery.BLOCK_META); final String blockTimeString = UIUtils.formatBlockTimeString(blockStart, blockEnd, mBuffer, context); final TextView timeView = (TextView) view.findViewById(R.id.block_time); final TextView endtimeView = (TextView) view.findViewById(R.id.block_endtime); final TextView titleView = (TextView) view.findViewById(R.id.block_title); final TextView subtitleView = (TextView) view.findViewById(R.id.block_subtitle); final ImageButton extraButton = (ImageButton) view.findViewById(R.id.extra_button); final View primaryTouchTargetView = view.findViewById(R.id.list_item_middle_container); final Resources res = getResources(); String subtitle; boolean isLiveStreamed = false; primaryTouchTargetView.setOnLongClickListener(null); primaryTouchTargetView.setSelected(false); endtimeView.setText(null); titleView.setTextColor(res.getColorStateList(R.color.body_text_1_stateful)); subtitleView.setTextColor(res.getColorStateList(R.color.body_text_2_stateful)); if (ScheduleContract.Blocks.BLOCK_TYPE_SESSION.equals(type) || ScheduleContract.Blocks.BLOCK_TYPE_CODELAB.equals(type) || ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS.equals(type)) { final int numStarredSessions = cursor.getInt(BlocksQuery.NUM_STARRED_SESSIONS); final String starredSessionId = cursor.getString(BlocksQuery.STARRED_SESSION_ID); View.OnClickListener allSessionsListener = new View.OnClickListener() { @Override public void onClick(View view) { if (mActionModeStarted) { return; } final Uri sessionsUri = ScheduleContract.Blocks.buildSessionsUri(blockId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.putExtra(Intent.EXTRA_TITLE, blockTimeString); startActivity(intent); } }; if (numStarredSessions == 0) { // 0 sessions starred titleView.setText(getString(R.string.schedule_empty_slot_title_template, TextUtils.isEmpty(blockTitle) ? "" : (" " + blockTitle.toLowerCase()))); titleView.setTextColor(res.getColorStateList( R.color.body_text_1_positive_stateful)); subtitle = getString(R.string.schedule_empty_slot_subtitle); extraButton.setVisibility(View.GONE); primaryTouchTargetView.setOnClickListener(allSessionsListener); primaryTouchTargetView.setEnabled(!mActionModeStarted); } else if (numStarredSessions == 1) { // exactly 1 session starred final String starredSessionTitle = cursor.getString(BlocksQuery.STARRED_SESSION_TITLE); final String starredSessionHashtags = cursor.getString(BlocksQuery.STARRED_SESSION_HASHTAGS); final String starredSessionUrl = cursor.getString(BlocksQuery.STARRED_SESSION_URL); final String starredSessionRoomId = cursor.getString(BlocksQuery.STARRED_SESSION_ROOM_ID); titleView.setText(starredSessionTitle); subtitle = cursor.getString(BlocksQuery.STARRED_SESSION_ROOM_NAME); if (subtitle == null) { subtitle = getString(R.string.unknown_room); } // Determine if the session is in the past long currentTimeMillis = UIUtils.getCurrentTime(context); boolean conferenceEnded = currentTimeMillis > UIUtils.CONFERENCE_END_MILLIS; boolean blockEnded = currentTimeMillis > blockEnd; if (blockEnded && !conferenceEnded) { subtitle = getString(R.string.session_finished); } isLiveStreamed = !TextUtils.isEmpty( cursor.getString(BlocksQuery.STARRED_SESSION_LIVESTREAM_URL)); extraButton.setVisibility(View.VISIBLE); extraButton.setOnClickListener(allSessionsListener); extraButton.setEnabled(!mActionModeStarted); if (mSelectedItemData != null && mActionModeStarted && mSelectedItemData.get(BlocksQuery.STARRED_SESSION_ID, "").equals( starredSessionId)) { primaryTouchTargetView.setSelected(true); mLongClickedView = primaryTouchTargetView; } final Runnable restartActionMode = new Runnable() { @Override public void run() { boolean currentlySelected = false; if (mActionModeStarted && mSelectedItemData != null && starredSessionId.equals(mSelectedItemData.get( BlocksQuery.STARRED_SESSION_ID))) { currentlySelected = true; } if (mActionMode != null) { mActionMode.finish(); if (currentlySelected) { return; } } mLongClickedView = primaryTouchTargetView; mSelectedItemData = new SparseArray<String>(); mSelectedItemData.put(BlocksQuery.STARRED_SESSION_ID, starredSessionId); mSelectedItemData.put(BlocksQuery.STARRED_SESSION_TITLE, starredSessionTitle); mSelectedItemData.put(BlocksQuery.STARRED_SESSION_HASHTAGS, starredSessionHashtags); mSelectedItemData.put(BlocksQuery.STARRED_SESSION_URL, starredSessionUrl); mSelectedItemData.put(BlocksQuery.STARRED_SESSION_ROOM_ID, starredSessionRoomId); mActionMode = ((ActionBarActivity) getActivity()) .startSupportActionMode(ScheduleFragment.this); primaryTouchTargetView.setSelected(true); } }; primaryTouchTargetView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mActionModeStarted) { restartActionMode.run(); return; } final Uri sessionUri = ScheduleContract.Sessions.buildSessionUri( starredSessionId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionUri); intent.putExtra(SessionsSandboxMultiPaneActivity.EXTRA_MASTER_URI, ScheduleContract.Blocks.buildSessionsUri(blockId)); intent.putExtra(Intent.EXTRA_TITLE, blockTimeString); startActivity(intent); } }); primaryTouchTargetView.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { restartActionMode.run(); return true; } }); primaryTouchTargetView.setEnabled(true); } else { // 2 or more sessions starred titleView.setText(getString(R.string.schedule_conflict_title, numStarredSessions)); subtitle = getString(R.string.schedule_conflict_subtitle); extraButton.setVisibility(View.VISIBLE); extraButton.setOnClickListener(allSessionsListener); extraButton.setEnabled(!mActionModeStarted); primaryTouchTargetView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mActionModeStarted) { return; } final Uri sessionsUri = ScheduleContract.Blocks .buildStarredSessionsUri( blockId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.putExtra(Intent.EXTRA_TITLE, blockTimeString); startActivity(intent); } }); primaryTouchTargetView.setEnabled(!mActionModeStarted); } } else if (ScheduleContract.Blocks.BLOCK_TYPE_KEYNOTE.equals(type)) { final String starredSessionId = cursor.getString(BlocksQuery.STARRED_SESSION_ID); final String starredSessionTitle = cursor.getString(BlocksQuery.STARRED_SESSION_TITLE); long currentTimeMillis = UIUtils.getCurrentTime(context); boolean past = (currentTimeMillis > blockEnd && currentTimeMillis < UIUtils.CONFERENCE_END_MILLIS); boolean present = !past && (currentTimeMillis >= blockStart); boolean canViewStream = present && UIUtils.hasHoneycomb(); boolean enabled = canViewStream && !mActionModeStarted; isLiveStreamed = true; subtitle = getString(R.string.keynote_room); titleView.setText(starredSessionTitle); extraButton.setVisibility(View.GONE); primaryTouchTargetView.setEnabled(enabled); primaryTouchTargetView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mActionModeStarted) { return; } final Uri sessionUri = ScheduleContract.Sessions.buildSessionUri( starredSessionId); Intent livestreamIntent = new Intent(Intent.ACTION_VIEW, sessionUri); livestreamIntent.setClass(getActivity(), SessionLivestreamActivity.class); startActivity(livestreamIntent); } }); } else { subtitle = blockMeta; titleView.setText(blockTitle); extraButton.setVisibility(View.GONE); primaryTouchTargetView.setEnabled(false); primaryTouchTargetView.setOnClickListener(null); mBuffer.setLength(0); endtimeView.setText(DateUtils.formatDateRange(context, mFormatter, blockEnd, blockEnd, DateUtils.FORMAT_SHOW_TIME, PrefUtils.getDisplayTimeZone(context).getID()).toString()); } mBuffer.setLength(0); timeView.setText(DateUtils.formatDateRange(context, mFormatter, blockStart, blockStart, DateUtils.FORMAT_SHOW_TIME, PrefUtils.getDisplayTimeZone(context).getID()).toString()); // Show past/present/future and livestream status for this block. UIUtils.updateTimeAndLivestreamBlockUI(context, blockStart, blockEnd, isLiveStreamed, titleView, subtitleView, subtitle); } } private interface BlocksQuery { String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Blocks.BLOCK_ID, ScheduleContract.Blocks.BLOCK_TITLE, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Blocks.BLOCK_TYPE, ScheduleContract.Blocks.BLOCK_META, ScheduleContract.Blocks.SESSIONS_COUNT, ScheduleContract.Blocks.NUM_STARRED_SESSIONS, ScheduleContract.Blocks.NUM_LIVESTREAMED_SESSIONS, ScheduleContract.Blocks.STARRED_SESSION_ID, ScheduleContract.Blocks.STARRED_SESSION_TITLE, ScheduleContract.Blocks.STARRED_SESSION_ROOM_NAME, ScheduleContract.Blocks.STARRED_SESSION_ROOM_ID, ScheduleContract.Blocks.STARRED_SESSION_HASHTAGS, ScheduleContract.Blocks.STARRED_SESSION_URL, ScheduleContract.Blocks.STARRED_SESSION_LIVESTREAM_URL, }; int _ID = 0; int BLOCK_ID = 1; int BLOCK_TITLE = 2; int BLOCK_START = 3; int BLOCK_END = 4; int BLOCK_TYPE = 5; int BLOCK_META = 6; int SESSIONS_COUNT = 7; int NUM_STARRED_SESSIONS = 8; int NUM_LIVESTREAMED_SESSIONS = 9; int STARRED_SESSION_ID = 10; int STARRED_SESSION_TITLE = 11; int STARRED_SESSION_ROOM_NAME = 12; int STARRED_SESSION_ROOM_ID = 13; int STARRED_SESSION_HASHTAGS = 14; int STARRED_SESSION_URL = 15; int STARRED_SESSION_LIVESTREAM_URL = 16; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { SessionsHelper helper = new SessionsHelper(getActivity()); String title = mSelectedItemData.get(BlocksQuery.STARRED_SESSION_TITLE); String hashtags = mSelectedItemData.get(BlocksQuery.STARRED_SESSION_HASHTAGS); String url = mSelectedItemData.get(BlocksQuery.STARRED_SESSION_URL); boolean handled = false; switch (item.getItemId()) { case R.id.menu_map: String roomId = mSelectedItemData.get(BlocksQuery.STARRED_SESSION_ROOM_ID); helper.startMapActivity(roomId); handled = true; break; case R.id.menu_star: String sessionId = mSelectedItemData.get(BlocksQuery.STARRED_SESSION_ID); Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId); helper.setSessionStarred(sessionUri, false, title); handled = true; break; case R.id.menu_share: // On ICS+ devices, we normally won't reach this as ShareActionProvider will handle // sharing. helper.shareSession(getActivity(), R.string.share_template, title, hashtags, url); handled = true; break; case R.id.menu_social_stream: helper.startSocialStream(hashtags); handled = true; break; default: LOGW(TAG, "Unknown action taken"); } mActionMode.finish(); return handled; } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.sessions_context, menu); MenuItem starMenuItem = menu.findItem(R.id.menu_star); starMenuItem.setTitle(R.string.description_remove_schedule); starMenuItem.setIcon(R.drawable.ic_action_remove_schedule); mAdapter.notifyDataSetChanged(); mActionModeStarted = true; return true; } @Override public void onDestroyActionMode(ActionMode mode) { mActionMode = null; if (mLongClickedView != null) { mLongClickedView.setSelected(false); } mActionModeStarted = false; mAdapter.notifyDataSetChanged(); } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; public class AnnouncementsActivity extends SimpleSinglePaneActivity { @Override protected Fragment onCreatePane() { setIntent(getIntent().putExtra(AnnouncementsFragment.EXTRA_ADD_VERTICAL_MARGINS, true)); return new AnnouncementsFragment(); } @Override protected int getContentViewResId() { return R.layout.activity_plus_stream; } }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.app.TaskStackBuilder; /** * Helper 'proxy' activity that simply accepts an activity intent and synthesize a back-stack * for it, per Android's design guidelines for navigation from widgets and notifications. */ public class TaskStackBuilderProxyActivity extends Activity { private static final String EXTRA_INTENTS = "com.google.android.apps.iosched.extra.INTENTS"; public static Intent getTemplate(Context context) { return new Intent(context, TaskStackBuilderProxyActivity.class) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } public static Intent getFillIntent(Intent... intents) { return new Intent().putExtra(EXTRA_INTENTS, intents); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TaskStackBuilder builder = TaskStackBuilder.create(this); Intent proxyIntent = getIntent(); if (!proxyIntent.hasExtra(EXTRA_INTENTS)) { finish(); return; } for (Parcelable parcelable : proxyIntent.getParcelableArrayExtra(EXTRA_INTENTS)) { builder.addNextIntent((Intent) parcelable); } builder.startActivities(); finish(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.database.DataSetObserver; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.TracksAdapter.TracksQuery; import com.google.android.apps.iosched.ui.tablet.SessionsSandboxMultiPaneActivity; import com.google.android.apps.iosched.ui.tablet.TracksDropdownFragment; import com.google.android.apps.iosched.util.UIUtils; /** * A simple {@link ListFragment} that renders a list of tracks with available * sessions or sandbox companies (depending on {@link ExploreFragment#VIEW_TYPE}) using a * {@link TracksAdapter}. */ public class ExploreFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> { private TracksAdapter mAdapter; private View mEmptyView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate( R.layout.fragment_list_with_empty_container_inset, container, false); mEmptyView = rootView.findViewById(android.R.id.empty); inflater.inflate(R.layout.empty_waiting_for_sync, (ViewGroup) mEmptyView, true); return rootView; } @Override public void onViewCreated(final View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.setBackgroundColor(Color.WHITE); final ListView listView = getListView(); listView.setSelector(android.R.color.transparent); listView.setCacheColorHint(Color.WHITE); addMapHeaderView(); mAdapter = new TracksAdapter(getActivity(), false); setListAdapter(mAdapter); // Override default ListView empty-view handling listView.setEmptyView(null); mEmptyView.setVisibility(View.VISIBLE); mAdapter.registerDataSetObserver(new DataSetObserver() { @Override public void onChanged() { if (mAdapter.getCount() > 0) { mEmptyView.setVisibility(View.GONE); mAdapter.unregisterDataSetObserver(this); } } }); } private void addMapHeaderView() { ListView listView = getListView(); final Context context = listView.getContext(); View mapHeaderContainerView = LayoutInflater.from(context).inflate( R.layout.list_item_track_map, listView, false); View mapButton = mapHeaderContainerView.findViewById(R.id.map_button); mapButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Launch map of conference venue EasyTracker.getTracker().sendEvent( "Explore Tab", "Click", "Map", 0L); startActivity(new Intent(context, UIUtils.getMapActivityClass(getActivity()))); } }); listView.addHeaderView(mapHeaderContainerView); listView.setHeaderDividersEnabled(false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // As of support library r12, calling initLoader for a fragment in a FragmentPagerAdapter // in the fragment's onCreate may cause the same LoaderManager to be dealt to multiple // fragments because their mIndex is -1 (haven't been added to the activity yet). Thus, // we do this in onActivityCreated. getLoaderManager().initLoader(TracksQuery._TOKEN, null, this); } private final ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (getActivity() == null) { return; } getLoaderManager().restartLoader(TracksQuery._TOKEN, null, ExploreFragment.this); } }; @Override public void onAttach(Activity activity) { super.onAttach(activity); activity.getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mObserver); } @Override public void onDetach() { super.onDetach(); getActivity().getContentResolver().unregisterContentObserver(mObserver); } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position - 1); // - 1 to account for header String trackId = ScheduleContract.Tracks.ALL_TRACK_ID; int trackMeta = ScheduleContract.Tracks.TRACK_META_NONE; if (cursor != null) { trackId = cursor.getString(TracksAdapter.TracksQuery.TRACK_ID); trackMeta = cursor.getInt(TracksAdapter.TracksQuery.TRACK_META); } final Intent intent = new Intent(Intent.ACTION_VIEW); final Uri trackUri = ScheduleContract.Tracks.buildTrackUri(trackId); intent.setData(trackUri); if (trackMeta == ScheduleContract.Tracks.TRACK_META_SANDBOX_OFFICE_HOURS_ONLY) { intent.putExtra(SessionsSandboxMultiPaneActivity.EXTRA_DEFAULT_VIEW_TYPE, TracksDropdownFragment.VIEW_TYPE_SANDBOX); } else if (trackMeta == ScheduleContract.Tracks.TRACK_META_OFFICE_HOURS_ONLY) { intent.putExtra(SessionsSandboxMultiPaneActivity.EXTRA_DEFAULT_VIEW_TYPE, TracksDropdownFragment.VIEW_TYPE_OFFICE_HOURS); } startActivity(intent); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); Uri tracksUri = intent.getData(); if (tracksUri == null) { tracksUri = ScheduleContract.Tracks.CONTENT_URI; } // Filter our tracks query to only include those with valid results String[] projection = TracksAdapter.TracksQuery.PROJECTION; String selection = null; return new CursorLoader(getActivity(), tracksUri, projection, selection, null, ScheduleContract.Tracks.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } mAdapter.setHasAllItem(true); mAdapter.swapCursor(cursor); if (cursor.getCount() > 0) { mEmptyView.setVisibility(View.GONE); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.nfc.tech.Ndef; import android.os.Bundle; import com.google.analytics.tracking.android.EasyTracker; import java.util.Arrays; import static com.google.android.apps.iosched.util.LogUtils.LOGI; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; public class NfcBadgeActivity extends Activity { private static final String TAG = makeLogTag(NfcBadgeActivity.class); private static final String ATTENDEE_URL_PREFIX = "\u0004plus.google.com/"; @Override public void onStart() { super.onStart(); EasyTracker.getInstance().activityStart(this); // Check for NFC data Intent i = getIntent(); if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(i.getAction())) { LOGI(TAG, "Badge detected"); EasyTracker.getTracker().sendEvent("NFC", "Read", "Badge", null); readTag((Tag) i.getParcelableExtra(NfcAdapter.EXTRA_TAG)); } finish(); } @Override public void onStop() { super.onStop(); EasyTracker.getInstance().activityStop(this); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EasyTracker.getInstance().setContext(this); } private void readTag(Tag t) { byte[] id = t.getId(); // get NDEF tag details Ndef ndefTag = Ndef.get(t); // get NDEF message details NdefMessage ndefMesg = ndefTag.getCachedNdefMessage(); if (ndefMesg == null) { return; } NdefRecord[] ndefRecords = ndefMesg.getRecords(); if (ndefRecords == null) { return; } for (NdefRecord record : ndefRecords) { short tnf = record.getTnf(); String type = new String(record.getType()); if (tnf == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(type.getBytes(), NdefRecord.RTD_URI)) { String url = new String(record.getPayload()); if (url.startsWith(ATTENDEE_URL_PREFIX)) { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("https://" + url.substring(1))); startActivity(i); return; } } } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.Menu; import android.view.MenuItem; import com.google.android.apps.iosched.R; public class SocialStreamActivity extends SimpleSinglePaneActivity { @Override protected Fragment onCreatePane() { setIntent(getIntent().putExtra(SocialStreamFragment.EXTRA_ADD_VERTICAL_MARGINS, true)); return new SocialStreamFragment(); } @Override protected int getContentViewResId() { return R.layout.activity_plus_stream; } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); setTitle(getIntent().getStringExtra(SocialStreamFragment.EXTRA_QUERY)); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.social_stream_standalone, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_refresh: ((SocialStreamFragment) getFragment()).refresh(); return true; } return super.onOptionsItemSelected(item); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Feedback; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesClient; import com.google.android.gms.plus.PlusClient; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.*; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.SeekBar; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A fragment that lets the user submit feedback about a given session. */ public class SessionFeedbackFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>, GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener { private static final String TAG = makeLogTag(SessionDetailFragment.class); // Set this boolean extra to true to show a variable height header public static final String EXTRA_VARIABLE_HEIGHT_HEADER = "com.google.android.iosched.extra.VARIABLE_HEIGHT_HEADER"; private String mSessionId; private Uri mSessionUri; private String mTitleString; private TextView mTitle; private PlusClient mPlusClient; private boolean mVariableHeightHeader = false; private RatingBarHelper mSessionRatingFeedbackBar; private RatingBarHelper mQ1FeedbackBar; private RatingBarHelper mQ2FeedbackBar; private RatingBarHelper mQ3FeedbackBar; private RadioGroup mQ4RadioGroup; private EditText mComments; public SessionFeedbackFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final String chosenAccountName = AccountUtils.getChosenAccountName(getActivity()); mPlusClient = new PlusClient.Builder(getActivity(), this, this) .clearScopes() .setAccountName(chosenAccountName) .build(); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mSessionUri = intent.getData(); if (mSessionUri == null) { return; } mSessionId = ScheduleContract.Sessions.getSessionId(mSessionUri); mVariableHeightHeader = intent.getBooleanExtra(EXTRA_VARIABLE_HEIGHT_HEADER, false); LoaderManager manager = getLoaderManager(); manager.restartLoader(0, null, this); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_session_feedback, null); mTitle = (TextView) rootView.findViewById(R.id.session_title); mSessionRatingFeedbackBar = RatingBarHelper.create(rootView.findViewById( R.id.session_rating_container)); mQ1FeedbackBar = RatingBarHelper.create(rootView.findViewById( R.id.session_feedback_q1_container)); mQ2FeedbackBar = RatingBarHelper.create(rootView.findViewById( R.id.session_feedback_q2_container)); mQ3FeedbackBar = RatingBarHelper.create(rootView.findViewById( R.id.session_feedback_q3_container)); mQ4RadioGroup = (RadioGroup) rootView.findViewById(R.id.session_feedback_q4); mComments = (EditText) rootView.findViewById(R.id.session_feedback_comments); if (mVariableHeightHeader) { View headerView = rootView.findViewById(R.id.header_session); ViewGroup.LayoutParams layoutParams = headerView.getLayoutParams(); layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT; headerView.setLayoutParams(layoutParams); } rootView.findViewById(R.id.submit_feedback_button).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { submitAllFeedback(); EasyTracker.getTracker().sendEvent("Session", "Feedback", mTitleString, 0L); LOGD("Tracker", "Feedback: " + mTitleString); getActivity().finish(); } }); return rootView; } @Override public void onStart() { super.onStart(); mPlusClient.connect(); } @Override public void onStop() { super.onStop(); mPlusClient.disconnect(); } @Override public void onConnected(Bundle connectionHint) { } @Override public void onDisconnected() { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { // Don't show an error just for the +1 button. Google Play services errors // should be caught at a higher level in the app } /** * Handle {@link SessionsQuery} {@link Cursor}. */ private void onSessionQueryComplete(Cursor cursor) { if (!cursor.moveToFirst()) { return; } mTitleString = cursor.getString(SessionsQuery.TITLE); // Format time block this session occupies mTitle.setText(mTitleString); EasyTracker.getTracker().sendView("Feedback: " + mTitleString); LOGD("Tracker", "Feedback: " + mTitleString); } /* ALL THE FEEDBACKS */ void submitAllFeedback() { int rating = mSessionRatingFeedbackBar.getValue() + 1; int q1Answer = mQ1FeedbackBar.getValue() + 1; int q2Answer = mQ2FeedbackBar.getValue() + 1; int q3Answer = mQ3FeedbackBar.getValue() + 1; // Don't add +1, since this is effectively a boolean. index 0 = false, 1 = true, // -1 means no answer was given. int q4Answer = getCheckedRadioIndex(mQ4RadioGroup); String comments = mComments.getText().toString(); String answers = mSessionId + ", " + rating + ", " + q1Answer + ", " + q2Answer + ", " + q3Answer + ", " + q4Answer + ", " + comments; LOGD(TAG, answers); ContentValues values = new ContentValues(); values.put(Feedback.SESSION_ID, mSessionId); values.put(Feedback.UPDATED, System.currentTimeMillis()); values.put(Feedback.SESSION_RATING, rating); values.put(Feedback.ANSWER_RELEVANCE, q1Answer); values.put(Feedback.ANSWER_CONTENT, q2Answer); values.put(Feedback.ANSWER_SPEAKER, q3Answer); values.put(Feedback.ANSWER_WILLUSE, q4Answer); values.put(Feedback.COMMENTS, comments); getActivity().getContentResolver() .insert(ScheduleContract.Feedback.buildFeedbackUri(mSessionId), values); } int getCheckedRadioIndex(RadioGroup rg) { int radioId = rg.getCheckedRadioButtonId(); View rb = rg.findViewById(radioId); return rg.indexOfChild(rb); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(getActivity(), mSessionUri, SessionsQuery.PROJECTION, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (!isAdded()) { return; } onSessionQueryComplete(cursor); } @Override public void onLoaderReset(Loader<Cursor> loader) {} /** * Helper class for building a rating bar from a {@link SeekBar}. */ private static class RatingBarHelper implements SeekBar.OnSeekBarChangeListener { private SeekBar mBar; private boolean mTrackingTouch; private TextView[] mLabels; public static RatingBarHelper create(View container) { return new RatingBarHelper(container); } private RatingBarHelper(View container) { // Force the seekbar to multiples of 100 mBar = (SeekBar) container.findViewById(R.id.rating_bar); mLabels = new TextView[]{ (TextView) container.findViewById(R.id.rating_bar_label_1), (TextView) container.findViewById(R.id.rating_bar_label_2), (TextView) container.findViewById(R.id.rating_bar_label_3), (TextView) container.findViewById(R.id.rating_bar_label_4), (TextView) container.findViewById(R.id.rating_bar_label_5), }; mBar.setMax(400); mBar.setProgress(200); onProgressChanged(mBar, 200, false); mBar.setOnSeekBarChangeListener(this); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int value = Math.round(progress / 100f); if (fromUser) { seekBar.setProgress(value * 100); } if (!mTrackingTouch) { for (int i = 0; i < mLabels.length; i++) { mLabels[i].setSelected(i == value); } } } @Override public void onStartTrackingTouch(SeekBar seekBar) { mTrackingTouch = true; for (TextView mLabel : mLabels) { mLabel.setSelected(false); } } @Override public void onStopTrackingTouch(SeekBar seekBar) { int value = getValue(); mTrackingTouch = false; for (int i = 0; i < mLabels.length; i++) { mLabels[i].setSelected(i == value); } } public int getValue() { return mBar.getProgress() / 100; } } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} query parameters. */ private interface SessionsQuery { String[] PROJECTION = { ScheduleContract.Sessions.SESSION_TITLE, }; int TITLE = 0; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import android.content.Intent; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.*; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A base activity that handles common functionality in the app. */ public abstract class BaseActivity extends ActionBarActivity { private static final String TAG = makeLogTag(BaseActivity.class); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EasyTracker.getInstance().setContext(this); if (!AccountUtils.isAuthenticated(this) || !PrefUtils.isSetupDone(this)) { LogUtils.LOGD(TAG, "exiting:" + " isAuthenticated=" + AccountUtils.isAuthenticated(this) + " isSetupDone=" + PrefUtils.isSetupDone(this)); AccountUtils.startAuthenticationFlow(this, getIntent()); finish(); } } @Override protected void onResume() { super.onResume(); // Verifies the proper version of Google Play Services exists on the device. PlayServicesUtils.checkGooglePlaySevices(this); } protected void setHasTabs() { if (!UIUtils.isTablet(this) && getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) { // Only show the tab bar's shadow getSupportActionBar().setBackgroundDrawable(getResources().getDrawable( R.drawable.actionbar_background_noshadow)); } } /** * Sets the icon. */ protected void setActionBarTrackIcon(String trackName, int trackColor) { if (trackColor == 0) { getSupportActionBar().setIcon(R.drawable.actionbar_icon); return; } new UIUtils.TrackIconAsyncTask(trackName, trackColor) { @Override protected void onPostExecute(Bitmap bitmap) { BitmapDrawable outDrawable = new BitmapDrawable(getResources(), bitmap); getSupportActionBar().setIcon(outDrawable); } }.execute(this); } /** * Converts an intent into a {@link Bundle} suitable for use as fragment arguments. */ protected static Bundle intentToFragmentArguments(Intent intent) { Bundle arguments = new Bundle(); if (intent == null) { return arguments; } final Uri data = intent.getData(); if (data != null) { arguments.putParcelable("_uri", data); } final Bundle extras = intent.getExtras(); if (extras != null) { arguments.putAll(intent.getExtras()); } return arguments; } /** * Converts a fragment arguments bundle into an intent. */ public static Intent fragmentArgumentsToIntent(Bundle arguments) { Intent intent = new Intent(); if (arguments == null) { return intent; } final Uri data = arguments.getParcelable("_uri"); if (data != null) { intent.setData(data); } intent.putExtras(arguments); intent.removeExtra("_uri"); return intent; } @Override public void onStart() { super.onStart(); EasyTracker.getInstance().activityStart(this); } @Override public void onStop() { super.onStop(); EasyTracker.getInstance().activityStop(this); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import android.content.Context; import android.database.DataSetObserver; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.Arrays; import java.util.Comparator; public class SimpleSectionedListAdapter extends BaseAdapter { private boolean mValid = true; private int mSectionResourceId; private LayoutInflater mLayoutInflater; private ListAdapter mBaseAdapter; private SparseArray<Section> mSections = new SparseArray<Section>(); public static class Section { int firstPosition; int sectionedPosition; CharSequence title; public Section(int firstPosition, CharSequence title) { this.firstPosition = firstPosition; this.title = title; } public CharSequence getTitle() { return title; } } public SimpleSectionedListAdapter(Context context, int sectionResourceId, ListAdapter baseAdapter) { mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mSectionResourceId = sectionResourceId; mBaseAdapter = baseAdapter; mBaseAdapter.registerDataSetObserver(new DataSetObserver() { @Override public void onChanged() { mValid = !mBaseAdapter.isEmpty(); notifyDataSetChanged(); } @Override public void onInvalidated() { mValid = false; notifyDataSetInvalidated(); } }); } public void setSections(Section[] sections) { mSections.clear(); Arrays.sort(sections, new Comparator<Section>() { @Override public int compare(Section o, Section o1) { return (o.firstPosition == o1.firstPosition) ? 0 : ((o.firstPosition < o1.firstPosition) ? -1 : 1); } }); int offset = 0; // offset positions for the headers we're adding for (Section section : sections) { section.sectionedPosition = section.firstPosition + offset; mSections.append(section.sectionedPosition, section); ++offset; } notifyDataSetChanged(); } public int positionToSectionedPosition(int position) { int offset = 0; for (int i = 0; i < mSections.size(); i++) { if (mSections.valueAt(i).firstPosition > position) { break; } ++offset; } return position + offset; } public int sectionedPositionToPosition(int sectionedPosition) { if (isSectionHeaderPosition(sectionedPosition)) { return ListView.INVALID_POSITION; } int offset = 0; for (int i = 0; i < mSections.size(); i++) { if (mSections.valueAt(i).sectionedPosition > sectionedPosition) { break; } --offset; } return sectionedPosition + offset; } public boolean isSectionHeaderPosition(int position) { return mSections.get(position) != null; } @Override public int getCount() { return (mValid ? mBaseAdapter.getCount() + mSections.size() : 0); } @Override public Object getItem(int position) { return isSectionHeaderPosition(position) ? mSections.get(position) : mBaseAdapter.getItem(sectionedPositionToPosition(position)); } @Override public long getItemId(int position) { return isSectionHeaderPosition(position) ? Integer.MAX_VALUE - mSections.indexOfKey(position) : mBaseAdapter.getItemId(sectionedPositionToPosition(position)); } @Override public int getItemViewType(int position) { return isSectionHeaderPosition(position) ? getViewTypeCount() - 1 : mBaseAdapter.getItemViewType(position); } @Override public boolean isEnabled(int position) { //noinspection SimplifiableConditionalExpression return isSectionHeaderPosition(position) ? false : mBaseAdapter.isEnabled(sectionedPositionToPosition(position)); } @Override public int getViewTypeCount() { return mBaseAdapter.getViewTypeCount() + 1; // the section headings } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean hasStableIds() { return mBaseAdapter.hasStableIds(); } @Override public boolean isEmpty() { return mBaseAdapter.isEmpty(); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (isSectionHeaderPosition(position)) { TextView view = (TextView) convertView; if (view == null) { view = (TextView) mLayoutInflater.inflate(mSectionResourceId, parent, false); } view.setText(mSections.get(position).title); return view; } else { return mBaseAdapter.getView(sectionedPositionToPosition(position), convertView, parent); } } }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.Checkable; import android.widget.LinearLayout; public class CheckableLinearLayout extends LinearLayout implements Checkable { private static final int[] CHECKED_STATE_SET = {android.R.attr.state_checked}; private boolean mChecked = false; public CheckableLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); } public boolean isChecked() { return mChecked; } public void setChecked(boolean b) { if (b != mChecked) { mChecked = b; refreshDrawableState(); } } public void toggle() { setChecked(!mChecked); } @Override public int[] onCreateDrawableState(int extraSpace) { final int[] drawableState = super.onCreateDrawableState(extraSpace + 1); if (isChecked()) { mergeDrawableStates(drawableState, CHECKED_STATE_SET); } return drawableState; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract.Announcements; import com.google.android.apps.iosched.util.TimeUtils; import com.google.android.apps.iosched.util.UIUtils; import android.content.ActivityNotFoundException; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.TextView; /** * A fragment used in {@link HomeActivity} that shows either a countdown, * Announcements, or 'thank you' text, at different times (before/during/after * the conference). */ public class WhatsOnFragment extends Fragment implements LoaderCallbacks<Cursor> { private static final int ANNOUNCEMENTS_LOADER_ID = 0; private static final int ANNOUNCEMENTS_CYCLE_INTERVAL_MILLIS = 6000; private Handler mHandler = new Handler(); private TextView mCountdownTextView; private ViewGroup mRootView; private View mAnnouncementView; private Cursor mAnnouncementsCursor; private String mLatestAnnouncementId; private LayoutInflater mInflater; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mInflater = inflater; mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_whats_on, container); refresh(); return mRootView; } @Override public void onDetach() { super.onDetach(); mHandler.removeCallbacksAndMessages(null); getActivity().getContentResolver().unregisterContentObserver(mObserver); } private void refresh() { mHandler.removeCallbacksAndMessages(null); mRootView.removeAllViews(); final long currentTimeMillis = UIUtils.getCurrentTime(getActivity()); // Show Loading... and load the view corresponding to the current state if (currentTimeMillis < UIUtils.CONFERENCE_START_MILLIS) { setupBefore(); } else if (currentTimeMillis > UIUtils.CONFERENCE_END_MILLIS) { setupAfter(); } else { setupDuring(); } } private void setupBefore() { // Before conference, show countdown. mCountdownTextView = (TextView) mInflater .inflate(R.layout.whats_on_countdown, mRootView, false); mRootView.addView(mCountdownTextView); mHandler.post(mCountdownRunnable); } private void setupAfter() { // After conference, show canned text. mInflater.inflate(R.layout.whats_on_thank_you, mRootView, true); } private void setupDuring() { // Start background query to load announcements getLoaderManager().initLoader(ANNOUNCEMENTS_LOADER_ID, null, this); getActivity().getContentResolver().registerContentObserver( Announcements.CONTENT_URI, true, mObserver); } /** * Event that updates countdown timer. Posts itself again to * {@link #mHandler} to continue updating time. */ private Runnable mCountdownRunnable = new Runnable() { public void run() { int remainingSec = (int) Math.max(0, (UIUtils.CONFERENCE_START_MILLIS - UIUtils .getCurrentTime(getActivity())) / 1000); final boolean conferenceStarted = remainingSec == 0; if (conferenceStarted) { // Conference started while in countdown mode, switch modes and // bail on future countdown updates. mHandler.postDelayed(new Runnable() { public void run() { refresh(); } }, 100); return; } final int secs = remainingSec % 86400; final int days = remainingSec / 86400; final String str; if (days == 0) { str = getResources().getString( R.string.whats_on_countdown_title_0, DateUtils.formatElapsedTime(secs)); } else { str = getResources().getQuantityString( R.plurals.whats_on_countdown_title, days, days, DateUtils.formatElapsedTime(secs)); } mCountdownTextView.setText(str); // Repost ourselves to keep updating countdown mHandler.postDelayed(mCountdownRunnable, 1000); } }; @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader(getActivity(), Announcements.CONTENT_URI, AnnouncementsQuery.PROJECTION, null, null, Announcements.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } if (cursor != null && cursor.getCount() > 0) { // Need to always set this because original gets unset in onLoaderReset mAnnouncementsCursor = cursor; cursor.moveToFirst(); // Only update announcements if there's a new one String latestAnnouncementId = cursor.getString(AnnouncementsQuery.ANNOUNCEMENT_ID); if (!latestAnnouncementId.equals(mLatestAnnouncementId)) { mHandler.removeCallbacks(mCycleAnnouncementsRunnable); mLatestAnnouncementId = latestAnnouncementId; showAnnouncements(); } } else { mHandler.removeCallbacks(mCycleAnnouncementsRunnable); showNoAnnouncements(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { mAnnouncementsCursor = null; } /** * Show the the announcements */ private void showAnnouncements() { mAnnouncementsCursor.moveToFirst(); ViewGroup announcementsRootView = (ViewGroup) mInflater.inflate( R.layout.whats_on_announcements, mRootView, false); mAnnouncementView = announcementsRootView.findViewById(R.id.announcement_container); // Begin cycling in announcements mHandler.post(mCycleAnnouncementsRunnable); final View moreButton = announcementsRootView.findViewById(R.id.extra_button); moreButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(getActivity(), AnnouncementsActivity.class)); } }); mRootView.removeAllViews(); mRootView.addView(announcementsRootView); } private Runnable mCycleAnnouncementsRunnable = new Runnable() { @Override public void run() { // First animate the current announcement out final int animationDuration = getResources().getInteger(android.R.integer.config_shortAnimTime); final int height = mAnnouncementView.getHeight(); TranslateAnimation anim = new TranslateAnimation(0, 0, 0, height); anim.setDuration(animationDuration); anim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationEnd(Animation animation) { // Set the announcement data TextView titleView = (TextView) mAnnouncementView.findViewById( R.id.announcement_title); TextView agoView = (TextView) mAnnouncementView.findViewById( R.id.announcement_ago); titleView.setText(mAnnouncementsCursor.getString( AnnouncementsQuery.ANNOUNCEMENT_TITLE)); long date = mAnnouncementsCursor.getLong( AnnouncementsQuery.ANNOUNCEMENT_DATE); String when = TimeUtils.getTimeAgo(date, getActivity()); agoView.setText(when); final String url = mAnnouncementsCursor.getString( AnnouncementsQuery.ANNOUNCEMENT_URL); mAnnouncementView.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { Intent announcementIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); announcementIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); UIUtils.preferPackageForIntent(getActivity(), announcementIntent, UIUtils.GOOGLE_PLUS_PACKAGE_NAME); try { startActivity(announcementIntent); } catch (ActivityNotFoundException ignored) { } } }); int nextPosition = (mAnnouncementsCursor.getPosition() + 1) % mAnnouncementsCursor.getCount(); mAnnouncementsCursor.moveToPosition(nextPosition); // Animate the announcement in TranslateAnimation anim = new TranslateAnimation(0, 0, height, 0); anim.setDuration(animationDuration); mAnnouncementView.startAnimation(anim); mHandler.postDelayed(mCycleAnnouncementsRunnable, ANNOUNCEMENTS_CYCLE_INTERVAL_MILLIS + animationDuration); } @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }); mAnnouncementView.startAnimation(anim); } }; /** * Show a placeholder message */ private void showNoAnnouncements() { mRootView.removeAllViews(); mInflater.inflate(R.layout.empty_announcements, mRootView, true); } private ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (getActivity() == null) { return; } getLoaderManager().restartLoader(ANNOUNCEMENTS_LOADER_ID, null, WhatsOnFragment.this); } }; private interface AnnouncementsQuery { String[] PROJECTION = { Announcements.ANNOUNCEMENT_ID, Announcements.ANNOUNCEMENT_TITLE, Announcements.ANNOUNCEMENT_DATE, Announcements.ANNOUNCEMENT_URL, }; int ANNOUNCEMENT_ID = 0; int ANNOUNCEMENT_TITLE = 1; int ANNOUNCEMENT_DATE = 2; int ANNOUNCEMENT_URL = 3; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import android.annotation.TargetApi; import android.app.SearchManager; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.Menu; import android.view.MenuItem; import android.widget.SearchView; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity; import com.google.android.apps.iosched.util.UIUtils; public class SessionsActivity extends SimpleSinglePaneActivity implements SessionsFragment.Callbacks { @Override protected Fragment onCreatePane() { return new SessionsFragment(); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.search, menu); MenuItem searchItem = menu.findItem(R.id.menu_search); if (searchItem != null && UIUtils.hasHoneycomb()) { SearchView searchView = (SearchView) searchItem.getActionView(); if (searchView != null) { SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setQueryRefinementEnabled(true); } } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_search: if (!UIUtils.hasHoneycomb()) { startSearch(null, false, Bundle.EMPTY, false); return true; } break; } return super.onOptionsItemSelected(item); } @Override public boolean onSessionSelected(String sessionId) { startActivity(new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(sessionId))); return false; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.*; import com.google.android.apps.iosched.ui.SandboxDetailFragment; import com.google.android.apps.iosched.util.ImageLoader; import com.google.android.apps.iosched.util.UIUtils; public class SandboxDetailActivity extends SimpleSinglePaneActivity implements SandboxDetailFragment.Callbacks, TrackInfoHelperFragment.Callbacks, ImageLoader.ImageLoaderProvider { private String mTrackId = null; private ImageLoader mImageLoader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mImageLoader = new ImageLoader(this, R.drawable.sandbox_logo_empty) .setMaxImageSize(getResources().getDimensionPixelSize( R.dimen.sandbox_company_image_size)) .setFadeInImage(UIUtils.hasHoneycombMR1()); } @Override protected Fragment onCreatePane() { return new SandboxDetailFragment(); } @Override public Intent getParentActivityIntent() { // Up to this company's track details, or Home if no track is available if (mTrackId != null) { return new Intent(Intent.ACTION_VIEW, ScheduleContract.Tracks.buildTrackUri(mTrackId)); } else { return new Intent(this, HomeActivity.class); } } @Override public void onTrackInfoAvailable(String trackId, TrackInfo track) { mTrackId = trackId; setTitle(track.name); setActionBarTrackIcon(track.name, track.color); } @Override public void onTrackIdAvailable(final String trackId) { new Handler().post(new Runnable() { @Override public void run() { FragmentManager fm = getSupportFragmentManager(); if (fm.findFragmentByTag("track_info") == null) { fm.beginTransaction() .add(TrackInfoHelperFragment.newFromTrackUri( ScheduleContract.Tracks.buildTrackUri(trackId)), "track_info") .commit(); } } }); } @Override public ImageLoader getImageLoaderInstance() { return mImageLoader; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import android.content.Intent; import android.support.v4.app.Fragment; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.MapFragment; import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity; public class MapActivity extends SimpleSinglePaneActivity implements MapFragment.Callbacks { @Override protected Fragment onCreatePane() { return new MapFragment(); } @Override public void onSessionRoomSelected(String roomId, String roomTitle) { Intent roomIntent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Rooms.buildSessionsDirUri(roomId)); roomIntent.putExtra(Intent.EXTRA_TITLE, roomTitle); startActivity(roomIntent); } @Override public void onSandboxRoomSelected(String trackId, String roomTitle) { Intent intent = new Intent(this,TrackDetailActivity.class); intent.setData( ScheduleContract.Tracks.buildSandboxUri(trackId)); intent.putExtra(Intent.EXTRA_TITLE, roomTitle); startActivity(intent); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.TaskStackBuilder; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.*; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.ImageLoader; import com.google.android.apps.iosched.util.UIUtils; public class SessionDetailActivity extends SimpleSinglePaneActivity implements TrackInfoHelperFragment.Callbacks, ImageLoader.ImageLoaderProvider { private String mTrackId = null; private ImageLoader mImageLoader; @Override protected void onCreate(Bundle savedInstanceState) { UIUtils.tryTranslateHttpIntent(this); BeamUtils.tryUpdateIntentFromBeam(this); super.onCreate(savedInstanceState); if (savedInstanceState == null) { Uri sessionUri = getIntent().getData(); BeamUtils.setBeamSessionUri(this, sessionUri); getSupportFragmentManager().beginTransaction() .add(TrackInfoHelperFragment.newFromSessionUri(sessionUri), "track_info") .commit(); } mImageLoader = new ImageLoader(this, R.drawable.person_image_empty) .setMaxImageSize(getResources().getDimensionPixelSize(R.dimen.speaker_image_size)) .setFadeInImage(UIUtils.hasHoneycombMR1()); } @Override protected Fragment onCreatePane() { return new SessionDetailFragment(); } @Override public Intent getParentActivityIntent() { // Up to this session's track details, or Home if no track is available if (mTrackId != null) { return new Intent(Intent.ACTION_VIEW, ScheduleContract.Tracks.buildTrackUri(mTrackId)); } else { return new Intent(this, HomeActivity.class); } } @Override public void onTrackInfoAvailable(String trackId, TrackInfo track) { mTrackId = trackId; setTitle(track.name); setActionBarTrackIcon(track.name, track.color); } @Override public ImageLoader getImageLoaderInstance() { return mImageLoader; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import android.view.Menu; import android.view.MenuItem; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.*; import com.google.android.apps.iosched.util.UIUtils; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.provider.ScheduleContract.Sessions.QUERY_PARAMETER_FILTER; import static com.google.android.apps.iosched.provider.ScheduleContract.Sessions.QUERY_VALUE_FILTER_SESSIONS_CODELABS_ONLY; import static com.google.android.apps.iosched.provider.ScheduleContract.Sessions.QUERY_VALUE_FILTER_OFFICE_HOURS_ONLY; import static com.google.android.apps.iosched.util.LogUtils.LOGD; public class TrackDetailActivity extends BaseActivity implements ActionBar.TabListener, ViewPager.OnPageChangeListener, SessionsFragment.Callbacks, SandboxFragment.Callbacks, TrackInfoHelperFragment.Callbacks { private static final int TAB_SESSIONS = 100; private static final int TAB_OFFICE_HOURS = 101; private static final int TAB_SANDBOX = 102; private ViewPager mViewPager; private String mTrackId; private String mHashtag; private List<Integer> mTabs = new ArrayList<Integer>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_track_detail); Uri trackUri = getIntent().getData(); mTrackId = ScheduleContract.Tracks.getTrackId(trackUri); mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(new TrackDetailPagerAdapter(getSupportFragmentManager())); mViewPager.setOnPageChangeListener(this); mViewPager.setPageMarginDrawable(R.drawable.grey_border_inset_lr); mViewPager.setPageMargin(getResources().getDimensionPixelSize(R.dimen.page_margin_width)); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(TrackInfoHelperFragment.newFromTrackUri(trackUri), "track_info") .commit(); } } @Override public Intent getParentActivityIntent() { return new Intent(this, HomeActivity.class) .putExtra(HomeActivity.EXTRA_DEFAULT_TAB, HomeActivity.TAB_EXPLORE); } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int position) { getSupportActionBar().setSelectedNavigationItem(position); int titleId = -1; switch (position) { case 0: titleId = R.string.title_sessions; break; case 1: titleId = R.string.title_office_hours; break; case 2: titleId = R.string.title_sandbox; break; } String title = getString(titleId); EasyTracker.getTracker().sendView(title + ": " + getTitle()); LOGD("Tracker", title + ": " + getTitle()); } @Override public void onPageScrollStateChanged(int i) { } private class TrackDetailPagerAdapter extends FragmentPagerAdapter { public TrackDetailPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { boolean allTracks = (ScheduleContract.Tracks.ALL_TRACK_ID.equals(mTrackId)); switch (mTabs.get(position)) { case TAB_SESSIONS: { Fragment fragment = new SessionsFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments(new Intent( Intent.ACTION_VIEW, (allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(mTrackId)) .buildUpon() .appendQueryParameter(QUERY_PARAMETER_FILTER, QUERY_VALUE_FILTER_SESSIONS_CODELABS_ONLY) .build() ))); return fragment; } case TAB_OFFICE_HOURS: { Fragment fragment = new SessionsFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments(new Intent( Intent.ACTION_VIEW, (allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(mTrackId)) .buildUpon() .appendQueryParameter(QUERY_PARAMETER_FILTER, QUERY_VALUE_FILTER_OFFICE_HOURS_ONLY) .build()))); return fragment; } case TAB_SANDBOX: default: { Fragment fragment = new SandboxFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments(new Intent( Intent.ACTION_VIEW, allTracks ? ScheduleContract.Sandbox.CONTENT_URI : ScheduleContract.Tracks.buildSandboxUri(mTrackId)))); return fragment; } } } @Override public int getCount() { return mTabs.size(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.track_detail, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_social_stream: Intent intent = new Intent(this, SocialStreamActivity.class); intent.putExtra(SocialStreamFragment.EXTRA_QUERY, UIUtils.getSessionHashtagsString(mHashtag)); startActivity(intent); break; } return super.onOptionsItemSelected(item); } @Override public void onTrackInfoAvailable(String trackId, TrackInfo track) { setTitle(track.name); setActionBarTrackIcon(track.name, track.color); mHashtag = track.hashtag; switch (track.meta) { case ScheduleContract.Tracks.TRACK_META_SESSIONS_ONLY: mTabs.add(TAB_SESSIONS); break; case ScheduleContract.Tracks.TRACK_META_SANDBOX_OFFICE_HOURS_ONLY: mTabs.add(TAB_OFFICE_HOURS); mTabs.add(TAB_SANDBOX); break; case ScheduleContract.Tracks.TRACK_META_OFFICE_HOURS_ONLY: mTabs.add(TAB_OFFICE_HOURS); break; case ScheduleContract.Tracks.TRACK_META_NONE: default: mTabs.add(TAB_SESSIONS); mTabs.add(TAB_OFFICE_HOURS); mTabs.add(TAB_SANDBOX); break; } mViewPager.getAdapter().notifyDataSetChanged(); if (mTabs.size() > 1) { setHasTabs(); final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); for (int tab : mTabs) { int titleResId; switch (tab) { case TAB_SANDBOX: titleResId = R.string.title_sandbox; break; case TAB_OFFICE_HOURS: titleResId = R.string.title_office_hours; break; case TAB_SESSIONS: default: titleResId = R.string.title_sessions; break; } actionBar.addTab(actionBar.newTab().setText(titleResId).setTabListener(this)); } } } @Override public boolean onSessionSelected(String sessionId) { startActivity(new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(sessionId))); return false; } @Override public boolean onCompanySelected(String companyId) { startActivity(new Intent(Intent.ACTION_VIEW, ScheduleContract.Sandbox.buildCompanyUri(companyId))); return false; } }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceActivity; import com.google.android.apps.iosched.R; /** * Activity for customizing app settings. */ public class SettingsActivity extends PreferenceActivity { @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB) protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) { getActionBar().setDisplayHomeAsUpEnabled(true); } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); setupSimplePreferencesScreen(); } private void setupSimplePreferencesScreen() { // Add 'general' preferences. addPreferencesFromResource(R.xml.preferences); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.TracksAdapter; import com.google.android.apps.iosched.util.ParserUtils; import android.annotation.TargetApi; import android.app.Activity; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListPopupWindow; import android.widget.PopupWindow; import android.widget.TextView; /** * A tablet-specific fragment that is a giant {@link android.widget.Spinner} * -like widget. It shows a {@link ListPopupWindow} containing a list of tracks, * using {@link TracksAdapter}. Requires API level 11 or later since * {@link ListPopupWindow} is API level 11+. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class TracksDropdownFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>, AdapterView.OnItemClickListener, PopupWindow.OnDismissListener { public static final int VIEW_TYPE_SESSIONS = 0; public static final int VIEW_TYPE_OFFICE_HOURS = 1; public static final int VIEW_TYPE_SANDBOX = 2; private static final String STATE_VIEW_TYPE = "viewType"; private static final String STATE_SELECTED_TRACK_ID = "selectedTrackId"; private TracksAdapter mAdapter; private int mViewType; private Handler mHandler = new Handler(); private ListPopupWindow mListPopupWindow; private ViewGroup mRootView; private ImageView mIcon; private TextView mTitle; private TextView mAbstract; private String mTrackId; public interface Callbacks { public void onTrackSelected(String trackId); public void onTrackNameAvailable(String trackId, String trackName); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onTrackSelected(String trackId) { } @Override public void onTrackNameAvailable(String trackId, String trackName) {} }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAdapter = new TracksAdapter(getActivity(), true); if (savedInstanceState != null) { // Since this fragment doesn't rely on fragment arguments, we must // handle state restores and saves ourselves. mViewType = savedInstanceState.getInt(STATE_VIEW_TYPE); mTrackId = savedInstanceState.getString(STATE_SELECTED_TRACK_ID); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_VIEW_TYPE, mViewType); outState.putString(STATE_SELECTED_TRACK_ID, mTrackId); } public String getSelectedTrackId() { return mTrackId; } public void selectTrack(String trackId) { loadTrackList(mViewType, trackId); } public void loadTrackList(int viewType) { loadTrackList(viewType, mTrackId); } public void loadTrackList(int viewType, String selectTrackId) { // Teardown from previous arguments if (mListPopupWindow != null) { mListPopupWindow.setAdapter(null); } mViewType = viewType; mTrackId = selectTrackId; // Start background query to load tracks getLoaderManager().restartLoader(TracksAdapter.TracksQuery._TOKEN, null, this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_tracks_dropdown, null); mIcon = (ImageView) mRootView.findViewById(R.id.track_icon); mTitle = (TextView) mRootView.findViewById(R.id.track_title); mAbstract = (TextView) mRootView.findViewById(R.id.track_abstract); mRootView.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mListPopupWindow = new ListPopupWindow(getActivity()); mListPopupWindow.setAdapter(mAdapter); mListPopupWindow.setModal(true); mListPopupWindow.setContentWidth( getResources().getDimensionPixelSize(R.dimen.track_dropdown_width)); mListPopupWindow.setAnchorView(mRootView); mListPopupWindow.setOnItemClickListener(TracksDropdownFragment.this); mListPopupWindow.show(); mListPopupWindow.setOnDismissListener(TracksDropdownFragment.this); } }); return mRootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; if (mListPopupWindow != null) { mListPopupWindow.dismiss(); } } /** {@inheritDoc} */ public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position); loadTrack(cursor, true); if (mListPopupWindow != null) { mListPopupWindow.dismiss(); } } public String getTrackName() { return (String) mTitle.getText(); } private void loadTrack(Cursor cursor, boolean triggerCallback) { final int trackColor; final Resources res = getResources(); if (cursor != null) { trackColor = cursor.getInt(TracksAdapter.TracksQuery.TRACK_COLOR); mTrackId = cursor.getString(TracksAdapter.TracksQuery.TRACK_ID); String trackName = cursor.getString(TracksAdapter.TracksQuery.TRACK_NAME); mTitle.setText(trackName); mAbstract.setText(cursor.getString(TracksAdapter.TracksQuery.TRACK_ABSTRACT)); int iconResId = res.getIdentifier( "track_" + ParserUtils.sanitizeId(trackName), "drawable", getActivity().getPackageName()); if (iconResId != 0) { BitmapDrawable sourceIconDrawable = (BitmapDrawable) res.getDrawable(iconResId); Bitmap icon = Bitmap.createBitmap(sourceIconDrawable.getIntrinsicWidth(), sourceIconDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(icon); sourceIconDrawable.setBounds(0, 0, icon.getWidth(), icon.getHeight()); sourceIconDrawable.draw(canvas); BitmapDrawable iconDrawable = new BitmapDrawable(res, icon); mIcon.setImageDrawable(iconDrawable); } else { mIcon.setImageDrawable(null); } } else { trackColor = res.getColor(R.color.all_track_color); mTrackId = ScheduleContract.Tracks.ALL_TRACK_ID; mIcon.setImageDrawable(null); switch (mViewType) { case VIEW_TYPE_SESSIONS: mTitle.setText(R.string.all_tracks_sessions); mAbstract.setText(R.string.all_tracks_subtitle_sessions); break; case VIEW_TYPE_OFFICE_HOURS: mTitle.setText(R.string.all_tracks_office_hours); mAbstract.setText(R.string.all_tracks_subtitle_office_hours); break; case VIEW_TYPE_SANDBOX: mTitle.setText(R.string.all_tracks_sandbox); mAbstract.setText(R.string.all_tracks_subtitle_sandbox); break; } } mRootView.setBackgroundColor(trackColor); mCallbacks.onTrackNameAvailable(mTrackId, mTitle.getText().toString()); if (triggerCallback) { mHandler.post(new Runnable() { @Override public void run() { mCallbacks.onTrackSelected(mTrackId); } }); } } public void onDismiss() { mListPopupWindow = null; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { // Filter our tracks query to only include those with valid results String[] projection = TracksAdapter.TracksQuery.PROJECTION; String selection = null; switch (mViewType) { case VIEW_TYPE_SESSIONS: // Only show tracks with at least one session projection = TracksAdapter.TracksQuery.PROJECTION_WITH_SESSIONS_COUNT; selection = ScheduleContract.Tracks.SESSIONS_COUNT + ">0"; break; case VIEW_TYPE_OFFICE_HOURS: // Only show tracks with at least one office hours projection = TracksAdapter.TracksQuery.PROJECTION_WITH_OFFICE_HOURS_COUNT; selection = ScheduleContract.Tracks.OFFICE_HOURS_COUNT + ">0"; break; case VIEW_TYPE_SANDBOX: // Only show tracks with at least one company projection = TracksAdapter.TracksQuery.PROJECTION_WITH_SANDBOX_COUNT; selection = ScheduleContract.Tracks.SANDBOX_COUNT + ">0"; break; } return new CursorLoader(getActivity(), ScheduleContract.Tracks.CONTENT_URI, projection, selection, null, ScheduleContract.Tracks.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null || cursor == null) { return; } boolean trackLoaded = false; if (mTrackId != null) { cursor.moveToFirst(); while (!cursor.isAfterLast()) { if (mTrackId.equals(cursor.getString(TracksAdapter.TracksQuery.TRACK_ID))) { loadTrack(cursor, false); trackLoaded = true; break; } cursor.moveToNext(); } } if (!trackLoaded) { loadTrack(null, false); } mAdapter.setHasAllItem(true); mAdapter.changeCursor(cursor); } @Override public void onLoaderReset(Loader<Cursor> cusor) { } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.tablet; import android.annotation.TargetApi; import android.app.SearchManager; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.widget.SlidingPaneLayout; import android.support.v7.app.ActionBar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.SearchView; import android.widget.SpinnerAdapter; import android.widget.TextView; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.*; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.ImageLoader; import com.google.android.apps.iosched.util.UIUtils; import static com.google.android.apps.iosched.util.LogUtils.LOGD; /** * A multi-pane activity, consisting of a {@link TracksDropdownFragment}, a * {@link SessionsFragment} or {@link com.google.android.apps.iosched.ui.SandboxFragment}, and {@link SessionDetailFragment} or * {@link com.google.android.apps.iosched.ui.SandboxDetailFragment}. * * This activity requires API level 11 or greater. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class SessionsSandboxMultiPaneActivity extends BaseActivity implements ActionBar.OnNavigationListener, SessionsFragment.Callbacks, SandboxFragment.Callbacks, SandboxDetailFragment.Callbacks, TracksDropdownFragment.Callbacks, TrackInfoHelperFragment.Callbacks, ImageLoader.ImageLoaderProvider { public static final String EXTRA_MASTER_URI = "com.google.android.apps.iosched.extra.MASTER_URI"; public static final String EXTRA_DEFAULT_VIEW_TYPE = "com.google.android.apps.iosched.extra.DEFAULT_VIEW_TYPE"; private static final String STATE_VIEW_TYPE = "view_type"; private TracksDropdownFragment mTracksDropdownFragment; private Fragment mDetailFragment; private boolean mFullUI = false; private SlidingPaneLayout mSlidingPaneLayout; private int mViewType; private boolean mInitialTabSelect = true; private ImageLoader mImageLoader; @Override protected void onCreate(Bundle savedInstanceState) { UIUtils.tryTranslateHttpIntent(this); BeamUtils.tryUpdateIntentFromBeam(this); super.onCreate(savedInstanceState); setContentView(R.layout.activity_sessions_sandbox); final FragmentManager fm = getSupportFragmentManager(); mTracksDropdownFragment = (TracksDropdownFragment) fm.findFragmentById( R.id.fragment_tracks_dropdown); mSlidingPaneLayout = (SlidingPaneLayout) findViewById(R.id.sliding_pane_layout); // Offset the left pane by its full width and left margin when collapsed // (ViewPager-like presentation) mSlidingPaneLayout.setParallaxDistance( getResources().getDimensionPixelSize(R.dimen.sliding_pane_width) + getResources().getDimensionPixelSize(R.dimen.multipane_padding)); mSlidingPaneLayout.setSliderFadeColor(getResources().getColor( R.color.sliding_pane_content_fade)); routeIntent(getIntent(), savedInstanceState != null); if (savedInstanceState != null) { if (mFullUI) { int viewType = savedInstanceState.getInt(STATE_VIEW_TYPE); getSupportActionBar().setSelectedNavigationItem(viewType); } mDetailFragment = fm.findFragmentById(R.id.fragment_container_detail); updateDetailBackground(); } // This flag prevents onTabSelected from triggering extra master pane reloads // unless it's actually being triggered by the user (and not automatically by // the system) mInitialTabSelect = false; mImageLoader = new ImageLoader(this, R.drawable.person_image_empty) .setMaxImageSize(getResources().getDimensionPixelSize(R.dimen.speaker_image_size)) .setFadeInImage(UIUtils.hasHoneycombMR1()); EasyTracker.getInstance().setContext(this); } private void routeIntent(Intent intent, boolean updateSurfaceOnly) { Uri uri = intent.getData(); if (uri == null) { return; } if (intent.hasExtra(Intent.EXTRA_TITLE)) { setTitle(intent.getStringExtra(Intent.EXTRA_TITLE)); } String mimeType = getContentResolver().getType(uri); if (ScheduleContract.Tracks.CONTENT_ITEM_TYPE.equals(mimeType)) { // Load track details showFullUI(true); if (!updateSurfaceOnly) { // TODO: don't assume the URI will contain the track ID int defaultViewType = intent.getIntExtra(EXTRA_DEFAULT_VIEW_TYPE, TracksDropdownFragment.VIEW_TYPE_SESSIONS); String selectedTrackId = ScheduleContract.Tracks.getTrackId(uri); loadTrackList(defaultViewType, selectedTrackId); getSupportActionBar().setSelectedNavigationItem(defaultViewType); onTrackSelected(selectedTrackId); mSlidingPaneLayout.openPane(); } } else if (ScheduleContract.Sessions.CONTENT_TYPE.equals(mimeType)) { // Load a session list, hiding the tracks dropdown and the tabs mViewType = TracksDropdownFragment.VIEW_TYPE_SESSIONS; showFullUI(false); if (!updateSurfaceOnly) { loadSessionList(uri, null); mSlidingPaneLayout.openPane(); } } else if (ScheduleContract.Sessions.CONTENT_ITEM_TYPE.equals(mimeType)) { // Load session details if (intent.hasExtra(EXTRA_MASTER_URI)) { mViewType = TracksDropdownFragment.VIEW_TYPE_SESSIONS; showFullUI(false); if (!updateSurfaceOnly) { loadSessionList((Uri) intent.getParcelableExtra(EXTRA_MASTER_URI), ScheduleContract.Sessions.getSessionId(uri)); loadSessionDetail(uri); } } else { mViewType = TracksDropdownFragment.VIEW_TYPE_SESSIONS; // prepare for onTrackInfo... showFullUI(true); if (!updateSurfaceOnly) { loadSessionDetail(uri); loadTrackInfoFromSessionUri(uri); } } } else if (ScheduleContract.Sandbox.CONTENT_TYPE.equals(mimeType)) { // Load a sandbox company list mViewType = TracksDropdownFragment.VIEW_TYPE_SANDBOX; showFullUI(false); if (!updateSurfaceOnly) { loadSandboxList(uri, null); mSlidingPaneLayout.openPane(); } } else if (ScheduleContract.Sandbox.CONTENT_ITEM_TYPE.equals(mimeType)) { // Load company details mViewType = TracksDropdownFragment.VIEW_TYPE_SANDBOX; showFullUI(false); if (!updateSurfaceOnly) { Uri masterUri = intent.getParcelableExtra(EXTRA_MASTER_URI); if (masterUri == null) { masterUri = ScheduleContract.Sandbox.CONTENT_URI; } loadSandboxList(masterUri, ScheduleContract.Sandbox.getCompanyId(uri)); loadSandboxDetail(uri); } } updateDetailBackground(); } private void showFullUI(boolean fullUI) { mFullUI = fullUI; final ActionBar actionBar = getSupportActionBar(); final FragmentManager fm = getSupportFragmentManager(); if (fullUI) { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); actionBar.setDisplayShowTitleEnabled(false); actionBar.setListNavigationCallbacks(mActionBarSpinnerAdapter, this); fm.beginTransaction() .show(fm.findFragmentById(R.id.fragment_tracks_dropdown)) .commit(); } else { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); fm.beginTransaction() .hide(fm.findFragmentById(R.id.fragment_tracks_dropdown)) .commit(); } } private SpinnerAdapter mActionBarSpinnerAdapter = new BaseAdapter() { @Override public int getCount() { return 3; } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position + 1; } private int getLabelResId(int position) { switch (position) { case TracksDropdownFragment.VIEW_TYPE_SESSIONS: return R.string.title_sessions; case TracksDropdownFragment.VIEW_TYPE_OFFICE_HOURS: return R.string.title_office_hours; case TracksDropdownFragment.VIEW_TYPE_SANDBOX: return R.string.title_sandbox; } return 0; } @Override public View getView(int position, View convertView, ViewGroup container) { if (convertView == null) { convertView = getLayoutInflater().inflate( android.R.layout.simple_spinner_item, container, false); } ((TextView) convertView.findViewById(android.R.id.text1)).setText( getLabelResId(position)); return convertView; } @Override public View getDropDownView(int position, View convertView, ViewGroup container) { if (convertView == null) { convertView = getLayoutInflater().inflate( android.R.layout.simple_spinner_dropdown_item, container, false); } ((TextView) convertView.findViewById(android.R.id.text1)).setText( getLabelResId(position)); return convertView; } }; @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.search, menu); MenuItem searchItem = menu.findItem(R.id.menu_search); if (searchItem != null && UIUtils.hasHoneycomb()) { SearchView searchView = (SearchView) searchItem.getActionView(); if (searchView != null) { SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setQueryRefinementEnabled(true); } } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: if (mSlidingPaneLayout.isSlideable() && !mSlidingPaneLayout.isOpen()) { // If showing the detail view, pressing Up should show the master pane. mSlidingPaneLayout.openPane(); return true; } break; case R.id.menu_search: if (!UIUtils.hasHoneycomb()) { startSearch(null, false, Bundle.EMPTY, false); return true; } break; } return super.onOptionsItemSelected(item); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_VIEW_TYPE, mViewType); } @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { loadTrackList(itemPosition); // itemPosition == view type if (!mInitialTabSelect) { onTrackSelected(mTracksDropdownFragment.getSelectedTrackId()); mSlidingPaneLayout.openPane(); } return true; } private void loadTrackList(int viewType) { loadTrackList(viewType, null); } private void loadTrackList(int viewType, String selectTrackId) { if (mDetailFragment != null && mViewType != viewType) { getSupportFragmentManager().beginTransaction() .remove(mDetailFragment) .commit(); mDetailFragment = null; } mViewType = viewType; if (selectTrackId != null) { mTracksDropdownFragment.loadTrackList(viewType, selectTrackId); } else { mTracksDropdownFragment.loadTrackList(viewType); } updateDetailBackground(); } private void updateDetailBackground() { if (mDetailFragment == null) { if (TracksDropdownFragment.VIEW_TYPE_SESSIONS == mViewType || TracksDropdownFragment.VIEW_TYPE_OFFICE_HOURS == mViewType) { findViewById(R.id.fragment_container_detail).setBackgroundResource( R.drawable.grey_frame_on_white_empty_sessions); } else { findViewById(R.id.fragment_container_detail).setBackgroundResource( R.drawable.grey_frame_on_white_empty_sandbox); } } else { findViewById(R.id.fragment_container_detail).setBackgroundResource( R.drawable.grey_frame_on_white); } } private void loadSessionList(Uri sessionsUri, String selectSessionId) { SessionsFragment fragment = new SessionsFragment(); fragment.setSelectedSessionId(selectSessionId); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, sessionsUri))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_master, fragment) .commit(); } private void loadSessionDetail(Uri sessionUri) { BeamUtils.setBeamSessionUri(this, sessionUri); SessionDetailFragment fragment = new SessionDetailFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, sessionUri))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .commit(); mDetailFragment = fragment; updateDetailBackground(); // If loading session details in portrait, hide the master pane mSlidingPaneLayout.closePane(); } private void loadSandboxList(Uri sandboxUri, String selectCompanyId) { SandboxFragment fragment = new SandboxFragment(); fragment.setSelectedCompanyId(selectCompanyId); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, sandboxUri))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_master, fragment) .commit(); } private void loadSandboxDetail(Uri companyUri) { SandboxDetailFragment fragment = new SandboxDetailFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, companyUri))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .commit(); mDetailFragment = fragment; updateDetailBackground(); // If loading session details in portrait, hide the master pane mSlidingPaneLayout.closePane(); } @Override public void onTrackNameAvailable(String trackId, String trackName) { String trackType = null; switch (mViewType) { case TracksDropdownFragment.VIEW_TYPE_SESSIONS: trackType = getString(R.string.title_sessions); break; case TracksDropdownFragment.VIEW_TYPE_OFFICE_HOURS: trackType = getString(R.string.title_office_hours); break; case TracksDropdownFragment.VIEW_TYPE_SANDBOX: trackType = getString(R.string.title_sandbox); break; } EasyTracker.getTracker().sendView(trackType + ": " + getTitle()); LOGD("Tracker", trackType + ": " + mTracksDropdownFragment.getTrackName()); } @Override public void onTrackSelected(String trackId) { boolean allTracks = (ScheduleContract.Tracks.ALL_TRACK_ID.equals(trackId)); switch (mViewType) { case TracksDropdownFragment.VIEW_TYPE_SESSIONS: loadSessionList((allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(trackId)) .buildUpon() .appendQueryParameter(ScheduleContract.Sessions.QUERY_PARAMETER_FILTER, ScheduleContract.Sessions.QUERY_VALUE_FILTER_SESSIONS_CODELABS_ONLY) .build(), null); break; case TracksDropdownFragment.VIEW_TYPE_OFFICE_HOURS: loadSessionList((allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(trackId)) .buildUpon() .appendQueryParameter( ScheduleContract.Sessions.QUERY_PARAMETER_FILTER, ScheduleContract.Sessions.QUERY_VALUE_FILTER_OFFICE_HOURS_ONLY) .build(), null); break; case TracksDropdownFragment.VIEW_TYPE_SANDBOX: loadSandboxList(allTracks ? ScheduleContract.Sandbox.CONTENT_URI : ScheduleContract.Tracks.buildSandboxUri(trackId), null); break; } } @Override public boolean onSessionSelected(String sessionId) { loadSessionDetail(ScheduleContract.Sessions.buildSessionUri(sessionId)); return true; } @Override public boolean onCompanySelected(String companyId) { loadSandboxDetail(ScheduleContract.Sandbox.buildCompanyUri(companyId)); return true; } private TrackInfoHelperFragment mTrackInfoHelperFragment; private String mTrackInfoLoadCookie; private void loadTrackInfoFromSessionUri(Uri sessionUri) { mTrackInfoLoadCookie = ScheduleContract.Sessions.getSessionId(sessionUri); Uri trackDirUri = ScheduleContract.Sessions.buildTracksDirUri( ScheduleContract.Sessions.getSessionId(sessionUri)); android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); if (mTrackInfoHelperFragment != null) { ft.remove(mTrackInfoHelperFragment); } mTrackInfoHelperFragment = TrackInfoHelperFragment.newFromTrackUri(trackDirUri); ft.add(mTrackInfoHelperFragment, "track_info").commit(); } @Override public void onTrackInfoAvailable(String trackId, TrackInfo track) { loadTrackList(mViewType, trackId); boolean allTracks = (ScheduleContract.Tracks.ALL_TRACK_ID.equals(trackId)); switch (mViewType) { case TracksDropdownFragment.VIEW_TYPE_SESSIONS: loadSessionList((allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(trackId)) .buildUpon() .appendQueryParameter(ScheduleContract.Sessions.QUERY_PARAMETER_FILTER, ScheduleContract.Sessions.QUERY_VALUE_FILTER_SESSIONS_CODELABS_ONLY) .build(), mTrackInfoLoadCookie); break; case TracksDropdownFragment.VIEW_TYPE_OFFICE_HOURS: loadSessionList((allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(trackId)) .buildUpon() .appendQueryParameter( ScheduleContract.Sessions.QUERY_PARAMETER_FILTER, ScheduleContract.Sessions.QUERY_VALUE_FILTER_OFFICE_HOURS_ONLY) .build(), mTrackInfoLoadCookie); break; case TracksDropdownFragment.VIEW_TYPE_SANDBOX: loadSandboxList(allTracks ? ScheduleContract.Sandbox.CONTENT_URI : ScheduleContract.Tracks.buildSandboxUri(trackId), mTrackInfoLoadCookie); break; } } @Override public void onTrackIdAvailable(String trackId) { } @Override public ImageLoader getImageLoaderInstance() { return mImageLoader; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.tablet; import android.annotation.TargetApi; import android.app.FragmentBreadCrumbs; import android.content.Intent; import android.content.res.Configuration; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.*; import com.google.android.apps.iosched.ui.SandboxDetailFragment; /** * A multi-pane activity, where the primary navigation pane is a * {@link MapFragment}, that shows {@link SessionsFragment}, * {@link SessionDetailFragment}, {@link com.google.android.apps.iosched.ui.SandboxFragment}, and * {@link com.google.android.apps.iosched.ui.SandboxDetailFragment} as popups. This activity requires API level 11 * or greater because of its use of {@link FragmentBreadCrumbs}. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class MapMultiPaneActivity extends BaseActivity implements FragmentManager.OnBackStackChangedListener, MapFragment.Callbacks, SessionsFragment.Callbacks, SandboxFragment.Callbacks, SandboxDetailFragment.Callbacks{ private boolean mPauseBackStackWatcher = false; private FragmentBreadCrumbs mFragmentBreadCrumbs; private String mSelectedRoomName; private MapFragment mMapFragment; private boolean isSessionShown = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); FragmentManager fm = getSupportFragmentManager(); fm.addOnBackStackChangedListener(this); mFragmentBreadCrumbs = (FragmentBreadCrumbs) findViewById(R.id.breadcrumbs); mFragmentBreadCrumbs.setActivity(this); mMapFragment = (MapFragment) fm.findFragmentByTag("map"); if (mMapFragment == null) { mMapFragment = new MapFragment(); mMapFragment.setArguments(intentToFragmentArguments(getIntent())); fm.beginTransaction() .add(R.id.fragment_container_map, mMapFragment, "map") .commit(); } findViewById(R.id.close_button).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { clearBackStack(false); } }); updateBreadCrumbs(); onConfigurationChanged(getResources().getConfiguration()); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); boolean landscape = (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE); LinearLayout spacerView = (LinearLayout) findViewById(R.id.map_detail_spacer); spacerView.setOrientation(landscape ? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL); spacerView.setGravity(landscape ? Gravity.END : Gravity.BOTTOM); View popupView = findViewById(R.id.map_detail_popup); LinearLayout.LayoutParams popupLayoutParams = (LinearLayout.LayoutParams) popupView.getLayoutParams(); popupLayoutParams.width = landscape ? 0 : ViewGroup.LayoutParams.MATCH_PARENT; popupLayoutParams.height = landscape ? ViewGroup.LayoutParams.MATCH_PARENT : 0; popupView.setLayoutParams(popupLayoutParams); popupView.requestLayout(); updateMapPadding(); } private void clearBackStack(boolean pauseWatcher) { if (pauseWatcher) { mPauseBackStackWatcher = true; } FragmentManager fm = getSupportFragmentManager(); while (fm.getBackStackEntryCount() > 0) { fm.popBackStackImmediate(); } if (pauseWatcher) { mPauseBackStackWatcher = false; } } public void onBackStackChanged() { if (mPauseBackStackWatcher) { return; } if (getSupportFragmentManager().getBackStackEntryCount() == 0) { showDetailPane(false); } updateBreadCrumbs(); } private void showDetailPane(boolean show) { View detailPopup = findViewById(R.id.map_detail_spacer); if (show != (detailPopup.getVisibility() == View.VISIBLE)) { detailPopup.setVisibility(show ? View.VISIBLE : View.GONE); updateMapPadding(); } } private void updateMapPadding() { // Pan the map left or up depending on the orientation. boolean landscape = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; boolean detailShown = findViewById(R.id.map_detail_spacer).getVisibility() == View.VISIBLE; mMapFragment.setCenterPadding( landscape ? (detailShown ? 0.25f : 0f) : 0, landscape ? 0 : (detailShown ? 0.25f : 0)); } void updateBreadCrumbs() { String detailTitle; if(isSessionShown){ detailTitle = getString(R.string.title_session_detail); }else{ detailTitle = getString(R.string.title_sandbox_detail); } if (getSupportFragmentManager().getBackStackEntryCount() >= 2) { mFragmentBreadCrumbs.setParentTitle(mSelectedRoomName, mSelectedRoomName, mFragmentBreadCrumbsClickListener); mFragmentBreadCrumbs.setTitle(detailTitle, detailTitle); } else { mFragmentBreadCrumbs.setParentTitle(null, null, null); mFragmentBreadCrumbs.setTitle(mSelectedRoomName, mSelectedRoomName); } } private View.OnClickListener mFragmentBreadCrumbsClickListener = new View.OnClickListener() { @Override public void onClick(View view) { getSupportFragmentManager().popBackStack(); } }; @Override public void onSessionRoomSelected(String roomId, String roomTitle) { // Load room details mSelectedRoomName = roomTitle; isSessionShown = true; SessionsFragment fragment = new SessionsFragment(); Uri uri = ScheduleContract.Rooms.buildSessionsDirUri(roomId); showList(fragment,uri); } @Override public void onSandboxRoomSelected(String trackId, String roomTitle) { // Load room details mSelectedRoomName = roomTitle; isSessionShown = false; Fragment fragment = new SandboxFragment(); Uri uri = ScheduleContract.Tracks.buildSandboxUri(trackId); showList(fragment,uri); } @Override public boolean onCompanySelected(String companyId) { isSessionShown = false; final Uri uri = ScheduleContract.Sandbox.buildCompanyUri(companyId); SandboxDetailFragment fragment = new SandboxDetailFragment(); showDetails(fragment,uri); return false; } @Override public boolean onSessionSelected(String sessionId) { isSessionShown = true; final Uri uri = ScheduleContract.Sessions.buildSessionUri(sessionId); SessionDetailFragment fragment = new SessionDetailFragment(); showDetails(fragment,uri); return false; } private void showList(Fragment fragment, Uri uri){ // Show the sessions in the room clearBackStack(true); showDetailPane(true); fragment.setArguments(BaseActivity.intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, uri ))); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .addToBackStack(null) .commit(); updateBreadCrumbs(); } private void showDetails(Fragment fragment, Uri uri){ // Show the session details showDetailPane(true); Intent intent = new Intent(Intent.ACTION_VIEW,uri); intent.putExtra(SessionDetailFragment.EXTRA_VARIABLE_HEIGHT_HEADER, true); fragment.setArguments(BaseActivity.intentToFragmentArguments(intent)); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .addToBackStack(null) .commit(); updateBreadCrumbs(); } @Override public void onTrackIdAvailable(String trackId) { } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.ImageLoader; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A fragment that shows detail information for a sandbox company, including * company name, description, product description, logo, etc. */ public class SandboxDetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final String TAG = makeLogTag(SandboxDetailFragment.class); private Uri mCompanyUri; private TextView mName; private TextView mSubtitle; private ImageView mLogo; private TextView mUrl; private TextView mDesc; private ImageLoader mImageLoader; private int mCompanyImageSize; private Drawable mCompanyPlaceHolderImage; private StringBuilder mBuffer = new StringBuilder(); private String mRoomId; private String mCompanyName; public interface Callbacks { public void onTrackIdAvailable(String trackId); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onTrackIdAvailable(String trackId) {} }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mCompanyUri = intent.getData(); if (mCompanyUri == null) { return; } mCompanyImageSize = getResources().getDimensionPixelSize(R.dimen.sandbox_company_image_size); mCompanyPlaceHolderImage = getResources().getDrawable(R.drawable.sandbox_logo_empty); setHasOptionsMenu(true); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (mCompanyUri == null) { return; } if (getActivity() instanceof ImageLoader.ImageLoaderProvider) { mImageLoader = ((ImageLoader.ImageLoaderProvider) getActivity()).getImageLoaderInstance(); } // Start background query to load sandbox company details getLoaderManager().initLoader(SandboxQuery._TOKEN, null, this); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.sandbox_detail, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { SessionsHelper helper = new SessionsHelper(getActivity()); switch (item.getItemId()) { case R.id.menu_map: if (mRoomId != null && mCompanyName != null) { EasyTracker.getTracker().sendEvent( "Sandbox", "Map", mCompanyName, 0L); LOGD("Tracker", "Map: " + mCompanyName); helper.startMapActivity(mRoomId); return true; } } return false; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_sandbox_detail, null); mName = (TextView) rootView.findViewById(R.id.company_name); mLogo = (ImageView) rootView.findViewById(R.id.company_logo); mUrl = (TextView) rootView.findViewById(R.id.company_url); mDesc = (TextView) rootView.findViewById(R.id.company_desc); mSubtitle = (TextView) rootView.findViewById(R.id.company_subtitle); return rootView; } void buildUiFromCursor(Cursor cursor) { if (getActivity() == null) { return; } if (!cursor.moveToFirst()) { return; } mCompanyName = cursor.getString(SandboxQuery.NAME); mName.setText(mCompanyName); // Start background fetch to load company logo final String logoUrl = cursor.getString(SandboxQuery.LOGO_URL); if (!TextUtils.isEmpty(logoUrl) && mImageLoader != null) { mImageLoader.get(UIUtils.getConferenceImageUrl(logoUrl), mLogo, mCompanyPlaceHolderImage, mCompanyImageSize, mCompanyImageSize); mLogo.setVisibility(View.VISIBLE); } else { mLogo.setVisibility(View.GONE); } mRoomId = cursor.getString(SandboxQuery.ROOM_ID); // Set subtitle: time and room long blockStart = cursor.getLong(SandboxQuery.BLOCK_START); long blockEnd = cursor.getLong(SandboxQuery.BLOCK_END); String roomName = cursor.getString(SandboxQuery.ROOM_NAME); final String subtitle = UIUtils.formatSessionSubtitle( "Sandbox", blockStart, blockEnd, roomName, mBuffer, getActivity()); mSubtitle.setText(subtitle); mUrl.setText(cursor.getString(SandboxQuery.URL)); mDesc.setText(cursor.getString(SandboxQuery.DESC)); String trackId = cursor.getString(SandboxQuery.TRACK_ID); EasyTracker.getTracker().sendView("Sandbox Company: " + mCompanyName); LOGD("Tracker", "Sandbox Company: " + mCompanyName); mCallbacks.onTrackIdAvailable(trackId); } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sandbox} * query parameters. */ private interface SandboxQuery { int _TOKEN = 0x4; String[] PROJECTION = { ScheduleContract.Sandbox.COMPANY_NAME, ScheduleContract.Sandbox.COMPANY_DESC, ScheduleContract.Sandbox.COMPANY_URL, ScheduleContract.Sandbox.COMPANY_LOGO_URL, ScheduleContract.Sandbox.TRACK_ID, ScheduleContract.Sandbox.BLOCK_START, ScheduleContract.Sandbox.BLOCK_END, ScheduleContract.Sandbox.ROOM_NAME, ScheduleContract.Sandbox.ROOM_ID }; int NAME = 0; int DESC = 1; int URL = 2; int LOGO_URL = 3; int TRACK_ID = 4; int BLOCK_START = 5; int BLOCK_END = 6; int ROOM_NAME = 7; int ROOM_ID = 8; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(getActivity(), mCompanyUri, SandboxQuery.PROJECTION, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { buildUiFromCursor(cursor); } @Override public void onLoaderReset(Loader<Cursor> loader) { } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.ActionBarActivity; import android.support.v7.view.ActionMode; import android.util.Pair; import android.util.SparseBooleanArray; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AbsListView; import android.widget.Adapter; import android.widget.AdapterView; import android.widget.ListView; import java.util.HashSet; /** * Utilities for handling multiple selection in list views. Contains functionality similar to * {@link AbsListView#CHOICE_MODE_MULTIPLE_MODAL} but that works with {@link ActionBarActivity} and * backward-compatible action bars. */ public class MultiSelectionUtil { public static Controller attachMultiSelectionController(final ListView listView, final ActionBarActivity activity, final MultiChoiceModeListener listener) { return Controller.attach(listView, activity, listener); } public static class Controller implements ActionMode.Callback, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener { private Handler mHandler = new Handler(); private ActionMode mActionMode; private ListView mListView = null; private ActionBarActivity mActivity = null; private MultiChoiceModeListener mListener = null; private HashSet<Long> mTempIdsToCheckOnRestore; private HashSet<Pair<Integer, Long>> mItemsToCheck; private AdapterView.OnItemClickListener mOldItemClickListener; private Controller() { } public static Controller attach(ListView listView, ActionBarActivity activity, MultiChoiceModeListener listener) { Controller controller = new Controller(); controller.mListView = listView; controller.mActivity = activity; controller.mListener = listener; listView.setOnItemLongClickListener(controller); return controller; } private void readInstanceState(Bundle savedInstanceState) { mTempIdsToCheckOnRestore = null; if (savedInstanceState != null) { long[] checkedIds = savedInstanceState.getLongArray(getStateKey()); if (checkedIds != null && checkedIds.length > 0) { mTempIdsToCheckOnRestore = new HashSet<Long>(); for (long id : checkedIds) { mTempIdsToCheckOnRestore.add(id); } } } } public void tryRestoreInstanceState(Bundle savedInstanceState) { readInstanceState(savedInstanceState); tryRestoreInstanceState(); } public void finish() { if (mActionMode != null) { mActionMode.finish(); } } public void tryRestoreInstanceState() { if (mTempIdsToCheckOnRestore == null || mListView.getAdapter() == null) { return; } boolean idsFound = false; Adapter adapter = mListView.getAdapter(); for (int pos = adapter.getCount() - 1; pos >= 0; pos--) { if (mTempIdsToCheckOnRestore.contains(adapter.getItemId(pos))) { idsFound = true; if (mItemsToCheck == null) { mItemsToCheck = new HashSet<Pair<Integer, Long>>(); } mItemsToCheck.add( new Pair<Integer, Long>(pos, adapter.getItemId(pos))); } } if (idsFound) { // We found some IDs that were checked. Let's now restore the multi-selection // state. mTempIdsToCheckOnRestore = null; // clear out this temp field mActionMode = mActivity.startSupportActionMode(Controller.this); } } public boolean saveInstanceState(Bundle outBundle) { // TODO: support non-stable IDs by persisting positions instead of IDs if (mActionMode != null && mListView.getAdapter().hasStableIds()) { long[] checkedIds = mListView.getCheckedItemIds(); outBundle.putLongArray(getStateKey(), checkedIds); return true; } return false; } private String getStateKey() { return MultiSelectionUtil.class.getSimpleName() + "_" + mListView.getId(); } @Override public boolean onCreateActionMode(ActionMode actionMode, Menu menu) { if (mListener.onCreateActionMode(actionMode, menu)) { mActionMode = actionMode; mOldItemClickListener = mListView.getOnItemClickListener(); mListView.setOnItemClickListener(Controller.this); mListView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE); mHandler.removeCallbacks(mSetChoiceModeNoneRunnable); if (mItemsToCheck != null) { for (Pair<Integer, Long> posAndId : mItemsToCheck) { mListView.setItemChecked(posAndId.first, true); mListener.onItemCheckedStateChanged(mActionMode, posAndId.first, posAndId.second, true); } } return true; } return false; } @Override public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) { if (mListener.onPrepareActionMode(actionMode, menu)) { mActionMode = actionMode; return true; } return false; } @Override public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) { return mListener.onActionItemClicked(actionMode, menuItem); } @Override public void onDestroyActionMode(ActionMode actionMode) { mListener.onDestroyActionMode(actionMode); SparseBooleanArray checkedPositions = mListView.getCheckedItemPositions(); if (checkedPositions != null) { for (int i = 0; i < checkedPositions.size(); i++) { mListView.setItemChecked(checkedPositions.keyAt(i), false); } } mListView.setOnItemClickListener(mOldItemClickListener); mActionMode = null; mHandler.post(mSetChoiceModeNoneRunnable); } private Runnable mSetChoiceModeNoneRunnable = new Runnable() { @Override public void run() { mListView.setChoiceMode(AbsListView.CHOICE_MODE_NONE); } }; @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { boolean checked = mListView.isItemChecked(position); mListener.onItemCheckedStateChanged(mActionMode, position, id, checked); int numChecked = 0; SparseBooleanArray checkedItemPositions = mListView.getCheckedItemPositions(); if (checkedItemPositions != null) { for (int i = 0; i < checkedItemPositions.size(); i++) { numChecked += checkedItemPositions.valueAt(i) ? 1 : 0; } } if (numChecked <= 0) { mActionMode.finish(); } } @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) { if (mActionMode != null) { return false; } mItemsToCheck = new HashSet<Pair<Integer, Long>>(); mItemsToCheck.add(new Pair<Integer, Long>(position, id)); mActionMode = mActivity.startSupportActionMode(Controller.this); return true; } } /** * @see android.widget.AbsListView.MultiChoiceModeListener */ public static interface MultiChoiceModeListener extends ActionMode.Callback { /** * @see android.widget.AbsListView.MultiChoiceModeListener#onItemCheckedStateChanged( * android.view.ActionMode, int, long, boolean) */ public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked); } }
Java