欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

android 检测摇一摇

程序员文章站 2024-02-10 22:02:52
...
Manifest添加  
<uses-permission android:name="android.permission.VIBRATE"/>


package com.example.a; import android.app.Activity; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Vibrator; import android.view.Menu; import android.widget.Toast; public class MainActivity extends Activity { private SensorManager smg; private Vibrator vbt; private static final int SENSOR_SHAKE=10; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); smg=(SensorManager)this.getSystemService(SENSOR_SERVICE); vbt=(Vibrator)this.getSystemService(VIBRATOR_SERVICE); } @Override public void onResume(){ super.onResume(); if(smg!=null){ smg.registerListener(sensorEventListener, smg.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),smg.SENSOR_DELAY_NORMAL); } } @Override public void onPause(){ super.onPause(); if(smg!=null){ smg.unregisterListener(sensorEventListener); } } private SensorEventListener sensorEventListener =new SensorEventListener(){ public void onSensorChanged(SensorEvent event){ float[] values =event.values; float x = values[0]; float y = values[1]; float z = values[2]; System.out.println("x:"+x+" y:"+y+" z:"+z); int medumValue =15; if(Math.abs(x)>medumValue||Math.abs(y)>medumValue||Math.abs(z)>medumValue){ vbt.vibrate(200); Message msg=new Message(); msg.what=SENSOR_SHAKE; } } public void onAccuracyChanged(Sensor sensor,int assuray){ } }; Handler handler=new Handler(){ public void handleMessage(Message msg){ super.handleMessage(msg); switch (msg.what){ case SENSOR_SHAKE: Toast.makeText(getApplicationContext(), "I know you are shake your phone now", 2000).show(); } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }