我有一個Android開發的加速計應用程序,我想用「開始」和「停止」按鈕啓動和停止活動。我在執行代碼本身的按鈕時遇到困難,我正在尋求一些幫助。這是我的主要Java文件。使用按鈕啓動和停止進程
package com.*****.accelo;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Button;
import android.view.View.OnClickListener;
public abstract class AcceloActivity extends Activity implements SensorEventListener,
OnClickListener {
TextView textViewX, textViewY, textViewZ, textViewError;
String blank;
Button buttonStop, buttonStart;
StringBuilder builderx = new StringBuilder();
StringBuilder buildery = new StringBuilder();
StringBuilder builderz = new StringBuilder();
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textViewError = (TextView) findViewById(R.id.textViewError);
textViewX = (TextView) findViewById(R.id.textViewX);
textViewY = (TextView) findViewById(R.id.textViewY);
textViewZ = (TextView) findViewById(R.id.textViewZ);
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
//Button listener
buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
SensorManager manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor accelerometer = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
if(!manager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_UI)){
}
textViewX.setText(blank);
textViewY.setText(blank);
textViewZ.setText(blank);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
builderx.setLength(0);
buildery.setLength(0);
builderz.setLength(0);
builderx.append("X: " + event.values[0]);
buildery.append("Y: "+ event.values[1]);
builderz.append("Z: " + event.values[2]);
textViewX.setText(builderx.toString());
textViewY.setText(buildery.toString());
textViewZ.setText(builderz.toString());
textViewError.setText(blank);
}
在此先感謝!
更新後的代碼,但仍不清楚如何實際使用按鈕來啓動傳感器偵聽器並結束它。 – Slicekick
@Slicekick - 編輯提供關於開始使用您的項目的一些想法。 – Carth
@Slicekick - 我不相信你會啓動和停止傳感器監聽器。您從傳感器註冊並取消註冊您的聽衆。傳感器本身繼續。你的應用程序只是停止關注它。 http://developer.android.com/reference/android/hardware/SensorManager.html – Carth