在OPhone应用程序中使用传感器和LBS

移动开发
OPhone是中国移动最新的手机平台,基于Google Android系统并与Android兼容。在3G时代,基于OPhone的手机应用将充分发挥智能手机的运算能力和无线网络功能,为消费者带来丰富的无线应用体验,同时为开发者带来不菲的回报。

OPhone平台内置了非常多的传感器,通过最新的硬件技术配合强大的系统API,开发者可以轻松调用手机内置的传感器,编写极具特色的非常适合移动设备使用的应用程序,为用户带来更强的移动应用体验。
本文以最常用的重力传感器和位置传感器为例,详细介绍如何在OPhone平台上开发基于传感器的应用。
 
搭建OPhone开发环境

为了开发OPhone应用程序,我们需要首先搭建OPhone开发环境。目前,OPhone开发平台支持Windows和Linux,可以参考“RSS Reader实例开发之搭建OPhone开发环境”一文搭建OPhone开发环境。

使用重力传感器

重力传感器是OPhone应用中最常用的一种传感器,它用于探测手机在各个方向的倾斜角度。重力传感器一共有X,Y,Z三个方向的传感数据,X,Y,Z轴定义如下:

 

当手机沿某个轴左右晃动时,传感器将返回-9.81至+9.81之间的数值,表示手机的倾斜角度。可以理解为将一个小球放在手机当前位置时的重力加速度。当手机水平放置时,小球的重力加速度是0:

 

当手机垂直放置时,小球的重力加速度是9.81:

 

当手机以一定倾斜角放置时,小球的重力加速度介于0和9.81之间:

 


实际的返回值为-9.81至+9.81,使用正负是为了区分手机的两种方向的倾斜。通过X、Y、Z三个轴返回的重力加速度,就可以完全确定当前手机的旋转位置。
重力传感器对于开发感应游戏来说至关重要,由于手机按键的限制,使用键盘的上下左右键控制游戏很不容易,而重力传感器则能让玩家通过晃动手机来控制游戏,带来更好更具特色的游戏体验。著名的手机游戏“平衡木”就完全依靠重力传感器来让玩家控制游戏:

 


下面,我们用一个实际例子来演示如何使用重力传感器。这个简化版的“平衡木”例子将在手机屏幕中央绘制一个小球,当用户晃动手机时,小球也将上下左右移动。#t#

我们新建一个OPhone工程,命名为Accelerometer,然后,编辑XML布局。我们在LinearLayout中放置一个TextView,用于显示重力传感器返回的数值,一个FrameLayout,包含一个自定义的BallView,内容如下:

  1. xml version="1.0" encoding="utf-8"?>     
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  3.     android:orientation="vertical"    
  4.     android:layout_width="fill_parent"    
  5.     android:layout_height="fill_parent"    
  6. >      
  7.     <TextView xmlns:android=  
  8. "http://schemas.android.com/apk/res/android"    
  9.         android:id="@+android:id/ball_prompt"    
  10.         android:layout_width="fill_parent"    
  11.         android:layout_height="wrap_content"    
  12.         android:text="Sensor: 0, 0, 0"    
  13.     />     
  14.     <FrameLayout xmlns:android=  
  15. "http://schemas.android.com/apk/res/android"    
  16.         android:id="@+android:id/ball_container"    
  17.         android:layout_width="fill_parent"    
  18.         android:layout_height="fill_parent"    
  19.     >     
  20.         <org.expressme.wireless.accelerometer.BallView xmlns:android=  
  21. "http://schemas.android.com/apk/res/android"    
  22.             android:id="@+android:id/ball"    
  23.             android:src="@drawable/icon"    
  24.             android:scaleType="center"    
  25.             android:layout_width="wrap_content"    
  26.             android:layout_height="wrap_content"    
  27.         />     
  28.     FrameLayout>     

