Android 計步器開發

github  地址:https://github.com/zhouguangfu09/StepCounter

1.    程序圖標


2.    點擊圖標,進入如下界面:


這個界面會有緩衝效果,然後進入程序的主界面.

3.程序主界面:

點擊開始按鈕,並甩動胳膊,計步器開始計數,也可以暫停計數,如下圖所示:


5.每走150步,系統獎勵一個星星,最高10顆星星。同時軟件會粗略的計算行程、熱量、速度等參數。如上圖所示。


6.點擊手機菜單鍵,點擊“設置”選項,進入如下界面:


軟件記步數的精準度跟用戶的補償以及體重有關,也跟用戶設置的傳感器的靈敏度有關係,在設置頁面可以對相應的參數進行調節。一旦調節結束,可以重新開始。

7.在手機的主界面按返回鍵,退出程序。

 

源碼部分解析

源碼主要包含UI控制邏輯代碼以及胳膊甩動檢測步數代碼,下面重點說一下 步數檢測代碼,主要集中在StepDector.Java文件中:

[java] view plain copy
  1. public void onSensorChanged(SensorEventevent) {  
  2.        // Log.i(Constant.STEP_SERVER, "StepDetector");  
  3.        Sensor sensor = event.sensor;  
  4.        // Log.i(Constant.STEP_DETECTOR,"onSensorChanged");  
  5.        synchronized (this) {  
  6.               if (sensor.getType() ==Sensor.TYPE_ORIENTATION) {  
  7.               } else {  
  8.                      int j =(sensor.getType() == Sensor.TYPE_ACCELEROMETER) ? 1 : 0;  
  9.                      if (j == 1) {  
  10.                             float vSum =0;  
  11.                             for (int i =0; i < 3; i++) {  
  12.                                    finalfloat v = mYOffset + event.values[i] * mScale[j];  
  13.                                    vSum+= v;  
  14.                             }  
  15.                             int k = 0;  
  16.                             float v =vSum / 3;  
  17.   
  18.                             floatdirection = (v > mLastValues[k] ? 1: (v < mLastValues[k] ? -1 : 0));  
  19.                             if (direction== -mLastDirections[k]) {  
  20.                                    //Direction changed  
  21.                                    intextType = (direction > 0 ? 0 : 1); // minumum or  
  22.                                    //maximum?  
  23.                                    mLastExtremes[extType][k]= mLastValues[k];  
  24.                                    floatdiff = Math.abs(mLastExtremes[extType][k]- mLastExtremes[1 - extType][k]);  
  25.   
  26.                                    if(diff > SENSITIVITY) {  
  27.                                           booleanisAlmostAsLargeAsPrevious = diff > (mLastDiff[k] * 2 / 3);  
  28.                                           booleanisPreviousLargeEnough = mLastDiff[k] > (diff / 3);  
  29.                                           booleanisNotContra = (mLastMatch != 1 - extType);  
  30.   
  31.                                           if(isAlmostAsLargeAsPrevious && isPreviousLargeEnough &&isNotContra) {  
  32.                                                  end= System.currentTimeMillis();  
  33.                                                  if(end - start > 500) {// 此時判斷爲走了一步  
  34.                                                         Log.i("StepDetector","CURRENT_SETP:"  
  35.                                                                       +CURRENT_SETP);  
  36.                                                         CURRENT_SETP++;  
  37.                                                         mLastMatch= extType;  
  38.                                                         start= end;  
  39.                                                  }  
  40.                                           }else {  
  41.                                                  mLastMatch= -1;  
  42.                                           }  
  43.                                    }  
  44.                                    mLastDiff[k]= diff;  
  45.                             }  
  46.                             mLastDirections[k]= direction;  
  47.                             mLastValues[k]= v;  
  48.                      }  
  49.               }  
  50.        }  
 

這個函數是一個傳感器的回調函數,在其中可以根據從系統地加速度傳感器獲取的數值進行胳膊甩動動作的判斷。主要從以下幾個方面判斷:

(1)人如果走起來了,一般會連續多走幾步。因此,如果沒有連續4-5個波動,那麼就極大可能是干擾。 

(2)人走動的波動,比坐車產生的波動要大,因此可以看波峯波谷的高度,只檢測高於某個高度的波峯波谷。

(3)人的反射神經決定了人快速動的極限,怎麼都不可能兩步之間小於0.2秒,因此間隔小於0.2秒的波峯波谷直接跳過

通過重力加速計感應,重力變化的方向,大小。與正常走路或跑步時的重力變化比對,達到一定相似度時認爲是在走路或跑步。實現起來很簡單,只要手機有重力感應器就能實現。

 

1.    啓動界面

程序啓動界面帶有緩衝效果,其中界面緩衝效果的配置文件在res/anim/目錄下。如果計步器已經開始工作,則跳過程序啓動界面,直接進入主界面。

[java] view plain copy
  1.        if (StepCounterService.FLAG || StepDetector.CURRENT_SETP > 0) {// 程序已經啓動,直接跳轉到運行界面  
  2.            Intent intent = new Intent(SplashActivity.this,StepCounterActivity.class); //創建一個新的Intent,指定當前應用程序上下文      
  3. //和要啓動的StepActivity類  
  4.            startActivity(intent);                                         //傳遞這個intent給startActivity  
  5.            this.finish();  
  6.        } else {  
  7.            this.requestWindowFeature(Window.FEATURE_NO_TITLE);  
  8.            this.setContentView(R.layout.splash);  
  9.    
  10.            animation = AnimationUtils.loadAnimation(SplashActivity.this,  
  11.                   R.anim.animation_splash);  
  12.            this.findViewById(R.id.iv_index).setAnimation(animation);  
  13.            animation.setAnimationListener(new AnimationListener() {// 動畫監聽,通過AnimationListener可以監聽Animation的運行過程  
  14.                      @Override  
  15.                      public void onAnimationStart(Animation animation){  
  16.                          // TODOAuto-generated method stub  
  17.                      }  
  18.                      @Override  
  19.                      public void onAnimationRepeat(Animationanimation) {  
  20.                          // TODOAuto-generated method stub  
  21.                      }  
  22.                      @Override  
  23.                      public void onAnimationEnd(Animation animation) {// 動畫結束時跳轉至運行界面  
  24.                          // TODOAuto-generated method stub  
  25.                          Intent intent = new Intent(SplashActivity.this,  
  26.                                 StepCounterActivity.class);  
  27.                          SplashActivity.this.startActivity(intent);  
  28.                          SplashActivity.this.finish();  
  29.                      }  
  30.                   });  
  31.        }  
  32. }  


