我必须做一个通过摇动手机返回随机数的应用程序。我用按钮做了它,它工作正常。问题在于加速度计。即使我没有错误,它也不起作用。
import java.util.Random;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RandomButtonActivity extends Activity implements SensorEventListener
{
Button tasto1;
TextView testo;
TextView message;
EditText limiteMin;
EditText limiteMax;
Random generator = new Random();
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
testo = (TextView) findViewById(R.id.textView1);
limiteMin = (EditText) findViewById(R.id.editText2);
limiteMax = (EditText) findViewById(R.id.EditText01);
}
public void onSensorChanged(SensorEvent event)
{
Sensor sensor = event.sensor;
if (sensor.getType()==Sensor.TYPE_ACCELEROMETER)
{
int j = Integer.parseInt(limiteMin.getText().toString());
int i = Integer.parseInt(limiteMax.getText().toString())-j;
int x = 0;
if(i==0 && j==0)
{
x = generator.nextInt();
while(x<0)
{
x = generator.nextInt();
}
}
else
{
if(j>=i)
{
i = 0;
j = 0;
}
else
{
x = generator.nextInt(i+1)+j;
testo.setText(""+x);
}
}
testo.setText(""+x);
}
else
{
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
}
环顾互联网,这段代码应该可以正常工作。我没有对XML文件做任何事情。
编辑:
我补充说:
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true"
到Android:清单但没有任何改变。
答案 0 :(得分:1)
您似乎永远不会将您的类添加为事件侦听器。 这段代码适合我:
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//This is what you are missing:
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_UI);
}
public void onSensorChanged(SensorEvent event)
{
Sensor sensor = event.sensor;
if (sensor.getType() == Sensor.TYPE_ACCELEROMETER)
{
/// Do something
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
像这样覆盖onResume / onStop / onPause也是一个好主意
@Override protected void onResume()
{
super.onResume();
sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
@Override protected void onStop()
{
sm.unregisterListener(this);
super.onStop();
}
正如ernell所提到的那样,请记住在清单中拥有所需的权限。