if(Math.abs(pitch)<=k){
mv.zuo2_Y=mv.zuo1_Y //左面的
+ (int)(((mv.zuoBitmap1.getHeight()
-mv.zuoBitmap2.getHeight())/2.0)
+(((mv.zuoBitmap1.getHeight()
-mv.zuoBitmap2.getHeight())/2.0)*pitch)/k);
y =mv.zhong1_Y+ //中间的
(int)(((mv.zhongBitmap1.getHeight()
-mv.zhongBitmap2.getHeight())/2.0)
+(((mv.zhongBitmap1.getHeight()
-mv.zhongBitmap2.getHeight())/2.0)*pitch)/k);
}else if(pitch>k){
mv.zuo2_Y=mv.zuo1_Y
+mv.zuoBitmap1.getHeight()
-mv.zuoBitmap2.getHeight();
y=mv.zhong1_Y+mv.zhongBitmap1.getHeight()
-mv.zhongBitmap2.getHeight();
}else{
mv.zuo2_Y = mv.zuo1_Y; y = mv.zhong1_Y;
}
//下面的
tempX = -(int) (((mv.xiaBitmap1.getWidth()/2-28)*roll
+(mv.xiaBitmap1.getWidth()/2-28)*pitch)/k);
tempY = -(int) ((-(mv.xiaBitmap1.getWidth()/2-28)*roll
-(mv.xiaBitmap1.getWidth()/2-28)*pitch)/k);
//限制下面的气泡范围
if(tempY>mv.xiaBitmap1.getHeight()/2-28){
tempY = mv.xiaBitmap1.getHeight()/2-28;
}
if(tempY < -mv.xiaBitmap1.getHeight()/2+28){
tempY = -mv.xiaBitmap1.getHeight()/2+28;
}
if(tempX > mv.xiaBitmap1.getWidth()/2-28){
tempX = mv.xiaBitmap1.getWidth()/2-28;
}
if(tempX < -mv.xiaBitmap1.getWidth()/2+28){
tempX = -mv.xiaBitmap1.getWidth()/2+28;
}
mv.xia2_X = tempX + mv.xia1_X
+ mv.xiaBitmap1.getWidth()/2
-mv.xiaBitmap2.getWidth()/2;
mv.xia2_Y = tempY + mv.xia1_Y
+ mv.xiaBitmap1.getHeight()/2
- mv.xiaBitmap2.getWidth()/2;
if(isContain(x, y)){//中间的水泡在圆内才改变坐标
mv.zhong2_X = x; mv.zhong2_Y = y;
}
mv.postInvalidate();//重绘MainView
}
}
在onSensorChanged 方法中首先得到pitch 轴以及roll 轴的数值, 然后根据该数值的大小调整水泡在屏幕中的位置, 同时需要对水泡的坐标进行判断, 使其保持在自身所在外框的范围内。
此时运行该程序, 并保证测试工具Sensorsimulator 与Android模拟器的连通, 便会观察到如图1 所示的效果, 通过Sensorsimulator 工具模拟手机的姿态的改变, 屏幕中的水泡便随之向高处运动。
8 程序发布
完成了所有代码的开发后, 就可以将应用程序打包发布了。本案例中只需将Eclipse 工具自动生成的apk 文件拷出即可, 按如下步骤操作。
(1) 进行正式发布之前首先需要将代码中注释为"测试时使用" 的两处代码删掉, 并将注释为"真机使用" 代码的注释去掉。
(2) 完成代码的修改后重新构建项目。
(3) 打开项目文件夹下的bin 目录, 其中名为SPY 的apk文件便为本应用程序的安装包。
(4) 将SPY.apk 文件拷贝到支持传感器的Android 手机中运行即可完成本应用程序的安装。
9 结语
通过开发基于Android 平台的传感器应用---水平仪程序, 读者应该对Android 程序的开发有了一定的了解, 同时读者也应该了解到在Android 平台下使用传感器来丰富自己软件的功能是十分方便的。
评论