Xamarin で android の加速度センサーを使う



using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Hardware; // センサーを使うので追加

namespace test0313_1
{
    [Activity (Label = "test0313_1", MainLauncher = true)]
    public class Activity1 : Activity, ISensorEventListener
    {                       // Activity と ISensorEventListener から継承
        float x,y,z;

        private TextView text1;
        private SensorManager _sensorManager;

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            SetContentView (Resource.Layout.Main);
            text1 = FindViewById<TextView> (Resource.Id.textView1);
            _sensorManager = (SensorManager)GetSystemService (SensorService);
        }

        protected override void OnResume()
        {
            base.OnResume();
            _sensorManager.RegisterListener(this, _sensorManager.GetDefaultSensor(SensorType.Accelerometer), SensorDelay.Ui);
        }

        protected override void OnPause()
        {
            base.OnPause();
            //_sensorManager.UnregisterListener(this);
        }

        public void OnAccuracyChanged(Sensor sensor, SensorStatus accuracy)
        {
            // センサーの Accuracy(精度?)が変わった時の処理
            // 何もしない
        }

        public void OnSensorChanged(SensorEvent e)
        {
            x = e.Values [0];
            y = e.Values [1];
            z = e.Values [2];

            text1.Text = "x=" + x.ToString ()
                + "\r\ny=" + y.ToString ()
                + "\r\nz=" + z.ToString ();
        }
    }
}


実機で実行した様子

このブログの人気の投稿

windowsで「インターネット接続の共有」の設定

月刊 I/O 記事リスト 1976~1989

X68000実機のROMを保存