android 类似微信的摇一摇功能实现思路及代码
来源:爱站网时间:2021-11-16编辑:网友分享
微信的摇一摇功能的出现,让彼此之间的距离有近了一步,爱站技术小编今天带来的本文也想实现以下微信的摇一摇功能,感兴趣的朋友可以了解下啊,希望对你有所帮助
package com.eboy.testyaoyiyao;
import java.text.SimpleDateFormat;
import java.util.Date;
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.Vibrator;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener {
//Sensor管理器
private SensorManager mSensorManager = null;
//震动
private Vibrator mVibrator = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mVibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent arg0) {
// TODO Auto-generated method stub
int sensorType = arg0.sensor.getType();
float[] values = arg0.values;
if (sensorType == Sensor.TYPE_ACCELEROMETER){
if (Math.abs(values[0]) > 14 || Math.abs(values[1]) > 14 || Math.abs(values[2]) > 14){
mVibrator.vibrate(100);
TextView tv1 = (TextView)findViewById(R.id.textView1);
SimpleDateFormat f=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
tv1.setText(f.format(new Date()) + "手机摇动了...");
}
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
mSensorManager.unregisterListener(this);
super.onStop();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
mSensorManager.unregisterListener(this);
super.onPause();
}
}
以上内容就是爱站技术频道小编为大家分享的android 类似微信的摇一摇功能实现思路及代码,看完以上分享之后,大家应该都更了解android了吧。