BallView派生自ImageView,主要通过moveTo(x,y)方法方便地将小球移动到指定的位置:

  1. public class BallView extends ImageView {     
  2.     public BallView(Context context) {     
  3.         super(context);     
  4.     }     
  5.       
  6.     public BallView(Context context, AttributeSet attrs) {     
  7.         super(context, attrs);     
  8.     }     
  9.       
  10.     public BallView(Context context, AttributeSet attrs, int defStyle) {     
  11.         super(context, attrs, defStyle);     
  12.     }     
  13.       
  14.     public void moveTo(int l, int t) {     
  15.         super.setFrame(l, t, l + getWidth(), t + getHeight());     
  16.     }     
  17. }    

下面,我们就需要在MainActivity中编写主要逻辑,获得重力传感器返回的数值。重力传感器的API主要是SensorManager和Sensor,在Activity的onCreate()方法中,我们可以获得系统的SensorManager实例,然后,再获得对应的Sensor实例:

  1. public class MainActivity extends Activity {     
  2.     SensorManager sensorManager = null;     
  3.     Sensor sensor = null;     
  4.       
  5.     @Override    
  6.     public void onCreate(Bundle savedInstanceState) {     
  7.         super.onCreate(savedInstanceState);     
  8.         setContentView(R.layout.main);     
  9.         prompt = (TextView) findViewById(R.id.ball_prompt);     
  10.         sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);     
  11.         sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);     
  12.     }     
  13.     ...     
  14. }    

我们编写一个register()方法,用于向SensorManager注册SensorEventListener,然后,在SensorEventListener中响应onSensorChanged事件,并处理即可。而unregister()方法则取消已注册的SensorEventListener。
 
SensorEventListener的onSensorChanged事件将返回SensorEvent对象,包含Sensor的最新数据,通过e.values获得一个float[]数组。对于不同的Sensor类型,其数组包含的元素个数是不同的,重力传感器总是返回一个长度为3的数组,分别代表X、Y和Z方向的数值。Z轴表示了手机是屏幕朝上还是屏幕朝下,一般不常用,我们主要关心X轴和Y轴的数值,以便能通过(x,y)定位小球在屏幕中的位置。通过重力传感器的X、Y值可以很容易地定位小球的位置:

  1. public class MainActivity extends Activity {     
  2.     private static final float MAX_ACCELEROMETER = 9.81f;     
  3.       
  4.     // x, y is between [-MAX_ACCELEROMETER, MAX_ACCELEROMETER]     
  5.     void moveTo(float x, float y) {     
  6.         int max_x = (container_width - ball_width) / 2;     
  7.         int max_y = (container_height - ball_height) / 2;     
  8.         int pixel_x = (int) (max_x * x / MAX_ACCELEROMETER + 0.5);     
  9.         int pixel_y = (int) (max_y * y / MAX_ACCELEROMETER + 0.5);     
  10.         translate(pixel_x, pixel_y);     
  11.     }     
  12.       
  13.     void translate(int pixelX, int pixelY) {     
  14.         int x = pixelX + container_width / 2 - ball_width / 2;     
  15.         int y = pixelY + container_height / 2 - ball_height / 2;     
  16.         ball.moveTo(x, y);     
  17.     }     
  18. }    

调用SensorManager的getDefaultSensor()就可以获得Sensor实例,这里,我们传入Sensor.TYPE_ACCELEROMETER,表示要获得重力传感器的实例。#p#
然后,我们需要向SensorManager对象注册一个SensorEventListener,这样,当Sensor变化时,我们就能获得通知:

  1. public class MainActivity extends Activity {     
  2.     SensorEventListener listener = new SensorEventListener() {     
  3.         public void onSensorChanged(SensorEvent e) {     
  4.             if (!init)     
  5.                 return;     
  6.             float x = e.values[SensorManager.DATA_X];     
  7.             float y = e.values[SensorManager.DATA_Y];     
  8.             float z = e.values[SensorManager.DATA_Z];     
  9.             prompt.setText("Sensor: " + x + ", " + y + ", " + z);     
  10.             moveTo(-x, y);     
  11.         }     
  12.       
  13.         public void onAccuracyChanged(Sensor s, int accuracy) {     
  14.         }     
  15.     };     
  16.       
  17.     void register() {     
  18.         sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME);     
  19. }     
  20.       
  21.     void unregister() {     
  22.         sensorManager.unregisterListener(listener);     
  23.     }     
  24. }    

需要注意的是,如何获得小球即BallView的大小,以及其容器FrameLayout的大小。在onCreate()方法中获取时我们发现,BallView和FrameLayout总是返回0,原因是OPhone系统在首次将UI组件绘制到屏幕之前,无法确定UI组件的具体大小,因此,getWidth()和getHeight()将返回0。那么,我们在何时才能获取UI组件的实际大小呢?答案仍然是第一次绘制UI组件时。由于第一次绘制UI组件会触发Focus事件,因此,我们可以响应onWindowFocusChanged()事件,在这里调用getWidth()和getHeight()能安全地返回UI组件的实际大小,因为此时Activity已绘制到手机屏幕。注意:布尔变量init用来保证仅第一次获得焦点时进行初始化:

  1. public class MainActivity extends Activity {     
  2.     boolean init = false;     
  3.     int container_width = 0;     
  4.     int container_height = 0;     
  5.     int ball_width = 0;     
  6.     int ball_height = 0;     
  7.       
  8.     @Override    
  9.     public void onWindowFocusChanged(boolean hasFocus) {     
  10.         super.onWindowFocusChanged(hasFocus);     
  11.         if (hasFocus && !init) {     
  12.             init();     
  13.             init = true;     
  14.         }     
  15.     }     
  16.       
  17.     void init() {     
  18.         View container = findViewById(R.id.ball_container);     
  19.         containercontainer_width = container.getWidth();     
  20.         containercontainer_height = container.getHeight();     
  21.         ball = (BallView) findViewById(R.id.ball);     
  22.         ballball_width = ball.getWidth();     
  23.         ballball_height = ball.getHeight();     
  24.         moveTo(0f, 0f);     
  25.     }     
  26. }    

此外,传感器也是手机的系统资源,在不必要的时候我们应当及时释放资源。我们需要在onStart()、onResume()和onRestart()事件中注册,在onPause()、onStop()和onDestroy()事件中取消注册:#p#

  1. public class MainActivity extends Activity {     
  2.     @Override    
  3.     protected void onStart() {     
  4.         super.onStart();     
  5.         register();     
  6.     }     
  7.       
  8.     @Override    
  9.     protected void onResume() {     
  10.         super.onResume();     
  11.         register();     
  12.     }     
  13.       
  14.     @Override    
  15.     protected void onRestart() {     
  16.         super.onRestart();     
  17.         register();     
  18.     }     
  19.       
  20.     @Override    
  21.     protected void onPause() {     
  22.         super.onPause();     
  23.         unregister();     
  24.     }     
  25.       
  26.     @Override    
  27.     protected void onStop() {     
  28.         super.onStop();     
  29.         unregister();     
  30.     }     
  31.       
  32.     @Override    
  33.     protected void onDestroy() {     
  34.         super.onDestroy();     
  35.         unregister();     
  36.     }     
  37. }    
  38.  
  39. public class MainActivity extends Activity { @Override protected void onStart() { super.onStart(); register(); } @Override protected void onResume() { super.onResume(); register(); } @Override protected void onRestart() { super.onRestart(); register(); } @Override protected void onPause() { super.onPause(); unregister(); } @Override protected void onStop() { super.onStop(); unregister(); } @Override protected void onDestroy() { super.onDestroy(); unregister(); } }  
  40.    

运行模拟器,运行效果如下:

 

由于模拟器无法模拟重力传感器,因此,这个应用程序需要在真机上才能看到实际效果,感兴趣的读者可以在真机上运行。
 
使用位置服务
位置服务是OPhone系统中另一种应用非常广泛的传感器。通过位置服务,开发基于位置的手机应用将为用户带来非常有价值的服务,如地图导航、餐厅搜索等等。
 
OPhone系统提供的基于位置的Location API可以提供GPS、AGPS和NETWORK三种模式的导航。其中,GPS是使用最广泛的卫星导航,我们可以利用GPS定位,开发出非常具有特色的手机应用。

