簡體   English   中英

如何在Android中訪問加速度計

[英]How to gain access to the accelerometer in Android

因此,我是Java / Android的初學者,並且我試圖獲得一個顯示手機加速器輸入的簡單應用。 我從書中得到了一些示例代碼:

package com.example.userinterfaceandvibra;

import android.app.Activity;
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.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.util.Log;



public class MainActivity
    extends Activity
    implements SensorEventListener 
{
    TextView statusTv;
    TextView messagesTv;
    SensorManager sensorManager;
    Sensor sensor;
    float g=9.81f;
    float x, y, z;

    /*** Main -- automatically called methods ***/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initGUI();
    }

    @Override
    public void onResume() {
        super.onResume();
        initAccel();
        msg("Running.");
    }

    @Override
    public void onPause() {
        super.onPause();
        closeAccel();
        msg("Paused. \n");
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        x=event.values[1]/g;
        y=event.values[2]/g;
        z=event.values[3]/g;
        statusTv.setText(String.format("x: %3.2f y: %3.2f, z: %3.2f", x,y,z));
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        //Must have when Activity implements SensorEventListener.
    }

    /***  Accelerometer ***/

    void initAccel()
    {
        msg("Accelerometer initialization...");
        sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
        sensor=sensorManager.getDefaultSensor(
                Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(
                this,
                sensor,
                sensorManager.SENSOR_DELAY_NORMAL);
    }

    void closeAccel()
    {
        msg("Accelerometer closing...");
        sensorManager.unregisterListener(this, sensor);
    }

    void initGUI()
    {
        //Window
        setRequestedOrientation(
                ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //Contents
        LinearLayout container=new LinearLayout(this);
        container.setOrientation(android.widget.LinearLayout.VERTICAL);
        statusTv = new TextView(this);
        container.addView(statusTv);
        messagesTv = new TextView(this);
        container.addView(messagesTv);
        //Show
        setContentView(container);
        msg("User interface created.");
    }

    public void msg(String s)
    {
        if (7<=messagesTv.getLineCount()) messagesTv.setText("");
        messagesTv.append(s);
    }


}

我的代碼沒有運行任何錯誤,但是,當我嘗試啟動它時,我得到的是經典的“不幸的是,myApp已停止。” 起初,我認為這是因為我的應用沒有使用加速器的權限,所以這是我的清單文件,我(希望)在其中添加了正確的代碼以獲得權限。

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

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

    <uses-feature android:name="android.hardware.sensor.accelerometer" 
        android:required="true"/>


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.userinterfaceandvibra.MainActivity"
            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>

最后,我調查了日志貓以嘗試查看正在拋出什么錯誤。 因為我太新了,所以我並不能真正獲得大部分,但是很明顯,第一個錯誤是“異常調度輸入事件”。 但是我看不到行號,並且由於錯誤如此模糊,我真的不知道下一步該怎么做。 對於那些比我聰明的人,這是logcat的讀數:

04-05 20:13:00.084: D/SensorManager(21947): registerListener :: create queue :: handler = 0, name = K330 3-axis Accelerometer, delay = 200000, 
04-05 20:13:00.104: D/SensorManager(21947): unregisterListener ::  
04-05 20:13:00.184: D/SensorManager(21947): registerListener :: create queue :: handler = 0, name = K330 3-axis Accelerometer, delay = 200000, 
04-05 20:13:00.304: D/libEGL(21947): loaded /vendor/lib/egl/libEGL_adreno.so
04-05 20:13:00.304: D/libEGL(21947): loaded /vendor/lib/egl/libGLESv1_CM_adreno.so
04-05 20:13:00.314: D/libEGL(21947): loaded /vendor/lib/egl/libGLESv2_adreno.so
04-05 20:13:00.324: I/Adreno-EGL(21947): <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build:  (CL4169980)
04-05 20:13:00.324: I/Adreno-EGL(21947): OpenGL ES Shader Compiler Version: 17.01.10.SPL
04-05 20:13:00.324: I/Adreno-EGL(21947): Build Date: 09/26/13 Thu
04-05 20:13:00.324: I/Adreno-EGL(21947): Local Branch: 
04-05 20:13:00.324: I/Adreno-EGL(21947): Remote Branch: 
04-05 20:13:00.324: I/Adreno-EGL(21947): Local Patches: 
04-05 20:13:00.324: I/Adreno-EGL(21947): Reconstruct Branch: 
04-05 20:13:00.424: D/OpenGLRenderer(21947): Enabling debug mode 0
04-05 20:13:00.434: E/SensorManager(21947): Exception dispatching input event.
04-05 20:13:00.434: D/AndroidRuntime(21947): Shutting down VM
04-05 20:13:00.434: W/dalvikvm(21947): threadid=1: thread exiting with uncaught exception (group=0x4176d898)
04-05 20:13:00.444: E/AndroidRuntime(21947): FATAL EXCEPTION: main
04-05 20:13:00.444: E/AndroidRuntime(21947): java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
04-05 20:13:00.444: E/AndroidRuntime(21947):    at com.example.userinterfaceandvibra.MainActivity.onSensorChanged(MainActivity.java:54)
04-05 20:13:00.444: E/AndroidRuntime(21947):    at android.hardware.SystemSensorManager$SensorEventQueue.dispatchSensorEvent(SystemSensorManager.java:467)
04-05 20:13:00.444: E/AndroidRuntime(21947):    at android.os.MessageQueue.nativePollOnce(Native Method)
04-05 20:13:00.444: E/AndroidRuntime(21947):    at android.os.MessageQueue.next(MessageQueue.java:132)
04-05 20:13:00.444: E/AndroidRuntime(21947):    at android.os.Looper.loop(Looper.java:124)
04-05 20:13:00.444: E/AndroidRuntime(21947):    at android.app.ActivityThread.main(ActivityThread.java:5419)
04-05 20:13:00.444: E/AndroidRuntime(21947):    at java.lang.reflect.Method.invokeNative(Native Method)
04-05 20:13:00.444: E/AndroidRuntime(21947):    at java.lang.reflect.Method.invoke(Method.java:525)
04-05 20:13:00.444: E/AndroidRuntime(21947):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
04-05 20:13:00.444: E/AndroidRuntime(21947):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
04-05 20:13:00.444: E/AndroidRuntime(21947):    at dalvik.system.NativeStart.main(Native Method)

如果您查看logcat錯誤:

04-05 20:13:00.444: E/AndroidRuntime(21947): java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
04-05 20:13:00.444: E/AndroidRuntime(21947):    at com.example.userinterfaceandvibra.MainActivity.onSensorChanged(MainActivity.java:54)

數組長度為3,正在訪問的索引為3。由於數組從索引0開始,因此可以通過索引0,1,2訪問3個數組元素。 因此,將您的onSensorChanged方法更改為:

x=event.values[1]/g;
y=event.values[2]/g;
z=event.values[3]/g;

x=event.values[0]/g;
y=event.values[1]/g;
z=event.values[2]/g;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM