2010-09-23 52 views
4

我正在开发一个android手机应用程序,它与json/rest web服务进行通信。我需要定期对服务器进行某些类型的调用以检查某些信息。 在这种情况下,我可能还需要查询GPS当前位置。我很难决定使用本地服务,因为我不太清楚如何处理它们,实际上我需要定期检索这些数据并相应刷新MapView。 我听说我可以在服务中使用PendingIntents,将这些数据作为有效载荷并将它们发送给解包数据并刷新UI的广播接收器,我还听说这是一种糟糕的设计方法,因为广播接收器旨在用于。 有没有人有一些有用的提示?设计方法:android和web服务

+0

我会用这个服务。 – fredley 2010-09-23 13:13:48

回答

2

首先你必须处理谷歌地图,因为你会显示一个地图视图。看看这个 Using Google Maps in Android on mobiForge

其次你需要一个提供gps数据的类。使用消息处理程序获取位置数据和更新UI非常简单。这里有一个例子:

public MyGPS implements LocationListener{ 

    public LocationManager lm = null; 
    private MainActivity SystemService = null; 
    //lat, lng 
    private double mLongitude = 0; 
    private double mLatitude = 0; 

    public MyGPS(MainActivity sservice){ 
     this.SystemService = sservice; 
     this.startLocationService(); 
    } 

    public void startLocationService(){ 
     this.lm = (LocationManager) this.SystemService.getSystemService(Context.LOCATION_SERVICE); 
     this.lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, this); 
    } 

    public void onLocationChanged(Location location) { 
     location = this.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
     try { 
      this.mLongitude = location.getLongitude(); 
      this.mLatitude = location.getLatitude(); 
     } catch (NullPointerException e) { 
      Log.i("Null pointer exception " + mLongitude + "," + mLatitude, null); 
     } 
    } 
} 

在你onCreate方法使这个类的一个实例和LocationListener的开始听的GPS更新。但是你不能访问lng和lat,因为你不知道你的活动是否被设置或为空。因此,你需要将消息发送到您的主活动时,纬度和经度设定的处理程序:

修改下面的方法:

public void onLocationChanged(Location location) { 
     location = this.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
     try { 
      this.mLongitude = location.getLongitude(); 
      this.mLatitude = location.getLatitude(); 
      Message msg = Message.obtain(); 
      msg.what = UPDATE_LOCATION; 
      this.SystemService.myViewUpdateHandler.sendMessage(msg); 
     } catch (NullPointerException e) { 
      Log.i("Null pointer exception " + mLongitude + "," + mLatitude, null); 
     } 
    } 

在您的主要活动补充一点:

Handler myViewUpdateHandler = new Handler(){ 

     public void handleMessage(Message msg) { 
       switch (msg.what) { 
       case UPDATE_LOCATION: 
       //access lat and lng 
     })); 
       } 

       super.handleMessage(msg); 
     } 
}; 

由于处理程序处于您的mapactivity中,因此您可以轻松地在处理程序本身中更新您的UI。每次gps数据都是可用的,处理程序触发并接收消息。

开发REST API是一件非常有趣的事情。一个简单的方法是在Web服务器上有一个php脚本,根据请求返回一些json数据。如果你想开发这样的服务,这个教程可能会帮助你,link

+0

谢谢。这有帮助!我所指的数据是其他用户(不同标准)与WS的位置的json表示。所以我只是想知道在哪里放置代码来创建http请求,这可能在这里,因为这是一个服务本身或者在一个不同的线程中。通过这种方式,只要我收到位置更新并且同时检索其他人(使用不同的处理程序进行UI更新),我就可以更新服务器上的位置。否则,这两个任务将在不同的线程中工作,但我不知道复杂程度。 – urobo 2010-09-23 14:58:16

+0

我找到了一个名为friend finder的应用程序,这里是教程,可能对你很有趣,http://www.anddev.org/viewtopic.php?t=93 – 2010-09-23 16:07:45