下面,我们以一个具体的例子来演示如何使用位置服务。我们利用手机内置的GPS定位,通过Google地图显示当前手机用户所处的位置。

我们首先新建一个OPhone工程,命名为Location。Location API提供的主要接口是LocationManager和LocationListener。首先,我们需要在Activity的onCreate()事件中获取LocationManager的实例,并创建LocationListener实例:

  1. public class MainActivity extends Activity {     
  2.     private LocationManager locationManager;     
  3.     private LocationListener locationListener;     
  4.     
  5.     @Override    
  6.     public void onCreate(Bundle savedInstanceState) {     
  7.         super.onCreate(savedInstanceState);     
  8.         setContentView(R.layout.main);     
  9.         locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);     
  10.         locationListener = new LocationListener() {     
  11.             public void onLocationChanged(Location newLocation) {     
  12.                 MainActivity.this.onLocationChanged(newLocation);     
  13.             }     
  14.             public void onProviderDisabled(String provider) {     
  15.             }     
  16.              public void onProviderEnabled(String provider) {     
  17.             }     
  18.             public void onStatusChanged(String provider, int status, Bundle extras) {     
  19.             }     
  20.         };     
  21.     }     
  22.     
  23.     private void onLocationChanged(Location newLocation) {     
  24.     }     
  25. }    

和使用重力传感器类似,我们需要将LocationListener注册到LocationManager,因此,在onStart()、onRestart()和onResume()事件中注册,在onStop()和onDestroy()事件中取消注册:

  1. public class MainActivity extends Activity {     
  2.     @Override    
  3.     protected void onStart() {     
  4.         super.onStart();     
  5.         register();     
  6.     }     
  7.     
  8.     @Override    
  9.     protected void onRestart() {     
  10.         super.onRestart();     
  11.         register();     
  12.     }     
  13.     
  14.     @Override    
  15.     protected void onResume() {     
  16.         super.onResume();     
  17.         register();     
  18.     }     
  19.     
  20.     @Override    
  21.     protected void onStop() {     
  22.         super.onStop();     
  23.         unregister();     
  24.     }     
  25.     
  26.     @Override    
  27.     protected void onDestroy() {     
  28.         super.onDestroy();     
  29.         unregister();     
  30.     }     
  31.     
  32.     private void register() {     
  33.         locationManager.requestLocationUpdates(     
  34.                 LocationManager.GPS_PROVIDER,     
  35.                 10000L,     
  36.                 0,     
  37.                 locationListener     
  38.         );     
  39.     }     
  40.     
  41.     private void unregister() {     
  42.         locationManager.removeUpdates(locationListener);     
  43.     }     
  44. }    

注册是通过requestLocationUpdates()方法完成的,第一个参数指定了位置服务的提供者,这里是GPS_PROVIDER,第二个和第三个参数指定了发送位置更新的最小时间间隔和最小距离间隔。我们指定了发送位置更新的时间间隔不小于10秒,而最小距离不限。最后一个参数是LocationListener的实例。注册后,就可以在onLocationChanged()事件中获得当前的Location。OPhone系统传入一个Location对象,使用如下代码即获得当前位置的经度和纬度:

  1. double lat = newLocation.getLatitude();     
  2. double lng = newLocation.getLongitude();    

有了经度和纬度,我们就可以在Google地图中做出标记,让用户在地图上看到自己的当前位置。

Google API提供了MapView,可以直接显示Google地图,并方便地对其进行控制。而OPhone 1.5 SDK并不包含Google API,因此,我们就无法使用MapView了,怎么办?答案是自己动手,丰衣足食。MapView归根结底也是在WebView基础上封装而成的,我们完全可以在WebView中显示Google地图并对其进行控制。#p#

我们首先在XML布局中添加一个WebView:

  1. xml version="1.0" encoding="utf-8"?>     
  2. <FrameLayout xmlns:android=  
  3. "http://schemas.android.com/apk/res/android"    
  4.     android:layout_width="fill_parent"    
  5.     android:layout_height="fill_parent"    
  6. >      
  7.     <WebView     
  8.         android:id="@+android:id/webview"    
  9.         android:layout_width="fill_parent"    
  10.         android:layout_height="fill_parent"    
  11.     />     
  12. FrameLayout>    

