1. Before updating to Windows 10 you may need to return your Pro license. More information here

Android life cycle accelerometer and gyroscope

Discussion in 'Android Development' started by jdwieber, Apr 29, 2012.

  1. jdwieber

    jdwieber

    Joined:
    Mar 20, 2012
    Messages:
    28
    Hello,

    I'm working on a mobile game that uses the accelerometer and gyroscope. When deployed to an android device, the game works well in the beginning. However, if the device sleeps, when I wake it up and try to continue playing the gyroscope, and accelerometer both stop working. Is there a way to hook into the android life cycle functions without writing a custom activity? The script that I'm using to update the gravity direction is below. It's very simple and does the job, until the phone sleeps. Also, can I provide a custom manifest without overriding the default unity activity (for using-permissions)?

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class GravityDirectionUpdater : MonoBehaviour
    5. {
    6.     private static Quaternion m_quat;
    7.     public float m_gravity = -29.8f;
    8.  
    9.     // Use this for initialization
    10.     void Start ()
    11.     {
    12.         //Doesn't always work unless I put this here.
    13.         Input.gyro.enabled = true;
    14.  
    15.         //TODO: reorient camera in scene to avoid transforming frame in scripts
    16.         m_quat = Quaternion.AngleAxis ( -90, Vector3.up ) *
    17.                  Quaternion.AngleAxis ( -90, Vector3.forward ) *
    18.                  Quaternion.AngleAxis ( -90, Vector3.left );
    19.     }
    20.  
    21.     // Update is called once per frame
    22.     void Update ()
    23.     {
    24.         //I always see this, even after waking up
    25.         Debug.Log ( "Updat gyro.enabled: " + Input.gyro.enabled.ToString () );
    26.  
    27.         //This makes no difference here
    28.         Input.gyro.enabled = true;
    29.  
    30.         Physics.gravity = m_quat * ( Input.gyro.gravity.normalized * m_gravity );
    31.  
    32.     }
    33. }
     
  2. szi_John

    szi_John

    Joined:
    Feb 10, 2012
    Messages:
    70
    Have you tried turning off sleep?

    Code (csharp):
    May not suit your exact app but...
     
  3. jdwieber

    jdwieber

    Joined:
    Mar 20, 2012
    Messages:
    28
    Hi John,
    Thanks for the suggestion. It does prevent the problem and the annoyance of the screen dimming during play. The only thing I did different is that I used the unity constant.

    Code (csharp):
    1.  Screen.sleepTimeout = SleepTimeout.NeverSleep;
    Cheers