Android SDK 自带的案例源码都很不错,想学习一下。本着天朝的大无畏分享精神,这里就把自己学习的东西跟大家分享下,共同进步。
AccelerometerPlay是Android自带例子中的加速度传感器的使用,同时也使用了自定义view。例子的运行效果由于网络不行,图片上传不了,感兴趣的朋友可以网上下载一个源码运行下看看,本博客也会附上源码的链接。
Android中自带的该例子把所有的类都写在了一起,本人觉得看的麻烦,容易让人思路不清(个人看法),就把他们都分开了。
主界面AccelerometerPlay类源码如下:
* This is an example of using the accelerometer to integrate the device's
* acceleration to a position using the Verlet method. This is illustrated with
* a very simple particle system comprised of a few iron balls freely moving on
* an inclined wooden table. The inclination of the virtual table is controlled
* by the device's accelerometer.
*
* @see SensorManager
* @see SensorEvent
* @see Sensor
*/
/**
* 参考资料 weakLock机制浅析:http://blog.sina.com.cn/s/blog_4ad7c2540101n2k2.html
* SensorManager:http://www.cnblogs.com/androidez/archive/2013/02/06/2901295.
* html
*
* 传感器的坐标系:http://www.cnblogs.com/mengdd/archive/2013/03/12/2954947.html
* @author LIUBO
*
*/
public class AccelerometerPlayActivity extends Activity {
private SimulationView mSimulationView;
/** 电源管理者 */
private PowerManager mPowerManager;
/** 唤醒锁 */
private WakeLock mWakeLock;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 获取一个电池管理者的实例
mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
// SCREEN_BRIGHT_WAKE_LOCK:保持CPU 运转,保持屏幕高亮显示,允许关闭键盘灯
// 保持屏幕的高亮
mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, getClass().getName());
//自定义的view,该示例的核心
mSimulationView = new SimulationView(this);
setContentView(mSimulationView);
}
@Override
protected void onResume() {
super.onResume();
mWakeLock.acquire();
//注册加速度传感器
mSimulationView.startSimulation();
}
@Override
protected void onPause() {
super.onPause();
//解除加速度传感器的注册
mSimulationView.stopSimulation();
mWakeLock.release();
}
}
上面的代码主要是传感器的注册和保持屏幕高亮显示。
该示例的核心VIew SImulationView继承View实现传感器的事件监听接口
<pre name="code" class="java">public class SimulationView extends View implements SensorEventListener {
// diameter of the balls in meters(以米为单位:小球的直径&