本项目就一个activity,直接上代码。
package com.example.qgns;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
public class MainActivity extends Activity {
private long exitTime;
private StartView startView;
private MyView myView;
private EndView endView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); //去标题,必须写在<span style="font-family: Arial, Helvetica, sans-serif;">setContentView方法之前</span>
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, //全屏显示
WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.getWindow().setFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, //保持屏幕常亮
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
startView = new StartView(this);
setContentView(startView);
}
public void toMyView() { //进入游戏主界面的方法
myView = new MyView(this);
setContentView(myView);
startView = null;
}
public void toEndView(int sumScore) { //游戏结束界面的方法
endView = new EndView(this, sumScore);
setContentView(endView);
myView = null;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) { //监听返回键,实现按两次返回键退出游戏
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getAction() == KeyEvent.ACTION_DOWN) {
if (System.currentTimeMillis() - exitTime > 2000) {
Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
System.exit(0);
}
}
AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE); //媒体音量的控制,控制声音的大小
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_RAISE,
AudioManager.FX_FOCUS_NAVIGATION_UP);
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_LOWER,
AudioManager.FX_FOCUS_NAVIGATION_UP);
}
return true;
}
}