我使用加速度计做了一个计步器。在开始时,它在模拟器中完美加载但在设备崩溃时。首先,它一直工作到if。
这是代码:
import android.app.Activity;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;
import java.util.List;
public class RunActivity extends Activity implements SensorEventListener, View.OnClickListener {
TextView x,y,z,e,l;
double x1,y1,z1, g;
private int total= 0;
private Chronometer chronometer;
Button start, stop;
private Sensor mAccelerometer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_run);
x = (TextView)findViewById(R.id.xID);
y = (TextView)findViewById(R.id.yID);
z = (TextView)findViewById(R.id.zID);
e = (TextView)findViewById(R.id.count);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
chronometer = (Chronometer) findViewById(R.id.Rchronometer);
start = (Button) findViewById(R.id.starttime);
stop = (Button) findViewById(R.id.endtime);
}
protected void onResume()
{
super.onResume();
SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);
List<Sensor> sensors = sm.getSensorList(Sensor.TYPE_ACCELEROMETER);
if (sensors.size() > 0)
{
sm.registerListener(this, sensors.get(0), SensorManager.SENSOR_DELAY_GAME);
}
}
protected void onPause()
{
SensorManager mSensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
mSensorManager.unregisterListener(this, mAccelerometer);
super.onPause();
}
protected void onStop()
{
SensorManager mSensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
mSensorManager.unregisterListener(this, mAccelerometer);
super.onStop();
}
@Override
public void onSensorChanged(SensorEvent event) {
this.x.setText("X = "+event.values[SensorManager.DATA_X]);
this.y.setText("Y = "+event.values[SensorManager.DATA_Y]);
this.z.setText("Z = "+event.values[SensorManager.DATA_Z]);
x1=event.values[SensorManager.DATA_X];
y1=event.values[SensorManager.DATA_Y];
z1=event.values[SensorManager.DATA_Z];
g = (Math.sqrt((x1*x1)+(y1*y1)+(z1*z1)))/9.8;
if (g<1){
total++;
e.setText(total);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.starttime:
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
break;
case R.id.endtime:
chronometer.stop();
break;
` }
}
}
另外,这是logcat。我不确定发生了什么
E/SensorManager: Exception dispatching input event.
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.paola.trition, PID: 6667
android.content.res.Resources$NotFoundException: String resource ID #0x1