android compass 源码,Android Compass

fe554079bcfdd355f305524f0e8a85ed.png

Introduction

This article explains how we can create our own compass app using the built-in magnetic sensor of our mobile device.

The foremost thing to remember is that a compass app works by using the data provided by the magnetometer sensor on a mobile device. So if our mobile device does not have this sensor, a compass app cannot run on it.

Also magnetometers are very sensitive to magnetic or electrical signals. So be careful that you are holding the device away from any such signals to get accurate direction from the compass app.

I have used the following image from cliparts.co for my compass app:

pi5op9qyT.png

Background

In this article, I have used a TextView control to display the angle at which the device is oriented. Also, I have used an image of a compass to point to the North-South direction. In order for all this to work, the sensor manager of the device needs to be initialized when the app is initialized.

Also, we need to register the orientation sensor of the device when the app is activated and unregister it when the app is paused, to conserve battery.

Using the code

Following is the main layout file which defines a TextView control and an ImageView control in a relative layout:

Copy Code

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:gravity="center"

android:orientation="vertical" >

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@+id/txtDegrees"

android:src="@drawable/compass" />

The following code is used to initialize the image for our compass.

Copy Code

imgCompass=(ImageView)findViewById(R.id.imgCompass);

The following code is used to initialize the textview to display the degree of rotation.

Copy Code

txtDegrees=(TextView)findViewById(R.id.txtDegrees);

The getSystemService() method can be used to initialize the sensor manager of our device as follows:

Copy Code

sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);

Following is the full code of the onCreate() method which is called once when the app is started:

Copy Code

@Override

public void onCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

imgCompass=(ImageView)findViewById(R.id.imgCompass);

txtDegrees=(TextView)findViewById(R.id.txtDegrees);

sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);

}

Following is the code of the onResume() method which is automatically called whenever the activity comes to the foreground:

Copy Code

@Override

protected void onResume()

{

super.onResume();

sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),SensorManager.SENSOR_DELAY_GAME);

}

The above code registers a SensorEventListener for the orientation sensor of our device at the sampling frequency specified by the parameter SensorManager.SENSOR_DELAY_GAME, which represents a rate suitable for games.

The following code unregisters the SensorEventListener when the activity is paused.

Copy Code

@Override

protected void onPause()

{

super.onPause();

sensorManager.unregisterListener(this);

}

The main action occurs in the following onSensorChanged() method. The onSensorChanged() method gets executed whenever sensor values have changed.

Copy Code

@Override

public void onSensorChanged(SensorEvent event)

{

float degree=Math.round(event.values[0]);

txtDegrees.setText("Rotation: "+Float.toString(degree)+"degrees");

RotateAnimation ra=new RotateAnimation(currentDegree,-degree,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);

ra.setDuration(120);

ra.setFillAfter(true);

imgCompass.startAnimation(ra);

currentDegree=-degree;

}

In the above code, the SensorEvent is the parameter to the onSensorChanged() method.

The degree of rotation is determined by the code float degree=Math.round(event.values[0]); and is displayed on the TextView using the setText() method.

The size and data of the values array depends on the sensor type.

In case of the orientation sensor, the values array contains the following values:

values[0]: Angle between the magnetic north direction and the y-axis around the z-axis (0 to 359), where 0=North, 90=East, 180=South, 270=West.

values[1]: Rotation around x-axis (-180 to 180), with positive values when the z-axis moves towards the y-axis.

values[2]: Rotation around x-axis, (-90 to 90), increasing as the device moves clockwise.

After that a RotateAnimation object is used to rotate the compass as the device is rotated. The constructor of the RotateAnimation class takes the following parameters:

fromDegrees: Rotation offset at the start of the animation.

toDegrees: Rotation offset at the end of the animation.

pivotXType: Interpretation of pivotXValue. Can be Animation.ABSOLUTE, Animation.RELATIVE_TO_SELF or Animation.RELATIVE_TO_PARENT.

pivotXValue: X coordinate of the point about which the object is being rotated.

pivotYType: Interpretation of pivotYValue. Can be Animation.ABSOLUTE, Animation.RELATIVE_TO_SELF or Animation.RELATIVE_TO_PARENT.

pivotYValue: Y coordinate of the point about which the object is being rotated.

The setDuration() method of the Animation class is used to specify the duration in milliseconds for which the animation should last.

The setFillAfter() method of the Animation class is used to persist the transformation produced by this animation.

The startAnimation() method of the Animation class is used to start the animation.

Finally, the currentDegree is updated with the value of -degree so that the next animation will start from the new position.

The following function is not used but is required to be specified because our activity class implements the SensorEventListener interface:

Copy Code

@Override

public void onAccuracyChanged(Sensor p1, int p2)

{

}

Following is the output of the execution of the compass app on my Samsung Galaxy Note 3 Neo mobile:

fe554079bcfdd355f305524f0e8a85ed.png

Points of Interest

I hope this article will help readers in understanding how easy it is to create our own compass app.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值