android-类似微信和米聊中摇一摇找好友的功能的实现
jopen
12年前
要实现该功能,主要借助于重力感应
package yyy.testsensor; public class TestSensorActivity extends Activity implements SensorEventListener { private SensorManager manager; private Vibrator vibrator; private TextView xSensor,ySensor,zSensor; private float X = 0.0f; private float Y = 0.0f; private float Z = 0.0f; private Button button1,button2; private TextView textView; private Animation animation ,animation2 ; private FrameLayout layout; private ImageView imageView; private String[] strs; private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); switch (msg.what) { case 0: textView.setText((String)msg.obj); imageView.startAnimation(animation); textView.startAnimation(animation); break; } } }; private int i = 0; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); manager = (SensorManager) getSystemService(SENSOR_SERVICE); //首先得到传感器管理器对象 vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); //注册监听器 manager.registerListener(this, manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), manager.SENSOR_DELAY_NORMAL); //第一个参数是Listener,第二个参数是所得传感器类型,第三个参数值获取传感器信息的频率 } @Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); manager.unregisterListener(this);//解绑定Listener } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO Auto-generated method stub } @Override public void onSensorChanged(SensorEvent event) { // TODO Auto-generated method stub //传感器信息改变时执行该方法 float[] values = event.values; float x = values[0]; //x轴方向的重力加速度,向右为正 float y = values[1]; // y轴方向的重力加速度,向前为正 float z = values[2]; // z轴方向的重力加速度,向上为正 if(x>40 || x<-40 || y>40 || y<-40 || z>40 || z<-40){ //一般在这三个方向的重力加速度达到40就达到了摇晃手机的状态。当然这个值可以根据需要,自己定义。 vibrator.vibrate(200); int random = getRandom(); Message msg = new Message(); msg.what = 0; msg.obj = strs[random]; handler.sendMessage(msg); } } }转自:http://blog.csdn.net/centralperk/article/details/7947741