package com.firefly.myflashlight;

 import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast; public class MainActivity extends Activity {
ImageView image;
Boolean flag = false;
Camera camera;
Parameters params;
// 传感器管理
SensorManager sm;
Vibrator v ;//震动
sensorListener s;//传感器监听 @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(1);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.image);
Shake();
} private void Shake() {
// 初始化数据
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
v = (Vibrator) getSystemService(VIBRATOR_SERVICE);
s = new sensorListener();
sm.registerListener(s, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
} //开/关按钮的点击事件
public void init(View view) {
Replese();
}
public void Replese(){
if (flag == false) {
camera = Camera.open();//打开相机
params = camera.getParameters();////获取预览的各种分辨率
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
Toast.makeText(getApplicationContext(), "别摇了,我又不是微信,摇不出妹子的!!", 0).show();
Toast.makeText(getApplicationContext(), "电筒已开启", 0).show();
image.setImageResource(R.drawable.off);//当相机打开之后按钮要变成关闭的颜色
flag = true;
} else {
Toast.makeText(getApplicationContext(), "您还可以直接摇一摇打开手电筒哦!", 0).show();
image.setImageResource(R.drawable.on);
camera.stopPreview();
camera.release();
flag = false;
}
} @Override
protected void onPause() {
// TODO Auto-generated method stub
sm.unregisterListener(s);
super.onPause();
} @Override
protected void onStop() {
// TODO Auto-generated method stub
sm.unregisterListener(s);
super.onStop();
} //震动(传感器)监听事件
private class sensorListener implements SensorEventListener { @Override
public void onSensorChanged(SensorEvent event) {
int sensorType = event.sensor.getType();
float[] values = event.values;
if (sensorType == Sensor.TYPE_ACCELEROMETER) {
//如果摇晃的力度在15
if (Math.abs(values[0]) > 15 || Math.abs(values[1]) > 15
|| Math.abs(values[2]) > 15) {
Replese();//就把电筒打开
v.vibrate(200);
}
}
} @Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub } }
}
04-18 03:35