2.  程序主界面

(1)界面元素的初始化(比如步數,星期,日期,運行時間,行程,卡路里,速度,開始按鈕和停止按鈕)。

[java] view plain copy
  1. //定義文本框控件  
  2.    private TextView tv_show_step;// 步數  
  3.    private TextView tv_week_day;// 星期  
  4.    private TextView tv_date;// 日期  
  5.   
  6.    private TextView tv_timer;// 運行時間  
  7.   
  8.    private TextView tv_distance;// 行程  
  9.    private TextView tv_calories;// 卡路里  
  10.    private TextView tv_velocity;// 速度  
  11.   
  12.    private Button btn_start;// 開始按鈕  
  13.    private Button btn_stop;// 停止按鈕  
  14.   
  15.    // 十顆星標  
  16.    private ImageView iv_star_1;                 
  17.    private ImageView iv_star_2;  
  18.    private ImageView iv_star_3;  
  19.    private ImageView iv_star_4;  
  20.    private ImageView iv_star_5;  
  21.    private ImageView iv_star_6;  
  22.    private ImageView iv_star_7;  
  23.    private ImageView iv_star_8;  
  24.    private ImageView iv_star_9;  
  25.    private ImageView iv_star_10;  
  26.   
  27.    private long timer = 0;// 運動時間  
  28.    private static long startTimer = 0;// 開始時間  
  29.    private static long tempTime = 0;  
  30.   
  31.    private Double distance = 0.0;// 路程:米  
  32.    private Double calories = 0.0;// 熱量:卡路里  
  33.    private Double velocity = 0.0;// 速度:米每秒  
  34.   
  35.    private int step_length = 0;  //步長  
  36.    private int weight = 0;       //體重  
  37.    private int total_step = 0;   //走的總步數  
  38.     
  39.    DatagramSocket socket;  
  40.    InetAddress serverAddress;  
  41.    DatagramPacket  send_package1;  
  42.    private Thread thread;  //定義線程對象  


