public class MainActivity extends Activity { private Button bu1; private Camera camera; private Parameters parameters; private static boolean kaiguan = true; public int back = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LinearLayout container = (LinearLayout)findViewById(R.id.Acc); new AdView(this,container).DisplayAd(); bu1=(Button)findViewById(R.id.bu1); bu1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if(kaiguan){ bu1.setBackgroundResource(R.drawable.on); camera = Camera.open(); parameters = camera.getParameters(); parameters.setFlashMode(Parameters.FLASH_MODE_TORCH); camera.setParameters(parameters); kaiguan = false; }else{ bu1.setBackgroundResource(R.drawable.off); parameters.setFlashMode(Parameters.FLASH_MODE_OFF); camera.setParameters(parameters); kaiguan = true; camera.release(); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. menu.add(0,1,1,"关于"); menu.add(1,2,2,"退出"); return super.onCreateOptionsMenu(menu); } public boolean onOptionsItemSelected(MenuItem item){ switch (item.getItemId()) { case 1: AlertDialog.Builder b = new Builder(MainActivity.this); b.setTitle("关于"); b.setMessage("卡卡手电做出最简洁的应用 作者:某人"); b.setCancelable(true); b.setNegativeButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface d, int which) { d.dismiss(); } }); b.show(); break; case 2: Myback(); break; } return super.onOptionsItemSelected(item); } public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK){ back++; switch (back) { case 1: Toast.makeText(MainActivity.this, "再按一次退出卡卡手电", Toast.LENGTH_LONG).show(); break; case 2: back = 0;//初始化back值 Myback(); break; } return true;//设置成false让back失效 ,true表示 不失效 } else{ return super.onKeyDown(keyCode, event); } } public void Myback(){ if(kaiguan){//开关关闭时 MainActivity.this.finish(); android.os.Process.killProcess(android.os.Process.myPid());//关闭进程 }else if(!kaiguan){//开关打开时 camera.release(); MainActivity.this.finish(); android.os.Process.killProcess(android.os.Process.myPid());//关闭进程 kaiguan = true;//避免,打开开关后退出程序,再次进入不打开开关直接退出时,程序错误 } }}