Android Accelerometer App仅检测两个方向

时间:2014-04-07 06:41:35

标签: java android eclipse accelerometer direction

我正在通过Eclipse编写一个针对Android的加速度计应用程序。我是编程Java的新手(这是我的第四个应用程序)。我得到正确的“右”和“向上”方向的显示,但它没有注册任何其他方向。思考?我知道z轴变化的图像是相同的,但即使评论出来,我也会遇到同样的问题。 谢谢!

附件是我的MainActivity.java,activity_main.xml和我的清单。

MainActivity.java

package com.example.accelerometer;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;



public class MainActivity extends Activity implements SensorEventListener{

    float [] history = new float[3];
    private int mIndex = 0;
    private int[] mImgs = new int[3];

    public Bitmap mBitMap;
    public TextView mTextView;
    public ImageView mImage;

    private SensorManager senSensorManager;
    private Sensor senAccelerometer;
    private long lastUpdate = 0;
    private float last_x, last_y, last_z;
    private static final int SHAKE_THRESHOLD = 600;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mImgs[0] = R.drawable.left;
        mImgs[1] = R.drawable.right;
        mImgs[2] = R.drawable.up;
        mImgs[3] = R.drawable.down;
        mImage = (ImageView) findViewById(R.id.imageView1);
//      mTextView = (TextView) findViewById(R.id.textView1);
        mBitMap = BitmapFactory.decodeResource(getResources(), mImgs[mIndex]);
        mImage.setImageResource(mImgs[mIndex]);  // Easiest way to show a image

        senSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        senSensorManager.registerListener(this, senAccelerometer , SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        Sensor mySensor = event.sensor;
        long curTime = System.currentTimeMillis();

        if ((curTime - lastUpdate) > 100) {
            long diffTime = (curTime - lastUpdate);
            lastUpdate = curTime;

        if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            float xChange = history[0] - event.values[0];
            float yChange = history[1] - event.values[1];
            float zChange = history[2] - event.values[2];

            history[0] = event.values[0];
            history[1] = event.values[1];
            history[2] = event.values[2];

            if ((Math.abs(xChange) > 2) || (Math.abs(yChange) > 2) || (Math.abs(zChange) > 2))
            {
                if ((xChange > yChange) && (xChange > zChange))

                {

                    if (xChange > 2){
                        //Left
        //              mIndex++;
        //              if (mIndex == 3) { mIndex = 0; }  // Overflow
                        mBitMap = BitmapFactory.decodeResource(getResources(), mImgs[0]);
                        mImage.setImageBitmap(mBitMap);
                        mImage.setVisibility(View.VISIBLE);
                    }
                    else if (xChange < -2){
                        //Right
                        mBitMap = BitmapFactory.decodeResource(getResources(), mImgs[1]);
                        mImage.setImageBitmap(mBitMap);
                        mImage.setVisibility(View.VISIBLE);
                    }
                }
                if ((yChange > xChange) && (yChange > zChange))

                    if (yChange > 2)
                    {
                        //Down
                        mBitMap = BitmapFactory.decodeResource(getResources(), mImgs[2]);
                        mImage.setImageBitmap(mBitMap);
                        mImage.setVisibility(View.VISIBLE);
                    }
                    else if (yChange < -2){
                        //Up
                        mBitMap = BitmapFactory.decodeResource(getResources(), mImgs[3]);
                        mImage.setImageBitmap(mBitMap);
                        mImage.setVisibility(View.VISIBLE);
                    }
            }
            if ((zChange > xChange) && (zChange > yChange))
            {
            if (zChange > 2){
                //Out
                mBitMap = BitmapFactory.decodeResource(getResources(), mImgs[0]);
                mImage.setImageBitmap(mBitMap);
                mImage.setVisibility(View.VISIBLE);
            }
            else if (zChange < -2){
                //In
                mBitMap = BitmapFactory.decodeResource(getResources(), mImgs[0]);
                mImage.setImageBitmap(mBitMap);
                mImage.setVisibility(View.VISIBLE);
            }
            }
        }

//          
//              
//              float speed = Math.abs(x + y + z - last_x - last_y - last_z)/ diffTime * 10000;
//              
//              if (speed > SHAKE_THRESHOLD) {
//   
//              }
//   
//              last_x = x;
//              last_y = y;
//              last_z = z;

            }
        }

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

    }

    protected void onPause() {
        super.onPause();
        senSensorManager.unregisterListener(this);
    }
    protected void onResume() {
        super.onResume();
        senSensorManager.registerListener(this, senAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="@string/hello_world" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="90dp"
        android:src="@drawable/up"
        android:visibility="invisible" />

</RelativeLayout>

清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.accelerometer"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.accelerometer.MainActivity"
            android:screenOrientation="portrait"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

1 个答案:

答案 0 :(得分:0)

我有类似的代码并正在运行...试试这个:

package com.example.accelerometer;

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.view.Menu;
import android.widget.ImageView;
import android.widget.TextView;

public class AccelerometerActivity extends Activity implements
SensorEventListener {    
    private SensorManager mSensorManager;
    private Sensor mAccelerometer;
    TextView title;
    ImageView iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_accelerometer);

        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAccelerometer = mSensorManager
                .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        title = (TextView) findViewById(R.id.txt);
        iv = (ImageView) findViewById(R.id.imageView1);
    }

    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1) {
        // TODO Auto-generated method stub
    }
    @Override
    public void onSensorChanged(SensorEvent event) {
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];
        if (Math.abs(x) > Math.abs(y)) {
            if (x < 0) {
                iv.setImageResource(R.drawable.cartoonright);
            }
            if (x > 0) {
                iv.setImageResource(R.drawable.cartoonleft);
            }
        } else {
            if (y < 0) {
                iv.setImageResource(R.drawable.cartoontop);
            }
            if (y > 0) {
                iv.setImageResource(R.drawable.ic_launcher);
            }
        }
        if (x > (-2) && x < (2) && y > (-2) && y < (2)) {
            iv.setImageResource(R.drawable.cartooncenter);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this, mAccelerometer,
                SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.accelerometer, menu);
        return true;
    }
}

这是我的activity_accelerometer:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/relative"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <TextView
    android:id="@+id/txt"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="20dp"
    android:text="Tilt the phone to see the difference" />

    <ImageView
    android:id="@+id/imageView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_below="@+id/txt"
    android:layout_centerHorizontal="true"
    android:scaleType="fitXY"
    android:src="@drawable/cartooncenter" />
    </RelativeLayout>