1

所以我有下面的代码,我无法开始工作。我试图让一个类(AccelerometerReader)读取我手机加速度计的值,然后我在另一个类(MyGame)中调用这些值,我用它在屏幕上打印这些值。代码中的一切似乎都很好,我没有得到任何值,除了我打印的值都只是说 0.0 并且不改变。我知道我的手机也有加速度计。任何帮助,将不胜感激!

谢谢,欧文

AccelerometerReader 类

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;

public class AccelerometerReader extends Activity implements SensorEventListener{
 private SensorManager sensorManager;
 float ax,ay,az;   // these are the acceleration in x, y and z axes

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
   }

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

   @Override
   public void onSensorChanged(SensorEvent event) {
       if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
           return;

       if (event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
           ax=event.values[0];
           ay=event.values[1];
           az=event.values[2];
       }
   }


public float getValueX() {
    return ax;
}

public float getValueY() {
    return ay;
}

public float getValueZ() {
    return az;
}
}

MyGame 类内部

@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);
    leftWall = new Rect(-100,0,0,canvas.getHeight());
    rightWall = new Rect(canvas.getWidth(), 0, (canvas.getWidth() + 100), canvas.getHeight());
    floor = new Rect(0,canvas.getHeight(),canvas.getWidth(),(canvas.getHeight() + 100));
    ceiling = new Rect(0,-100,canvas.getWidth(),0);

    AccelerometerReader acc = new AccelerometerReader();
    float ax = acc.getValueX();
    float ay = acc.getValueY();
    float az = acc.getValueZ();     

    canvas.drawColor(Color.rgb(red,green,blue)); //0 or 51?, 51, 102

    Rect player = new Rect(xPos,yPos,xPos+100,yPos+100);
    Paint myPaint = new Paint();
    myPaint.setColor(Color.rgb(0, 102, 255));
    canvas.drawRect(player, myPaint);
    myPaint.setColor(Color.rgb(0, 0, 0));
    canvas.drawRect(xPos + 5, yPos + 5, xPos + 95, yPos +95, myPaint);
    myPaint.setColor(Color.WHITE);
    myPaint.setTextSize(20);
    canvas.drawText("" + Math.round(ySpeed), 75, 50, myPaint);
    canvas.drawText(ax +", "+ ay +", "+ az, 300, 50, myPaint);
    if(gameStarted == false) {
        myPaint.setTextSize(30);
        myPaint.setTextAlign(Align.CENTER);
        canvas.drawText("Touch screen to begin!", canvas.getWidth()/2, canvas.getHeight()/2, myPaint);
    }
    int r = Math.round(rand.nextInt(canvas.getHeight() - 150));
    if(needsRand == true) {
        blockY = r;
        myPaint.setColor(Color.rgb(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)));
    }


    //if(isAlive == true) { 
        Rect block =  new Rect(blockX,blockY,(blockX+100),(blockY+100)); // left, top, right, bottom
        myPaint.setColor(Color.WHITE);
        canvas.drawRect(block, myPaint);
        blockX--;
    //}


    if(player.intersect(leftWall)) {
        xSpeed = Math.abs(xSpeed);
    } else if(player.intersect(rightWall)) { 
        xSpeed = -(xSpeed);
    } else if(player.intersect(floor)) {
        yPos = canvas.getHeight() - 150;
        ySpeed = -(ySpeed)*.75;
    } else if(player.intersect(ceiling)) {
        ySpeed = Math.abs(ySpeed);
    } else if(player.intersect(block)) {
        ySpeed = 0;
    }
    if(blockX <= -100) {
        blockX = canvas.getWidth() + 100;
        needsRand = true;
    } else {
        needsRand = false;
    }

    canvas.drawText("" + r, 300, 100, myPaint);

    physics();
    invalidate();
}
4

2 回答 2

0

你使用的方法对我来说真的很奇怪。您实际上在绘图类中提取加速度计值。这就像,您创建一个加速度计类的实例,然后立即取出他的值(无需等待真正的加速度计实际检索值)然后尝试绘制它。无论如何,这可能是您的问题,您绘制起始加速度计值并且在它们更改时不要刷新它们。我不知道你的其余代码是什么,但是如果你 onDraw 被多次调用,你只需创建你的类的一个新实例,你从中提取的值没有时间被传感器更改读数。

您最好使用 push 方法,在加速度计类中实现一个侦听器接口,以便每当检索到新的加速度值时,都会通知绘图类并获取新值,然后绘制它们。

编辑:我强烈建议您为加速度计使用更快的延迟(最快的会这样做)。请记住,加速度是所有这些中功耗较低的。

于 2012-06-08T09:01:32.247 回答
0

我的服务.java

public class MyService extends Service implements SensorEventListener {
       public void onCreate() {
              super.onCreate();
              sm = (SensorManager) getSystemService(SENSOR_SERVICE);
              sm.unregisterListener(this);  
              sm.registerListener(this,sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_FASTEST);
       }
       public void onDestroy() {
              super.onDestroy();
              sm.unregisterListener(this);
       }

// Creates a new binder
@Override
public IBinder onBind(Intent intent) {
       return new MyBinder<MyService>(this);
}

public void onSensorChanged(SensorEvent event) {
       ax=event.values[0];                           
       ay=event.values[1];                           
       az=event.values[2];                
       for (Listener listener : listeners) listener.handleNewAccelValue(this);
}

public interface Listener {
       // Actions to take when a new position has been added to the model
       void handleNewAccelValue(MyService sender);
}

// List of all the ongoing listeners bound to the Model
private List<Listener> listeners = new ArrayList<Listener>();

// Binds a listener from the View to the Model
public void addListener(Listener listener) {
       this.listeners.add(listener);
}

// Removes a listener from the View to the Model
public void removeListener(Listener listener) {
       this.listeners.remove(listener);
}

你的活动.java

public class YourActivity implements MyService.Listener{
public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState); 
        // Binds to the created service
        doBindService();
}

// Creating the controller and the model
private ServiceComputeFinal controller;

// Creates the connection with a MyService service
ServiceConnection connection = new ServiceConnection(){
    public void onServiceConnected(ComponentName name, IBinder binder) {
        controller = ((MyBinder<MyService>) binder).getService();           
    }

    public void onServiceDisconnected(ComponentName name) {
        controller = null;
    }   
};

// Binds to the created service
void doBindService(){
    bindService(new Intent(this, MyService.class), connection, Context.BIND_AUTO_CREATE);
}

// And finally recover the accelerometer data that interest you
public void handleNewAccelValue(MyService sender){
    DO_WHATEVER_YOU_WANT_WITH(controller.getAx());
}

我给了你所有的工具来做你想做的事。尝试查看这段代码并了解它的作用(其实并不复杂),ServiceConnection 允许 Activity 从 Service 中恢复值,而 Listener 接口允许 Service 在新值准备好时通知 Activity。如果需要,请随时提出任何问题。

于 2012-06-11T08:27:09.513 回答