📅  最后修改于: 2023-12-03 15:08:32.923000             🧑  作者: Mango
开发一个计步应用程序可以帮助用户记录他们的步数并跟踪他们的健康状况。在这篇文章中,我们将展示如何在 Android Studio 中构建一个简单的计步应用程序。
首先,打开 Android Studio 并创建一个新项目。选择“Empty Activity”作为项目模板。
接下来,我们需要添加计步器功能。在此之前,确保你已经向你的项目添加了以下依赖项:
dependencies {
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.google.android.gms:play-services-fitness:11.8.0'
}
创建一个名为 StepCounter
的 Java 类并添加以下代码:
public class StepCounter {
private static final String TAG = "StepCounter";
private static final long INTERVAL = 3000;
private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
private final WeakReference<Activity> mActivityRef;
private OnStepChangeListener mListener;
private SensorManager mSensorManager;
private Sensor mSensor;
private boolean mRegistered = false;
private GoogleApiClient mClient;
public StepCounter(Activity activity) {
mActivityRef = new WeakReference<>(activity);
}
public void setOnStepChangeListener(OnStepChangeListener listener) {
mListener = listener;
}
public void start() {
if (mRegistered) return;
mSensorManager = (SensorManager) mActivityRef.get().getSystemService(Activity.SENSOR_SERVICE);
if (mSensorManager == null) return;
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if (mSensor == null) {
Toast.makeText(mActivityRef.get(), "Sensor not available", Toast.LENGTH_LONG).show();
return;
}
mRegistered = mSensorManager.registerListener(mSensorEventListener, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
public void stop() {
if (!mRegistered) return;
mSensorManager.unregisterListener(mSensorEventListener);
mRegistered = false;
}
private GoogleApiClient getClient() {
if (mClient == null) {
mClient = new GoogleApiClient.Builder(mActivityRef.get())
.addApi(Fitness.SENSORS_API)
.addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.d(TAG, "onConnected: " + bundle);
}
@Override
public void onConnectionSuspended(int i) {
Log.d(TAG, "onConnectionSuspended: " + i);
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed: " + connectionResult);
}
})
.build();
}
return mClient;
}
private boolean checkPermissions() {
int permissionState = ActivityCompat.checkSelfPermission(mActivityRef.get(),
Manifest.permission.ACTIVITY_RECOGNITION);
return permissionState == PackageManager.PERMISSION_GRANTED;
}
public void requestPermissions() {
boolean shouldProvideRationale = ActivityCompat.shouldShowRequestPermissionRationale(mActivityRef.get(),
Manifest.permission.ACTIVITY_RECOGNITION);
if (shouldProvideRationale) {
Snackbar.make(mActivityRef.get().findViewById(android.R.id.content),
"Activity recognition permission is needed for this feature",
Snackbar.LENGTH_INDEFINITE)
.setAction("Ok", new View.OnClickListener() {
@Override
public void onClick(View view) {
ActivityCompat.requestPermissions(mActivityRef.get(),
new String[]{Manifest.permission.ACTIVITY_RECOGNITION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
}).show();
} else {
ActivityCompat.requestPermissions(mActivityRef.get(),
new String[]{Manifest.permission.ACTIVITY_RECOGNITION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
start();
}
}
}
private final SensorEventListener mSensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
if (mListener != null) mListener.onStepChange(event.values[0]);
if (checkPermissions()) {
Fitness.getHistoryClient(mActivityRef.get(), getClient())
.insertData(new DataSet.Builder(DataType.TYPE_STEP_COUNT_DELTA)
.setTimeInterval(System.currentTimeMillis(), System.currentTimeMillis(), TimeUnit.MILLISECONDS)
.setField(Field.FIELD_STEPS, event.values[0])
.build());
} else {
requestPermissions();
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
public interface OnStepChangeListener {
void onStepChange(float steps);
}
}
这段代码创建了一个名为 StepCounter 的 Java 类,它使用 Android 的传感器 API 和 Google Fit API 以实时方式接收步数。
在你的 MainActivity 类中添加以下代码以初始化 StepCounter 对象并启动它:
public class MainActivity extends AppCompatActivity {
private TextView mTextView;
private StepCounter mStepCounter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.text_view);
mStepCounter = new StepCounter(this);
mStepCounter.setOnStepChangeListener(new StepCounter.OnStepChangeListener() {
@Override
public void onStepChange(float steps) {
if (mTextView != null) {
mTextView.setText(String.valueOf(steps));
}
}
});
mStepCounter.start();
}
@Override
protected void onStop() {
super.onStop();
mStepCounter.stop();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mStepCounter.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == StepCounter.REQUEST_PERMISSIONS_REQUEST_CODE) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mStepCounter.start();
}
}
}
}
该代码:
mStepCounter = new StepCounter(this)
创建 StepCounter 对象并将 MainActivity 对象作为参数传递给它。mStepCounter.setOnStepChangeListener()
允许我们监听每次步数变化并更新 UI。mStepCounter.start()
开始使用 Step Counter 传感器接收事件。mStepCounter.stop()
在 onStop 方法中停止使用传感器接收事件。onRequestPermissionsResult()
方法处理请求权限操作的结果。onActivityResult()
方法在用户接受访问 Google Fit API 的请求时被调用。现在运行你的应用程序并开始步行。你应该看到步数逐渐增加并显示在 UI 上。
我们学会了如何使用 Android 的传感器 API 和 Google Fit API 构建一个计步应用程序。这可以帮助用户追踪他们的健康状况并获得关于他们步行活动的实时数据。希望这篇文章对你有所帮助!