热门关键字:
jquery > jquery教程 > Android开发 > Java版Android开发实现摇一摇的功能解剖

Java版Android开发实现摇一摇的功能解剖

3433
作者:管理员
发布时间:2013/8/10 15:11:43
评论数:0
转载请自觉注明原文:http://www.jq-school.com/Show.aspx?id=309

最近安卓(Android)软件系列中的摇一摇功能很火,但很多网友不知道是怎么实现的,学习前端jquery的网友可能看不懂,只适合搞Java开发的网友们,但不要紧哦,可以收藏,接下来一步步的把它解剖出来给大家看。


源码打包下载


主要有两个类:

1、监听类ShakeListener.java


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 {
	// 速度阈值,当摇晃速度达到这值后产生作用
	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("thelog", "===========log===================");
		// 达到速度阀值,发出提示
		if (speed >= SPEED_SHRESHOLD) {
			onShakeListener.onShake();
		}
	}

	public void onAccuracyChanged(Sensor sensor, int accuracy) {

	}

	// 摇晃监听接口
	public interface OnShakeListener {
		public void onShake();
	}

}


2、激活类ShackActivity.java


import java.util.ArrayList;
import java.util.HashMap;
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.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.zk.Promotion.ShakeListener.OnShakeListener;
import com.zk.Promotion.domain.PromotionMessage;
import com.zk.Promotion.util.AppHelper;

/**
 * http://blog.csdn.net/fuzhengchao/article/details/6736908
 * http://www.cnblogs.com/wisekingokok/archive/2011/09/05/2167755.html
 */
public class ShackActivity 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();
		setValues();
		setListeners();
	}

	private void initRes() {
	}

	private void findViews() {
		mListview = (ListView) findViewById(R.id.listview);
		mShakeListener = new ShakeListener(this);
	}

	private void setValues() {
		mListview.setAdapter(new MessageAdapter(this, getAdapteValues()));
	}

	private void setListeners() {
		mListview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					Bundle bundle = new Bundle();
					bundle.putString("id", String.valueOf(position));
					Intent intent = new Intent();
					intent.putExtras(bundle);
					intent.setClass(ShackActivity.this,
							PromotionDetailActivity.class);
					startActivity(intent);
					ShackActivity.this.finish();
				} catch (Exception e) {
					Log.v("exception", e.getMessage());
				}
			}
		});

		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(ShackActivity.this,
							PromotionActivity.class).putExtras(b);
					startActivity(intent);
					ShackActivity.this.finish();
				} catch (Exception e) {
					Toast.makeText(ShackActivity.this, e.getMessage(),
							Toast.LENGTH_SHORT).show();
				}
			}
		});
	}

	/**
	 * 获得adapter数据
	 * 
	 * @return
	 */
	private ArrayList<HashMap<String, Object>> getAdapteValues() {
		// 获取默认商家促销信息
		ArrayList<PromotionMessage> list = AppHelper.getDefaultMessage();
		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.d("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.d("Location", "Latitude: " + currentLocation.getLatitude());
				Log.d("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.d("Location", "onLocationChanged");
			Log.d("Location",
					"onLocationChanged Latitude" + location.getLatitude());
			Log.d("Location",
					"onLocationChanged location" + location.getLongitude());
		}

		@Override
		public void onProviderDisabled(String provider) {
			Log.d("Location", "onProviderDisabled");
		}

		@Override
		public void onProviderEnabled(String provider) {
			Log.d("Location", "onProviderEnabled");
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			Log.d("Location", "onStatusChanged");
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mShakeListener != null) {
			mShakeListener.stop();
		}
	}
}






如果您觉得本文的内容对您的学习有所帮助:支付鼓励



关键字:Java开发 安卓开发 Android开发 摇一摇
友荐云推荐