android手电筒(摇一摇也可开启手电筒)
1 package com.firefly.myflashlight; 2 3 import android.app.Activity; 4 import android.hardware.Camera; 5 import android.hardware.Camera.Parameters; 6 import android.hardware.Sensor; 7 import android.hardware.SensorEvent; 8 import android.hardware.SensorEventListener; 9 import android.hardware.SensorManager; 10 import android.os.Bundle; 11 import android.os.Vibrator; 12 import android.view.View; 13 import android.widget.ImageView; 14 import android.widget.Toast; 15 16 public class MainActivity extends Activity { 17 ImageView image; 18 Boolean flag = false; 19 Camera camera; 20 Parameters params; 21 // 传感器管理 22 SensorManager sm; 23 Vibrator v ;//震动 24 sensorListener s;//传感器监听 25 26 @Override 27 protected void onCreate(Bundle savedInstanceState) { 28 super.onCreate(savedInstanceState); 29 requestWindowFeature(1); 30 setContentView(R.layout.activity_main); 31 image = (ImageView) findViewById(R.id.image); 32 Shake(); 33 } 34 35 private void Shake() { 36 // 初始化数据 37 sm = (SensorManager) getSystemService(SENSOR_SERVICE); 38 v = (Vibrator) getSystemService(VIBRATOR_SERVICE); 39 s = new sensorListener(); 40 sm.registerListener(s, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), 41 SensorManager.SENSOR_DELAY_NORMAL); 42 } 43 44 //开/关按钮的点击事件 45 public void init(View view) { 46 Replese(); 47 } 48 public void Replese(){ 49 if (flag == false) { 50 camera = Camera.open();//打开相机 51 params = camera.getParameters();////获取预览的各种分辨率 52 params.setFlashMode(Parameters.FLASH_MODE_TORCH); 53 camera.setParameters(params); 54 camera.startPreview(); 55 Toast.makeText(getApplicationContext(), "别摇了,我又不是微信,摇不出妹子的!!", 0).show(); 56 Toast.makeText(getApplicationContext(), "电筒已开启", 0).show(); 57 image.setImageResource(R.drawable.off);//当相机打开之后按钮要变成关闭的颜色 58 flag = true; 59 } else { 60 Toast.makeText(getApplicationContext(), "您还可以直接摇一摇打开手电筒哦!", 0).show(); 61 image.setImageResource(R.drawable.on); 62 camera.stopPreview(); 63 camera.release(); 64 flag = false; 65 } 66 } 67 68 @Override 69 protected void onPause() { 70 // TODO Auto-generated method stub 71 sm.unregisterListener(s); 72 super.onPause(); 73 } 74 75 @Override 76 protected void onStop() { 77 // TODO Auto-generated method stub 78 sm.unregisterListener(s); 79 super.onStop(); 80 } 81 82 //震动(传感器)监听事件 83 private class sensorListener implements SensorEventListener { 84 85 @Override 86 public void onSensorChanged(SensorEvent event) { 87 int sensorType = event.sensor.getType(); 88 float[] values = event.values; 89 if (sensorType == Sensor.TYPE_ACCELEROMETER) { 90 //如果摇晃的力度在15 91 if (Math.abs(values[0]) > 15 || Math.abs(values[1]) > 15 92 || Math.abs(values[2]) > 15) { 93 Replese();//就把电筒打开 94 v.vibrate(200); 95 } 96 } 97 } 98 99 @Override 100 public void onAccuracyChanged(Sensor sensor, int accuracy) { 101 // TODO Auto-generated method stub 102 103 } 104 105 } 106 }
种一棵树最早的时间是十年前,其次是现在。