2025-05-17

 

重力感應主要應用於遊戲開發中,這個效果非常棒!主要是3個軸,簡單理解:那個朝上,值為正,朝下值為負!這個效果我測試過瞭,由於在手機上才能實現重力感應,所以沒有效果圖。見諒!轉載請標明出處:https://blog.csdn.net/wdaming1986/article/details/6752232

 

一、MainActivity。java的代碼:

 

package com.ray.test; 

 

import android.app.Activity; 

import android.hardware.Sensor; 

import android.hardware.SensorEvent; 

import android.hardware.SensorEventListener; 

import android.hardware.SensorManager; 

import android.os.Bundle; 

import android.widget.TextView; 

 

public class MainActivity extends Activity{ 

 

    private SensorManager sensorMgr;  

    private TextView show_TextView; 

    Sensor sensor; 

    private float x, y, z;    

     

    @Override 

    protected void onCreate(Bundle savedInstanceState) { 

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.main); 

        show_TextView = (TextView)findViewById(R.id.text_view); 

        sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);    

        sensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);    

        SensorEventListener lsn = new SensorEventListener()  

        {    

            @Override 

            public void onSensorChanged(SensorEvent e) { 

                // TODO Auto-generated method stub 

                x = e.values[SensorManager.DATA_X];    

                y = e.values[SensorManager.DATA_Y];    

                z = e.values[SensorManager.DATA_Z];    

                setTitle("x="+(int)x+","+"y="+(int)y+","+"z="+(int)z);  

                show_TextView.setText("x="+(int)x+", "+"y="+(int)y+", "+"z="+(int)z); 

            } 

 

            @Override 

            public void onAccuracyChanged(Sensor arg0, int arg1) { 

                 

            }    

        };   //註冊listener,第三個參數是檢測的精確度  

        sensorMgr.registerListener(lsn, sensor, SensorManager.SENSOR_DELAY_GAME);  

    } 

 

二、main.xml的代碼: www.aiwalls.com

 

<?xml version="1.0" encoding="utf-8"?> 

 

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" 

    android:orientation="vertical" 

     

android:layout_width="fill_parent" 

     

android:layout_height="fill_parent" 

     

     

<TextView   

         

android:id="@+id/text_view" 

         

android:layout_width="fill_parent"  

         

android:layout_height="wrap_content"  

         

android:textSize="25pt" 

     

/> 

 

</LinearLayout>   

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *