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

android 类似微信的摇一摇功能实现思路及代码

程序员文章站 2023-12-01 08:38:34
复制代码 代码如下: package com.eboy.testyaoyiyao; import java.text.simpledateformat; import ja...
复制代码 代码如下:

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();
}
}