Search code examples
androidwear-os

Will my code work on an Android wear?


I'm new to Android. This is my first wear compatible app. I know this is a very silly question, but I don't know if my code below works on wear or not (I don't have a real device).

    public class MainWearActivity extends Activity implements SensorEventListener {

    // record the compass picture angle turned
    private float currentDegree = 0f;
    private SensorManager mSensorManager;
    ImageView image;
    TextView tvHeading;
    TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
        stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
            @Override
            public void onLayoutInflated(WatchViewStub stub) {
                mTextView = (TextView) stub.findViewById(R.id.text);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        // for the system's orientation sensor registered listeners
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_GAME);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // to stop the listener and save battery
        mSensorManager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {

        // get the angle around the z-axis rotated
        float degree = event.values[0];
        if (Math.round(degree) == 360) {
            tvHeading.setText("0°");
        }else{
            tvHeading.setText(Math.round(degree) + "°");
        }
        // create a rotation animation (reverse turn degree degrees)
        RotateAnimation ra = new RotateAnimation(currentDegree, -degree, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        // how long the animation will take place
        ra.setDuration(210);
        // set the animation after the end of the reservation status
        ra.setFillAfter(true);
        // Start the animation
        currentDegree = -degree;
        image.startAnimation(ra);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // Not in use
    }
}

UPDATE:

Now you can test apps that require sensors on an emulator by using virtual sensors.


Solution

  • You do not have an Android Wear. But you can have access to a simulator of Android Wear. Look at Android Wear Emulator.

    Update your SDK, set up an Android Wear Device and you can test your app and verify your code by yourself.

    Hope this could be helpful.