File Name : FlashLightActivity.java
package com.richview.flashlight;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
public class FlashLightActivity extends Activity {
private Button onebutton = null;
private Camera camera = null;
private Parameters parameters = null;
public static boolean kaiguan = true; //false :poweron, true:poweroff
private int back = 0;//record the back key pressed times
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD,WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_HOMEKEY_DISPATCHED,WindowManager.LayoutParams.FLAG_HOMEKEY_DISPATCHED);
setContentView(R.layout.main);
onebutton = (Button)findViewById(R.id.onebutton);
onebutton.setOnClickListener(new Mybutton());
}
class Mybutton implements OnClickListener{
@Override
public void onClick(View v) {
if(kaiguan){
onebutton.setBackgroundResource(R.drawable.bgon);
camera = Camera.open();
parameters = camera.getParameters();
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
kaiguan = false;
}else{
onebutton.setBackgroundResource(R.drawable.bg);
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
kaiguan = true;
camera.release();
}
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK){
back++;
switch (back) {
case 1:
Toast.makeText(FlashLightActivity.this,R.string.press_again_to_exit,Toast.LENGTH_LONG).show();
break;
case 2:
back = 0;//初始化back值
Myback();
break;
}
return true;//设置成false让back失效 ,true表示 不失效
}else if(keyCode == KeyEvent.KEYCODE_HOME)
{
Myback();
return super.onKeyDown(keyCode, event);
}
else{
return super.onKeyDown(keyCode, event);
}
}
public void Myback(){ //关闭程序
if(kaiguan){//开关关闭时
FlashLightActivity.this.finish();
android.os.Process.killProcess(android.os.Process.myPid());//关闭进程
}else if(!kaiguan){//开关打开时
camera.release();
FlashLightActivity.this.finish();
android.os.Process.killProcess(android.os.Process.myPid());//关闭进程
kaiguan = true;//避免,打开开关后退出程序,再次进入不打开开关直接退出时,程序错误
}
}
}
阅读(468) | 评论(0) | 转发(0) |