2015-12-06 84 views
0

我嘗試在android中製作一個基本的計步器應用程序。但是,當我得到下面的錯誤不可在Android步計數器(計數器傳感器不起作用)

計數器傳感器

請幫助我。

package com.starboardland.pedometer; 

import android.app.Activity; 
import android.content.Context; 
import android.hardware.*; 
import android.os.Bundle; 
import android.widget.TextView; 
import android.widget.Toast; 

public class CounterActivity extends Activity implements SensorEventListener { 

    private SensorManager sensorManager; 
    private TextView count; 
    boolean activityRunning; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     count = (TextView) findViewById(R.id.count); 

     sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); 
    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     activityRunning = true; 
     Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER); 
     if (countSensor != null) { 
      sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI); 
     } else { 
      Toast.makeText(this, "Count sensor not available!", Toast.LENGTH_LONG).show(); 
     } 

    } 

    @Override 
    protected void onPause() { 
     super.onPause(); 
     activityRunning = false; 
     // if you unregister the last listener, the hardware will stop detecting step events 
//  sensorManager.unregisterListener(this); 
    } 

    @Override 
    public void onSensorChanged(SensorEvent event) { 
     if (activityRunning) { 
      count.setText(String.valueOf(event.values[0])); 
     } 

    } 

    @Override 
    public void onAccuracyChanged(Sensor sensor, int accuracy) { 
    } 
} 

回答

1

Android 4.4 API Documentation指出,傳感器是硬件相關的。

兩個步驟傳感器是依賴於硬件的(Nexus 5採用以支持它們的第一裝置),所以你應該檢查與hasSystemFeature()的可用性,使用FEATURE_SENSOR_STEP_DETECTOR和FEATURE_SENSOR_STEP_COUNTER常數。

您應該檢查設備是否具有功能優先。

PackageManager pm = getPackageManager(); 
if (pm.hasSystemFeature(PackageManager.FEATURE_SENSOR_STEP_COUNTER)) { 
    // the awesome stuff here 
}