WebView本质上就是浏览器,它和OPhone系统自带的浏览器完全一样。既然系统浏览器可以直接显示Google地图,那么,我们使用WebView也能显示Google地图。编写一个简单的HTML页面如下:

  1. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">     
  2. <html xmlns="http://www.w3.org/1999/xhtml">     
  3.     <head>     
  4.         <meta http-equiv="content-type" content="text/html; charset=utf-8"/>     
  5.         <title>Maptitle>     
  6.         <script src="http://ditu.google.cn/maps?hl=zh-CN&file=api&v=2&sensor=true&key=ABQIAAAANv4vRQVBvuMJA6tyhpEVYhT2yXp_ZAY8_ufC3CFXhHIE1NvwkxS5EvCTylQAqE2076RlFUaSV7w-gA" type="text/javascript">script>     
  7.         <script type="text/javascript">     
  8.             var g_map = null;     
  9.             var g_marker = null;     
  10.       
  11.             function getParam(_param) {     
  12.                 var query = location.search.substring(1);     
  13.                 var pairs = query.split("&");     
  14.                 for(var i=0;i<pairs.length;i++) {     
  15.                     var pos = pairs[i].indexOf("=");     
  16.                     if(pos==-1)     
  17.                         continue;     
  18.                     var argname=pairs[i].substring(0,pos);     
  19.                     if(argname==_param) {     
  20.                         var value=pairs[i].substring(pos+1).replace(/\+/g,' ');     
  21.                         return decodeURIComponent(value);     
  22.                     }     
  23.                }     
  24.                 return null;     
  25.             }     
  26.       
  27.             function initialize() {     
  28.                 d = document.getElementById("map_canvas");     
  29.                 sw = getParam("w");     
  30.                 sh = getParam("h");     
  31.                 if (sw!=null && sh!=null) {     
  32.                     w = parseInt(sw);     
  33.                     h = parseInt(sh);     
  34.                     d.style.width = w + "px";     
  35.                     d.style.height = h + "px";     
  36.                 }     
  37.                 lat = parseFloat(getParam("lat"));     
  38.                 lng = parseFloat(getParam("lng"));     
  39.                 map = new GMap2(d);     
  40.                 map.setCenter(new GLatLng(lat, lng), 14);     
  41.                 setMarker(lat, lng);     
  42.             }     
  43.       
  44.             function setMarker(lat, lng) {     
  45.                 if (g_marker!=null)     
  46.                     map.removeOverlay(g_marker);     
  47.                 ll = new GLatLng(lat, lng);     
  48.                 g_marker = new GMarker(ll);     
  49.                 map.addOverlay(g_marker);     
  50.                 map.panTo(ll);     
  51.             }     
  52.         script>     
  53.     head>     
  54.     <body onload="initialize()"      
  55.           onunload="GUnload()"    
  56.           style="margin: 0px; padding: 0px">     
  57.         <div id="map_canvas" style="width: 260px; height: 300px">div>     
  58.     body>     
  59. html>    

其中,导入Google地图是通过JavaScript完成的:

  1. <script src="http://ditu.google.cn/maps?...">script>  


为了控制地图标记的显示,我们编写了一个JavaScript函数:

  1. function setMarker(lat, lng) { ... }   

稍候我们会讲解如何调用这个JavaScript函数。
 
由于Google地图需要开发者申请一个Key才能使用,尽管申请Key是免费的,但是,不同的域名会对应不同的Key,为了简化应用程序的开发,我们直接使用localhost的Key,并通过如下代码将上面的HTML页面载入到WebView中,告诉WebView当前导航地址是http://localhost/map.html,这样,应用程序就无需再申请Key了:

  1. webView.loadDataWithBaseURL  
  2. ("http://localhost/map.html?lat=0&lng=0&w=" +   
  3. webView.getWidth() + "&h=" + webView.getHeight(), loadHtml(), "text/html", "UTF-8", null);   

