Android摇一摇软件功能解析(java版)

主要有两个类:

1、监听类ShakeListener.java


001 import android.content.Context;
002 import android.hardware.Sensor;
003 import android.hardware.SensorEvent;
004 import android.hardware.SensorEventListener;
005 import android.hardware.SensorManager;
006 import android.util.Log;
007  
008 /**
009  * 一个检测手机摇晃的监听器
010  */
011 public class ShakeListener implements SensorEventListener {
012     // 速度阈值,当摇晃速度达到这值后产生作用
013     private static final int SPEED_SHRESHOLD = 3000;
014     // 两次检测的时间间隔
015     private static final int UPTATE_INTERVAL_TIME = 70;
016     // 传感器管理器
017     private SensorManager sensorManager;
018     // 传感器
019     private Sensor sensor;
020     // 重力感应监听器
021     private OnShakeListener onShakeListener;
022     // 上下文
023     private Context mContext;
024     // 手机上一个位置时重力感应坐标
025     private float lastX;
026     private float lastY;
027     private float lastZ;
028     // 上次检测时间
029     private long lastUpdateTime;
030  
031     // 构造器
032     public ShakeListener(Context c) {
033         // 获得监听对象
034         mContext = c;
035         start();
036     }
037  
038     // 开始
039     public void start() {
040         // 获得传感器管理器
041         sensorManager = (SensorManager) mContext
042                 .getSystemService(Context.SENSOR_SERVICE);
043         if (sensorManager != null) {
044             // 获得重力传感器
045             sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
046         }
047         // 注册
048         if (sensor != null) {
049             sensorManager.registerListener(this, sensor,
050                     SensorManager.SENSOR_DELAY_GAME);
051         }
052  
053     }
054  
055     // 停止检测
056     public void stop() {
057         sensorManager.unregisterListener(this);
058     }
059  
060     // 设置重力感应监听器
061     public void setOnShakeListener(OnShakeListener listener) {
062         onShakeListener = listener;
063     }
064  
065     // 重力感应器感应获得变化数据
066     public void onSensorChanged(SensorEvent event) {
067         // 现在检测时间
068         long currentUpdateTime = System.currentTimeMillis();
069         // 两次检测的时间间隔
070         long timeInterval = currentUpdateTime - lastUpdateTime;
071         // 判断是否达到了检测时间间隔
072         if (timeInterval < UPTATE_INTERVAL_TIME)
073             return;
074         // 现在的时间变成last时间
075         lastUpdateTime = currentUpdateTime;
076  
077         // 获得x,y,z坐标
078         float x = event.values[0];
079         float y = event.values[1];
080         float z = event.values[2];
081  
082         // 获得x,y,z的变化值
083         float deltaX = x - lastX;
084         float deltaY = y - lastY;
085         float deltaZ = z - lastZ;
086  
087         // 将现在的坐标变成last坐标
088         lastX = x;
089         lastY = y;
090         lastZ = z;
091  
092         double speed = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ
093                 * deltaZ)
094                 / timeInterval * 10000;
095         Log.v("thelog""===========log===================");
096         // 达到速度阀值,发出提示
097         if (speed >= SPEED_SHRESHOLD) {
098             onShakeListener.onShake();
099         }
100     }
101  
102     public void onAccuracyChanged(Sensor sensor, int accuracy) {
103  
104     }
105  
106     // 摇晃监听接口
107     public interface OnShakeListener {
108         public void onShake();
109     }
110  
111 }


2、激活类ShackActivity.java


