Learn more with dummies

Enter your email to join our mailing list for FREE content right to your inbox. Easy!

Common Android Game Development Tasks

By Derek James

Part of Android Game Programming For Dummies Cheat Sheet

In the process of developing Android games, you’ll perform a few common tasks over and over. If these tasks aren’t already automatic for you, keep them handy.

Fix an app in portrait or landscape (in manifest file):

<activity
   android:label="@string/app_name"
   android:name=".MyActivity" 
   android:screenOrientation="portrait"                            
   android:configChanges="orientation|keyboardHidden"              
/>

Disable screen timeout:

public class MyActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyView myView = new MyView(this);
        myView.setKeepScreenOn(true);                                   
        setContentView(myView);
    }
}

Load an image:

private Bitmap myImage;
public myView(Context context) {
       super(context);
       myImage=
BitmapFactory.decodeResource(getResources(),R.drawable.my_image);
}

Draw an image:

@Override
protected void onDraw(Canvas canvas) {
   canvas.drawBitmap(myImage, 0, 0, null);
}

Load a sound:

Soundpool sounds = new SoundPool(5,AudioManager.STREAM_MUSIC, 0);
int mySound = sounds.load(myContext, R.raw.my_sound, 1);

Play a sound:

AudioManager am = (AudioManager)
    myContext.getSystemService(Context.AUDIO_SERVICE);
float volume = (float) 
    audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
sounds.play(mySound, volume, volume, 1, 0, 1);