2013-04-20 139 views
2

我有一個Android應用程序,基本上想跟蹤用戶的整個一天的運動,並每週向他們報告一些趨勢。我最初認爲,只要用戶具有位置服務和/或GPS功能,系統總是試圖保持用戶的位置是最新的。但是,在閱讀Location Strategies的文章後,我意識到情況並非如此。以短間隔或長時間間隔長間隔請求位置更新是否更好?

看起來,即使用戶已經選中位置服務或GPS的方框,接收方只會在應用程序調用requestLocationUpdates後真正嘗試確定設備的位置,並且將繼續這樣做,直到調用removeUpdates 。 (如果這不正確,請告訴我)。

由於我的應用程序真的只需要設備運動的「粗略」概念,因此我一直在考慮每五分鐘左右記錄一次設備的位置。但是,這篇文章中的例子都沒有描述這種應用。這兩個例子都是關於確定設備在特定時間點的位置,而不是試圖「跟隨」設備:標記用戶創建的內容與其創建的位置並找到附近的興趣點。

我的問題是,讓我的應用程序每五分鐘「喚醒」一次,然後使用文章中的技術之一確定設備的當前位置會更有效率(通過開始聆聽,確定最佳樣本,停止收聽,然後回到睡眠狀態),還是最好開始收聽更新,並在五分鐘更新之間給出最短時間並且永不停止收聽?

回答

0

即使您的應用程序不可見,也可以定期使用BroastcastReceiver獲取新位置。不要使用服務,它可能會被殺死。

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(MyLocationBroadcastReceiver.action), 0); 
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5 * 60 * 1000, 100, pendingIntent); 
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5 * 60 * 1000, 100, pendingIntent); 
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, pendingIntent); 

不要忘記將操作字符串添加到manifest.xml,並在其中添加ACCESS_FINE_LOCATION權限(對於GPS)。如果您不需要GPS,請使用ACCESS_COARSE_LOCATION。

<receiver android:name="MyLocationBroadcastReceiver" android:process=":myLocationBroadcastReceiver" > 
    <intent-filter> 
     <action android:name="Hello.World.BroadcastReceiver.LOCATION_CHANGED" /> 
    </intent-filter> 
</receiver> 
<uses-permission android:name="android.permission.GET_ACCOUNTS" /> 

在BroastcastReceiver.onReceive()中,您必須理清所得到的結果。我扔掉新位置的距離比以前的位置少,而不是新的準確度。如果他們的準確度比前一個更差,我也會扔掉「最近」的位置。精度高於100米的GPS定位通常毫無價值。您必須將位置存儲在文件或首選項中,因爲您的BroastcastReceiver對象在onReceive()調用之間不存在。

public class MyLocationBroadcastReceiver extends BroadcastReceiver 
{ 
    static public final String action = "Hello.World.BroadcastReceiver.LOCATION_CHANGED"; 

    public void onReceive(Context context, Intent intent) 
    { 
     Location location = (Location) intent.getExtras().get(LocationManager.KEY_LOCATION_CHANGED); 
     if (location == null) 
     { 
      return; 
     } 

     // your strategies here 
    } 
}