Android game development 3: Brief Introduction to related APIs

Source: Internet
Author: User
Tags gety

 

1. Activity Lifecycle

 

During Game Development, we only need to reload the onCreate (), onResume (), and onPause () methods, because onResume () and onPause () methods will be called no matter how it is. After onPause (), the system may kill the activity because the memory is too low, and onStop () and onDestroy () will not be executed, while onStart () will be in onStop () it will be called after execution. After onpause (), the wake-up activity will only call onResume ().

 

1) In onCreate (), we set up our window and UI component that we

Render to and receive input from.

2) In onResume (), we (re) start our main loop thread (discussed in the last

Chapter ).

3) In onPause (), we simply pause our main loop thread, and if

Activity. isFinishing () returns true, we also save any state we want

To persist to disk.

 

 

 

 

 

Ii. event handling

 

1) multi-touch

 

 

Public boolean onTouch (View v, MotionEvent event ){

Int action = event. getAction () & MotionEvent. ACTION_MASK; // get the type of Click event

Int pointerIndex = (event. getAction () & MotionEvent. ACTION_POINTER_ID_MASK)> MotionEvent. ACTION_POINTER_ID_SHIFT; // retrieve the index of the Click event

Int pointerId = event. getPointerId (pointerIndex); // obtain the Click event ID

Switch (action ){

Case MotionEvent. ACTION_DOWN:

Case MotionEvent. ACTION_POINTER_DOWN:

Touched [pointerId] = true;

X [pointerId] = (int) event. getX (pointerIndex );

Y [pointerId] = (int) event. getY (pointerIndex );

Break;

 

Case MotionEvent. ACTION_UP:

Case MotionEvent. ACTION_POINTER_UP:

Case MotionEvent. ACTION_CANCEL:

Touched [pointerId] = false;

X [pointerId] = (int) event. getX (pointerIndex );

Y [pointerId] = (int) event. getY (pointerIndex );

Break;

 

More new events than single touch:

 

1. MotionEvent. ACTION_POINTER_DOWN: This event happens for any additional finger that

Touches the screen after the first finger touches. The first finger will still produce

MotionEvent. ACTION_DOWN event.

2. MotionEvent. ACTION_POINTER_UP: This is analogous the previous action. This gets

Fired when a finger is lifted up from the screen and more than one finger is touching

The screen. The last finger on the screen to go up will produce

MotionEvent. ACTION_UP event. This finger doesn't necessarily have to be the first

Finger that touched the screen.

 

 

 

Use Single-touch to process multi-touch

 

For this to happen, the merged events have to have

Same type. In reality this will only happen for the MotionEvent. ACTION_MOVE event, so we

Only have to deal with this fact when processing said event type. To check how many

Events are contained in a single MotionEvent, we use

MotionEvent. getPointerCount () method, which tells us for how many fingers

MotionEvent contains coordinates for. We then can fetch the pointer identifier and

Coordinates for the pointer indices 0 to MotionEvent. getPointerCount ()-1 via

MotionEvent. getX (), MotionEvent. getY (), and MotionEvent. getPointerId () methods.

 

 

 

Case MotionEvent. ACTION_MOVE:

Int pointerCount = event. getPointerCount (); // gets the number of click events

For (int I = 0; I <pointerCount; I ++ ){

PointerIndex = I;

PointerId = event. getPointerId (pointerIndex );

X [pointerId] = (int) event. getX (pointerIndex );

Y [pointerId] = (int

 

 

 

 

3. Button events

 

 

 

Public boolean onKey (View view, int keyCode, KeyEvent event)

 

Keycode: indicates the unique identifier of the key on the mobile phone. For example, KeyCode. KEYCODE_A indicates that the key A is pressed.

 

KeyEvent: similar to MotionEvent, there are two important methods.

 

KeyEvent. getAction (): This method returns KeyEvent. ACTION_DOWN,

 

KeyEvent. ACTION_UP, and KeyEvent. ACTION_MULTIPLE.

 

KeyEvent. getUnicodeChar (): Process click events as characters

 

Note: To obtain the key event, view must obtain the focus, View. setFocusableInTouchMode (true); View. requestFocus ();

 

 

 

Iv. Acceleration Sensor

 

1. Use the Context interface to obtain the sensor Service

 

SensorManager manager = (SensorManager) context. getSystemService (Context. SENSOR_SERVICE );

 

2. Check whether the sensor contains an acceleration sensor (optional, because all android devices are equipped with an acceleration sensor)

 

Boolean hasAccel = manager. getSensorList (Sensor. TYPE_ACCELEROMETER). size ()> 0;

 

3. register the listener

 

Sensor sensor = manager. getSensorList (Sensor. TYPE_ACCELEROMETER). get (0 );

Boolean success = manager. registerListener (listener, sensor,

SensorManager. SENSOR_DELAY_GAME );

 

 

 

 

 

V. Sound Effect Processing

 

 

 

Context. setVolumeControlStream (AudioManager. STREAM_MUSIC); // set the volume key to adjust the volume.

 

 

 

Play real-time sound effects with soundpool

 

1. SoundPool soundPool = new SoundPool (20, AudioManager. STREAM_MUSIC, 0 );

 

2. Load the audio file to the memory

 

AssetManager assetManager = getAssets ();

 

AssetFileDescriptor descriptor = assetManager. openFd ("explosion.ogg"); // in Game Development, audio images and other resources are usually put into assets to facilitate hierarchical folder management.

Int explosionId = soundPool. load (descriptor, 1 );

 

3. Playback

 

SoundPool. play (explosionId, 1.0f, 1.0f, 0, 0, 1 );

 

4. Remember to release the memory when you do not need it.

 

SoundPool. unload (explosionId );

 

SoundPool. release (); // release all resources used by SoundPool

 

 

 

 

 

Play background music with MediaPlayer

 

1. MediaPlayer mediaPlayer = new MediaPlayer ();

 

2. AssetManager assetManager = getAssets ();

AssetFileDescriptor descriptor = assetManager. openFd ("music.ogg ");

 

 

 

MediaPlayer. setDataSource (descriptor. getFileDescriptor (), descriptor. getStartOffset (),

Descriptor. getLength ());

 

 

3. Open the music file and check whether it can be played.

 

MediaPlayer. prepare ();

 

4. Playback

 

MediaPlayer. start ();

 

MediaPlayer. pause ();

 

MediaPlayer. stop (); // For replay, you must first play mediaPlayer. prepare () and then play mediaPlayer. start ()

 

MediaPlayer. setLooping (true );

5. release resources

 

MediaPlayer. release ();

 

 

 

MediaPlayer occupies a considerable amount of resources, so it is only used to play background music.

 

 

 

 

 

Vi. 2D image processing

 

 

 

1. Attach Images

 

AssetManager assetManager = context. getAssets ();

 

InputStream inputStream = assetManager. open ("bob.png ");

Bitmap bitmap = BitmapFactory. decodeStream (inputStream );

 

InputStream. close ();

 

2. Draw

 

Canvas. drawBitmap (Bitmap bitmap, float topLeftX, float topLeftY, painting );

 

Or Canvas. drawBitmap (Bitmap bitmap, Rect src, Rect dst, Paint paint );

 

2. Release image resources

 

Bitmap. recycle ();

 

Unless absolutely necessary, refrain from drawing bitmaps scaled. If

You know their scaled size, prescale them offline or during loading

Time.

Always make sure you call the Bitmap. recycle () method if you no

Longer need a Bitmap. Otherwise you'll get some memory leaks or run

Low on memory.

 

 

SurfaceView

 

The advantage of SurfaceView over View is that it can process game logic in a separate thread to avoid blocking the UI thread.

 

1. Obtain SurfaceHolder from the constructor

 

SurfaceHolder holder = surfaceView. getHolder ();

 

The SurfaceHolder is a wrapper around the Surface, and does some bookkeeping

Us. It provides us with two methods:

Canvas SurfaceHolder. lockCanvas (); // lock the Surface to be drawn and return an available Canvas

SurfaceHolder. unlockAndPost (Canvas canvas); // unlock the Surface and display the drawing on the Canvas on the screen.

2. Draw

 

Canvas canvas = holder. lockCanvas ();

Canvas. draw # ff0000;

Holder. unlockCanvasAndPost (canvas );

 

Author: shangdahao

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.