001 import java.util.ArrayList;
002 import java.util.HashMap;
003 import android.app.Activity;
004 import android.content.Intent;
005 import android.location.Criteria;
006 import android.location.Location;
007 import android.location.LocationListener;
008 import android.location.LocationManager;
009 import android.os.Bundle;
010 import android.util.Log;
011 import android.view.View;
012 import android.view.Window;
013 import android.widget.AdapterView;
014 import android.widget.AdapterView.OnItemClickListener;
015 import android.widget.ListView;
016 import android.widget.Toast;
017 import com.zk.Promotion.ShakeListener.OnShakeListener;
018 import com.zk.Promotion.domain.PromotionMessage;
019 import com.zk.Promotion.util.AppHelper;
020  
021 /**
024  */
025 public class ShackActivity extends Activity {
026     ListView mListview;
027     ShakeListener mShakeListener = null;
028  
029     @Override
030     protected void onCreate(Bundle savedInstanceState) {
031         super.onCreate(savedInstanceState);
032         requestWindowFeature(Window.FEATURE_NO_TITLE);// 不显示程序的标题栏
033         setContentView(R.layout.shack);
034         initRes();
035         findViews();
036         setValues();
037         setListeners();
038     }
039  
040     private void initRes() {
041     }
042  
043     private void findViews() {
044         mListview = (ListView) findViewById(R.id.listview);
045         mShakeListener = new ShakeListener(this);
046     }
047  
048     private void setValues() {
049         mListview.setAdapter(new MessageAdapter(this, getAdapteValues()));
050     }
051  
052     private void setListeners() {
053         mListview.setOnItemClickListener(new OnItemClickListener() {
054             @Override
055             public void onItemClick(AdapterView<?> parent, View view,
056                     int position, long id) {
057                 try {
058                     Bundle bundle = new Bundle();
059                     bundle.putString("id", String.valueOf(position));
060                     Intent intent = new Intent();
061                     intent.putExtras(bundle);
062                     intent.setClass(ShackActivity.this,
063                             PromotionDetailActivity.class);
064                     startActivity(intent);
065                     ShackActivity.this.finish();
066                 catch (Exception e) {
067                     Log.v("exception", e.getMessage());
068                 }
069             }
070         });
071  
072         mShakeListener.setOnShakeListener(new OnShakeListener() {
073             public void onShake() {
074                 try {
075                     Location location = getLocation();
076                     Bundle b = new Bundle();
077                     b.putDouble("latitude", location.getLatitude());
078                     b.putDouble("longitude", location.getLongitude());
079                     Intent intent = new Intent(ShackActivity.this,
080                             PromotionActivity.class).putExtras(b);
081                     startActivity(intent);
082                     ShackActivity.this.finish();
083                 catch (Exception e) {
084                     Toast.makeText(ShackActivity.this, e.getMessage(),
085                             Toast.LENGTH_SHORT).show();
086                 }
087             }
088         });
089     }
090  
091     /**
092      * 获得adapter数据
093      *
094      * @return
095      */
096     private ArrayList<HashMap<String, Object>> getAdapteValues() {
097         // 获取默认商家促销信息
098         ArrayList<PromotionMessage> list = AppHelper.getDefaultMessage();
099         if (list != null && list.size() != 0) {
100             ArrayList<HashMap<String, Object>> values = newArrayList<HashMap<String, Object>>();
101             for (int i = 0; i < list.size(); i++) {
102                 HashMap<String, Object> item = new HashMap<String, Object>();
103                 PromotionMessage m = list.get(i);
104                 item.put("item_paymessage", m.getTitle());
105                 values.add(item);
106             }
107             return values;
108         }
109         return null;
110     }
111  
112     /**
113      * 获取经度维度
114      */
115     public Location getLocation() {
116         // 获取到LocationManager对象
117         LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
118         // 创建一个Criteria对象
119         Criteria criteria = new Criteria();
120         // 设置粗略精确度
121         criteria.setAccuracy(Criteria.ACCURACY_COARSE);
122         // 设置是否需要返回海拔信息
123         criteria.setAltitudeRequired(false);
124         // 设置是否需要返回方位信息
125         criteria.setBearingRequired(false);
126         // 设置是否允许付费服务
127         criteria.setCostAllowed(true);
128         // 设置电量消耗等级
129         criteria.setPowerRequirement(Criteria.POWER_HIGH);
130         // 设置是否需要返回速度信息
131         criteria.setSpeedRequired(false);
132         // 根据设置的Criteria对象,获取最符合此标准的provider对象
133         String currentProvider = locationManager
134                 .getBestProvider(criteria, true);
135         Log.d("Location""currentProvider: " + currentProvider);
136         if (currentProvider == null) {
137             currentProvider = LocationManager.NETWORK_PROVIDER;
138         }
139         Location currentLocation = locationManager
140                 .getLastKnownLocation(currentProvider);
141         if (currentLocation == null) {
142             locationManager.requestLocationUpdates(currentProvider, 0, 0,
143                     locationListener);
144         }
145         // 直到获得最后一次位置信息为止,如果未获得最后一次位置信息,则显示默认经纬度
146         // 每隔3秒获取一次位置信息
147         while (true) {
148             currentLocation = locationManager
149                     .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
150             if (currentLocation != null) {
151                 Log.d("Location""Latitude: " + currentLocation.getLatitude());
152                 Log.d("Location",
153                         "Longitude: " + currentLocation.getLongitude());
154                 return currentLocation;
155             }
156             try {
157                 Thread.sleep(3);
158             catch (InterruptedException e) {
159                 Log.e("Location", e.getMessage());
160             }
161         }
162     }
163  
164     /**
165      * 创建位置监听器
166      */
167     private LocationListener locationListener = new LocationListener() {
168         @Override
169         public void onLocationChanged(Location location) {
170             Log.d("Location""onLocationChanged");
171             Log.d("Location",
172                     "onLocationChanged Latitude" + location.getLatitude());
173             Log.d("Location",
174                     "onLocationChanged location" + location.getLongitude());
175         }
176  
177         @Override
178         public void onProviderDisabled(String provider) {
179             Log.d("Location""onProviderDisabled");
180         }
181  
182         @Override
183         public void onProviderEnabled(String provider) {
184             Log.d("Location""onProviderEnabled");
185         }
186  
187         @Override
188         public void onStatusChanged(String provider, int status, Bundle extras) {
189             Log.d("Location""onStatusChanged");
190         }
191     };
192  
193     @Override
194     protected void onDestroy() {
195         super.onDestroy();
196         if (mShakeListener != null) {
197             mShakeListener.stop();
198         }
199     }
200 }

>>>>更多精彩.请访问 it学习网  www.5axxw.com
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值