在c#中定义加速度计传感器时出现System.NullReferenceException

时间:2016-05-25 09:41:50

标签: c# android accelerometer sensormanager

我是c#编程的初学者并遇到问题: 我在第51行得到一个System.NullReferenceException,我想创建一个SensorManager。我从“专业跨平台移动开发在C#”一书中得到了这个代码,但不确定,在哪里调用AccelerometerStart方法!如果有人可以帮助我,真的很好!

感谢您的帮助:)

using Magic.Util;
using System;
using Android.Content;
using Android.Hardware;
using Magic.UI;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Android.OS;



namespace Magic
{

    public class MiningMinigame : Scene, ISensorEventListener
    {
        Context _context;

        //Random float value
        Random random;

        //Current mining Container Position
        float xPositionMiningContainer;

        //max & min value depends on the displaysize
        float minValue;
        float maxValue;

        //device sizes
        int deviceWidth;
        int deviceHeight;

        //UIElements
        UIElement backgroundImage;
        UIElement miningContainer;


        public MiningMinigame (SceneManager sM)
            : base(sM)
        {
            deviceWidth = graphicsDevice.Viewport.Width;
            deviceHeight = graphicsDevice.Viewport.Height;
            SceneManager = sM;
            InitializeBackgroundImage ();
            InitializeMiningContainer ();
        }

        protected void AccelerometerStart() {
            SensorManager sm = _context.GetSystemService(Context.SensorService) as SensorManager;
            Sensor sensor = sm.GetDefaultSensor(SensorType.Accelerometer); 
            if (sensor != null)
            {
                sm.RegisterListener(this, sensor, SensorDelay.Ui); 
            }
            else 
            {
                throw new Exception("Could not load Accelerometer sensor"); 
            }
        }

        void AccelerometerCancel() 
        {
            SensorManager sm = _context.GetSystemService(Context.SensorService) as SensorManager;
            Sensor sensor = sm.GetDefaultSensor(SensorType.Accelerometer);
            sm.UnregisterListener(this); 
        }

        public void OnAccuracyChanged(Sensor sensor, SensorStatus sensorStatus) 
        {
        }

        public void OnSensorChanged(SensorEvent e) 
        {
            string js = string.Empty; switch (e.Sensor.Type)
            {
            case SensorType.Accelerometer: 
                js = string.Format(
                    "javascript:accelerometer.onAccelerometerSuccess({0:0.00})", 
                    e.Values[0], e.Values[1], e.Values[2]);
                break; 
            }
            if (js.Length > 0) 
            {

            } 
        }

        public IntPtr Handle 
        {
            get { throw new NotImplementedException(); } 
        }

        public override void OnCreate ()
        {
            base.OnCreate ();
            AccelerometerStart ();
        }

        /// <summary>
        /// Initializes the background image.
        /// </summary>
        public void InitializeBackgroundImage() 
        {
            Console.WriteLine("Welcome in the MiningMiniGame Scene");

            //Sets the backgroundimage of the Scene
            backgroundImage = new UIElement(this, new Rectangle(0, 0, deviceWidth, deviceHeight));
            backgroundImage.SetBackgroundTexture(Resources.Content.Load<Texture2D>("Images/UI/Backgrounds/main_background"));
            AddUIElement(backgroundImage);
        }

        /// <summary>
        /// Initializes the mining container, where you collect the downfalling stuff.
        /// </summary>
        /// <returns>The mining container.</returns>
        public void InitializeMiningContainer()
        {
            miningContainer = new UIElement (this, new Rectangle ((int)(deviceWidth * 0.375), (int)(deviceHeight * 0.8), (int)(deviceWidth * 0.25), (int)(deviceHeight * 0.2)));
            miningContainer.SetBackgroundTexture (Resources.Content.Load<Texture2D> ("Images/UI/Buttons/mine"));
            miningContainer.SetID ("MiningContainer");
//          miningContainer.SetOnClickMethod (delegate() 
//              {
//                  
//              });
            AddUIElement (miningContainer);
        }

        /// <summary>
        /// Updates the x-position from the mining container.
        /// </summary>
        public void UpdatePositionMiningContainer(float xPosition) {
            miningContainer.Position.X = xPosition;
        }


        /// <summary>
        /// Update the scene using the specified gameTime.
        /// </summary>
        /// <param name="gameTime">Game time.</param>
        public override void Update (Microsoft.Xna.Framework.GameTime gameTime)
        {
            base.Update (gameTime);
            HandleBackButton();
        }

        /// <summary>
        /// Draw the scene using the specified gameTime.
        /// </summary>
        /// <param name="gameTime">Game time.</param>
        public override void Draw (Microsoft.Xna.Framework.GameTime gameTime)
        {
            graphicsDevice.Clear (Color.White);
            base.Draw (gameTime);
        }

        /// <summary>
        /// Handles the back button.
        /// </summary>
        private void HandleBackButton()
        {
            if(GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed){
                Console.WriteLine("HardwareBackButton in MiniGame was clicked!");
                SceneManager.SwitchToOldScene();
            }
        }

        /// <summary>
        /// Creates the random X position.
        /// </summary>
        /// <returns>The random X position.</returns>
        public float createRandomXPosition()
        {
            minValue = 0;
            maxValue = graphicsDevice.Viewport.Width;
            return ((float)random.NextDouble ()) * (maxValue - minValue) + minValue;
        }

        /// <summary>
        /// Releases all resource used by the <see cref="Magic.MiningMinigame"/> object.
        /// </summary>
        /// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="Magic.MiningMinigame"/>. The
        /// <see cref="Dispose"/> method leaves the <see cref="Magic.MiningMinigame"/> in an unusable state. After calling
        /// <see cref="Dispose"/>, you must release all references to the <see cref="Magic.MiningMinigame"/> so the garbage
        /// collector can reclaim the memory that the <see cref="Magic.MiningMinigame"/> was occupying.</remarks>
        public override void Dispose()
        {

        }

    }
}

0 个答案:

没有答案