2)利用消息機制對主界面的UI元素進行更新。定義了一個handler,當檢測的步數變化時,更新主界面顯示的信息。主要代碼如下:

[java] view plain copy
  1. Handler handler = new Handler() {// Handler對象用於更新當前步數,定時發送消息,調用方法查詢數據用於顯示??????????  
  2.                                        //主要接受子線程發送的數據, 並用此數據配合主線程更新UI  
  3.                                    //Handler運行在主線程中(UI線程中), 它與子線程可以通過Message對象來傳遞數據,  
  4.    //Handler就承擔着接受子線程傳過來的(子線程用sendMessage()方法傳遞Message對象,(裏面包含數據)  
  5.    //把這些消息放入主線程隊列中,配合主線程進行更新UI。  
  6.   
  7.    @Override                  //這個方法是從父類/接口繼承過來的,需要重寫一次  
  8.    public void handleMessage(Message msg) {  
  9.        // TODO Auto-generated method stub  
  10.        super.handleMessage(msg);        // 此處可以更新UI  
  11.   
  12.        countDistance();     //調用距離方法,看一下走了多遠  
  13.   
  14.        if (timer != 0 && distance != 0.0) {  
  15.   
  16.           // 體重、距離  
  17.            // 跑步熱量(kcal)=體重(kg)×距離(公里)×1.036  
  18.           calories = weight * distance * 0.001;  
  19.           //速度velocity  
  20.           velocity = distance * 1000 / timer;  
  21.        } else {  
  22.           calories =0.0;  
  23.           velocity =0.0;  
  24.        }  
  25.   
  26.        countStep();          //調用步數方法  
  27.   
  28.        tv_show_step.setText(total_step + "");// 顯示當前步數  
  29.   
  30.        tv_distance.setText(formatDouble(distance));// 顯示路程  
  31.        tv_calories.setText(formatDouble(calories));// 顯示卡路里  
  32.        tv_velocity.setText(formatDouble(velocity));// 顯示速度  
  33.   
  34.        tv_timer.setText(getFormatTime(timer));// 顯示當前運行時間  
  35.   
  36.        changeStep();// 設置當前步數和星標  
  37.   
  38.    }  

(3)初始化主界面的信息。

[java] view plain copy
  1. /** 
  2.  * 初始化界面 
  3.  */  
  4. private void init() {  
  5.   
  6.    step_length =SettingsActivity.sharedPreferences.getInt(  
  7.           SettingsActivity.STEP_LENGTH_VALUE, 70);  
  8.    weight =SettingsActivity.sharedPreferences.getInt(  
  9.           SettingsActivity.WEIGHT_VALUE, 50);  
  10.   
  11.    countDistance();  
  12.    countStep();  
  13.    if ((timer += tempTime) != 0 && distance != 0.0) {  //tempTime記錄運動的總時間,timer記錄每次運動時間  
  14.   
  15.        // 體重、距離  
  16.        // 跑步熱量(kcal)=體重(kg)×距離(公里)×1.036,換算一下  
  17.        calories = weight * distance * 0.001;  
  18.   
  19.        velocity = distance * 1000 / timer;  
  20.    } else {  
  21.        calories = 0.0;  
  22.        velocity = 0.0;  
  23.    }  
  24.   
  25.    tv_timer.setText(getFormatTime(timer + tempTime));  
  26.   
  27.    tv_distance.setText(formatDouble(distance));  
  28.    tv_calories.setText(formatDouble(calories));  
  29.    tv_velocity.setText(formatDouble(velocity));  
  30.   
  31.    tv_show_step.setText(total_step + "");  
  32.   
  33.    btn_start.setEnabled(!StepCounterService.FLAG);  
  34.    btn_stop.setEnabled(StepCounterService.FLAG);  
  35.   
  36.    if(StepCounterService.FLAG) {  
  37.        btn_stop.setText(getString(R.string.pause));  
  38.    } else if (StepDetector.CURRENT_SETP > 0) {  
  39.        btn_stop.setEnabled(true);  
  40.        btn_stop.setText(getString(R.string.cancel));  
  41.    }  
  42.   
  43.    setDate();  
  44. }  

(4)計算距離和步長。

[java] view plain copy
  1. /** 
  2.  * 計算行走的距離                                                                        
  3.  */  
  4. private void countDistance() {  
  5.    if (StepDetector.CURRENT_SETP % 2 == 0) {  
  6.        distance = (StepDetector.CURRENT_SETP / 2) * 3 * step_length * 0.01;  
  7.    } else {  
  8.        distance = ((StepDetector.CURRENT_SETP / 2) * 3 + 1) * step_length * 0.01;  
  9.    }  
  10. }  
  11.   
  12. /** 
  13.  * 實際的步數 
  14.  */  
  15. private void countStep() {  
  16.    if (StepDetector.CURRENT_SETP % 2 == 0) {  
  17.        total_step = StepDetector.CURRENT_SETP;  
  18.    } else {  
  19.        total_step = StepDetector.CURRENT_SETP +1;  
  20.    }  
  21.     
  22.    total_step = StepDetector.CURRENT_SETP;  
  23. }  


3.    後臺檢測傳感器信息的服務(service).

[java] view plain copy
  1. //service負責後臺的需要長期運行的任務  
  2.  // 計步器服務  
  3.  // 運行在後臺的服務程序,完成了界面部分的開發後  
  4.  // 就可以開發後臺的服務類StepService  
  5.  // 註冊或註銷傳感器監聽器,在手機屏幕狀態欄顯示通知,與StepActivity進行通信,走過的步數記到哪裏了???  
  6. public class StepCounterService extends Service {  
  7.    
  8.     public static Boolean FLAG = false;// 服務運行標誌  
  9.    
  10.     private SensorManagermSensorManager;// 傳感器服務  
  11.     private StepDetector detector;// 傳感器監聽對象  
  12.    
  13.     private PowerManager mPowerManager;// 電源管理服務  
  14.     private WakeLock mWakeLock;// 屏幕燈  
  15.    
  16.     @Override  
  17.     public IBinder onBind(Intent intent) {  
  18.        // TODOAuto-generated method stub  
  19.        return null;  
  20.     }  
  21.    
  22.     @Override  
  23.     public void onCreate() {  
  24.        // TODOAuto-generated method stub  
  25.        super.onCreate();  
  26.    
  27.        FLAG = true;// 標記爲服務正在運行  
  28.    
  29.        // 創建監聽器類,實例化監聽對象  
  30.        detector = new StepDetector(this);  
  31.    
  32.        // 獲取傳感器的服務,初始化傳感器  
  33.        mSensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);  
  34.        // 註冊傳感器,註冊監聽器  
  35.        mSensorManager.registerListener(detector,  
  36.               mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),  
  37.               SensorManager.SENSOR_DELAY_FASTEST);  
  38.    
  39.        // 電源管理服務  
  40.        mPowerManager = (PowerManager) this  
  41.               .getSystemService(Context.POWER_SERVICE);  
  42.        mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK  
  43.               |PowerManager.ACQUIRE_CAUSES_WAKEUP, "S");  
  44.        mWakeLock.acquire();  
  45.     }  
  46.    
  47.     @Override  
  48.     public void onDestroy() {  
  49.        // TODOAuto-generated method stub  
  50.        super.onDestroy();  
  51.        FLAG = false;// 服務停止  
  52.        if (detector != null) {  
  53.            mSensorManager.unregisterListener(detector);  
  54.        }  
  55.    
  56.        if (mWakeLock != null) {  
  57.            mWakeLock.release();  
  58.        }  
  59.     }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章