摇一摇Listener
1、摇一摇Listener
package com.tangzq;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
/**
* 一个检测手机摇晃的监听器
*/
public class ShakeListener implements SensorEventListener {
String TAG="ShakeListener";
// 速度阈值,当摇晃速度达到这值后产生作用
private static final int SPEED_SHRESHOLD = 3000;
// 两次检测的时间间隔
private static final int UPTATE_INTERVAL_TIME = 70;
// 传感器管理器
private SensorManager sensorManager;
// 传感器
private Sensor sensor;
// 重力感应监听器
private OnShakeListener onShakeListener;
// 上下文
private Context mContext;
// 手机上一个位置时重力感应坐标
private float lastX;
private float lastY;
private float lastZ;
// 上次检测时间
private long lastUpdateTime;
// 构造器
public ShakeListener(Context c) {
// 获得监听对象
mContext = c;
start();
}
// 开始
public void start() {
// 获得传感器管理器
sensorManager = (SensorManager) mContext
.getSystemService(Context.SENSOR_SERVICE);
if (sensorManager != null) {
// 获得重力传感器
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
// 注册
if (sensor != null) {
sensorManager.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_GAME);
}
}
// 停止检测
public void stop() {
sensorManager.unregisterListener(this);
}
// 设置重力感应监听器
public void setOnShakeListener(OnShakeListener listener) {
onShakeListener = listener;
}
// 重力感应器感应获得变化数据
public void onSensorChanged(SensorEvent event) {
// 现在检测时间
long currentUpdateTime = System.currentTimeMillis();
// 两次检测的时间间隔
long timeInterval = currentUpdateTime - lastUpdateTime;
// 判断是否达到了检测时间间隔
if (timeInterval < UPTATE_INTERVAL_TIME)
return;
// 现在的时间变成last时间
lastUpdateTime = currentUpdateTime;
// 获得x,y,z坐标
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
// 获得x,y,z的变化值
float deltaX = x - lastX;
float deltaY = y - lastY;
float deltaZ = z - lastZ;
// 将现在的坐标变成last坐标
lastX = x;
lastY = y;
lastZ = z;
double speed = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ
* deltaZ)
/ timeInterval * 10000;
Log.v(TAG, "===========log===================");
// 达到速度阀值,发出提示
if (speed >= SPEED_SHRESHOLD) {
onShakeListener.onShake();
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
// 摇晃监听接口
public interface OnShakeListener {
public void onShake();
}
}
2、摇一摇主界面Activity
package com.tangzq;
import android.app.Activity;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.ListView;
import android.widget.Toast;
import com.tangzq.ShakeListener.OnShakeListener;
public class YaoYiYaoActivity extends Activity {
ListView mListview;
ShakeListener mShakeListener = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);// 不显示程序的标题栏
setContentView(R.layout.shack);
initRes();
findViews();
setListeners();
}
private void initRes() {
}
private void findViews() {
mShakeListener = new ShakeListener(this);
}
private void setListeners() {
mShakeListener.setOnShakeListener(new OnShakeListener() {
public void onShake() {
try {
Location location = getLocation();
Bundle b = new Bundle();
b.putDouble("latitude", location.getLatitude());
b.putDouble("longitude", location.getLongitude());
Intent intent = new Intent(YaoYiYaoActivity.this,AfterShakedActivity.class).putExtras(b);
startActivity(intent);
YaoYiYaoActivity.this.finish();
} catch (Exception e) {
Toast.makeText(YaoYiYaoActivity.this, e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
}
///**
// * 获得adapter数据
// *
// * @return
// */
//private ArrayList<HashMap<String, Object>> getAdapteValues() {
//// 获取默认商家促销信息
//ArrayList<PromotionMessage> list = new ArrayList<PromotionMessage>();
//if (list != null && list.size() != 0) {
//ArrayList<HashMap<String, Object>> values = new ArrayList<HashMap<String, Object>>();
//for (int i = 0; i < list.size(); i++) {
//HashMap<String, Object> item = new HashMap<String, Object>();
//PromotionMessage m = list.get(i);
//item.put("item_paymessage", m.getTitle());
//values.add(item);
//}
//return values;
//}
//return null;
//}
/**
* 获取经度维度
*/
public Location getLocation() {
// 获取到LocationManager对象
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// 创建一个Criteria对象
Criteria criteria = new Criteria();
// 设置粗略精确度
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
// 设置是否需要返回海拔信息
criteria.setAltitudeRequired(false);
// 设置是否需要返回方位信息
criteria.setBearingRequired(false);
// 设置是否允许付费服务
criteria.setCostAllowed(true);
// 设置电量消耗等级
criteria.setPowerRequirement(Criteria.POWER_HIGH);
// 设置是否需要返回速度信息
criteria.setSpeedRequired(false);
// 根据设置的Criteria对象,获取最符合此标准的provider对象
String currentProvider = locationManager
.getBestProvider(criteria, true);
Log.e("Location", "currentProvider: " + currentProvider);
if (currentProvider == null) {
currentProvider = LocationManager.NETWORK_PROVIDER;
}
Location currentLocation = locationManager
.getLastKnownLocation(currentProvider);
if (currentLocation == null) {
locationManager.requestLocationUpdates(currentProvider, 0, 0,
locationListener);
}
// 直到获得最后一次位置信息为止,如果未获得最后一次位置信息,则显示默认经纬度
// 每隔3秒获取一次位置信息
while (true) {
currentLocation = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (currentLocation != null) {
Log.e("Location", "Latitude: " + currentLocation.getLatitude());
Log.e("Location",
"Longitude: " + currentLocation.getLongitude());
return currentLocation;
}
try {
Thread.sleep(3);
} catch (InterruptedException e) {
Log.e("Location", e.getMessage());
}
}
}
/**
* 创建位置监听器
*/
private LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.e("Location", "onLocationChanged");
Log.e("Location",
"onLocationChanged Latitude" + location.getLatitude());
Log.e("Location",
"onLocationChanged location" + location.getLongitude());
}
@Override
public void onProviderDisabled(String provider) {
Log.e("Location", "onProviderDisabled");
}
@Override
public void onProviderEnabled(String provider) {
Log.e("Location", "onProviderEnabled");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e("Location", "onStatusChanged");
}
};
@Override
protected void onDestroy() {
super.onDestroy();
if (mShakeListener != null) {
mShakeListener.stop();
}
}
}
3、摇一摇主界面shake.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="center_vertical|center_horizontal"
android:text="摇一摇"
android:textColor="#3A7EBD"
android:textSize="36dp" />
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/shake" />
</LinearLayout>
4、摇一摇跳转Activity
package com.tangzq;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.TextView;
public class AfterShakedActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv=new TextView(this);
tv.setText("哈哈,你摇成功了,xiangxi信息");
tv.setBackgroundDrawable(getResources().getDrawable(R.drawable.smile));
tv.setTextSize(32);
tv.setTextColor(Color.MAGENTA);
//tv.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL);
tv.setGravity(Gravity.CENTER_HORIZONTAL);
//tv.setGravity();
setContentView(tv);
}
}
参照:
http://blog.csdn.net/fuzhengchao/article/details/6736908
http://www.cnblogs.com/wisekingokok/archive/2011/09/05/2167755.html
邮箱:steven9801@163.com
QQ: 48039387