从assets中读取文件内容的loadHtml()方法如下:

  1. String loadHtml() {     
  2.     InputStream input = null;     
  3.     try {     
  4.         input = getAssets().open("map.html");     
  5.         ByteArrayOutputStream result = new ByteArrayOutputStream(4096);     
  6.         byte[] buffer = new byte[1024];     
  7.         for (;;) {     
  8.             int n = input.read(buffer);     
  9.             if (n==(-1))     
  10.                 break;     
  11.             result.write(buffer, 0, n);     
  12.         }     
  13.         return result.toString("UTF-8");     
  14.     }     
  15.     catch (IOException e) {     
  16.         return "";     
  17.     }     
  18.     finally {     
  19.         if (input!=null) {     
  20.             try {     
  21.                 input.close();     
  22.             }     
  23.             catch (IOException e) {}     
  24.         }     
  25.     }     
  26. }    

这里需要注意的要点是,更新WebView需要在UI线程中进行,通过Handler.post()方法很容易实现,而调用JavaScript函数则通过loadUrl("javascript:函数名(参数)")就完成了,非常简单。

  1. void onLocationChanged(Location newLocation) {     
  2.     final double lat = newLocation.getLatitude();     
  3.     final double lng = newLocation.getLongitude();     
  4.     handler.post(     
  5.             new Runnable() {     
  6.                 public void run() {     
  7.                     webView.loadUrl  
  8. ("javascript:setMarker(" + lat + "," + lng + ")");     
  9.                 }     
  10.             }     
  11.     );     
  12. }    

运行代码,我们发现,调用该JavaScript函数不起作用,原因是WebView默认状态不启用JavaScript功能,因此,还需要在Activity的onCreate()中添加一点初始化代码,顺便将WebView的滚动条去掉:

  1. @Override    
  2. public void onCreate(Bundle savedInstanceState) {     
  3.     super.onCreate(savedInstanceState);     
  4.     setContentView(R.layout.main);     
  5.     webView = (WebView) findViewById(R.id.webview);     
  6.     webView.getSettings().setJavaScriptEnabled(true);     
  7.     webView.setVerticalScrollBarEnabled(false);     
  8.     webView.setHorizontalScrollBarEnabled(false);     
  9. }    

最后,不要忘记在AndroidManifest.xml中添加权限声明,我们需要网络访问权限和位置访问权限:

  1. <uses-permission android:name="android.permission.INTERNET" />     
  2. <uses-permission android:name=  
  3. "android.permission.ACCESS_FINE_LOCATION" /> 

运行模拟器,我们可以通过Emulator Control向模拟器发送经度和纬度数据,应用程序运行效果如下:

 

通过对assets资源的国际化,我们还可以在一个应用程序中针对中英文用户分别显示中文地图和英文地图:

 

在真机上运行该应用程序时,随着用户的移动,地图会自动跟踪并刷新用户的当前位置。感兴趣的读者可以在真机上运行。

责任编辑:chenqingxiang 来源: ophonesdn
相关推荐

2009-09-22 12:17:59

ibmdwLotus

2021-09-07 10:24:36

Vue应用程序Web Workers

2011-05-27 08:48:13

Android HTML

2013-10-09 11:15:49

Ubuntu应用程序

2009-06-19 13:45:53

Java应用程序Jfreechart

2009-11-23 19:52:55

ibmdwFlex

2022-08-30 20:00:37

零信任Linkerd

2023-11-24 09:37:05

Linux数据

2009-02-17 09:56:00

2010-03-16 10:00:24

无线传感器

2009-08-27 11:22:30

ibmdw云计算

2023-08-22 20:55:04

AzureLLMTypeChat

2009-11-20 16:04:40

网络路由协议

2010-03-16 10:27:32

无线传感器网络

2010-04-12 16:28:41

无线通信模块

2020-03-21 20:18:28

物联网Wi-Fi互联网

2023-08-28 16:49:08

物联网传感器

2021-08-20 13:32:45

传感器物联网智能音箱

2011-07-18 10:00:47

iPhone iOS Visual Stu

2010-11-30 15:44:27

Windows 7兼容
点赞
收藏

51CTO技术栈公众号