我從很多主題研究Android操作系統獲取位置信息,並嘗試了一些設計。但是,我每次都耗費大量電量,無法擺脫它。這是我的代碼的一部分。ANDROID在後臺獲取網絡位置
LocationReceiver.Java
public class LocationReceiver extends BroadcastReceiver {
public static double latestUpdate = 0;
public static int status = 0;
public static int count_upload = 0;
public static int count_ignored = 0;
public static Geocoder gc;
public void onReceive(Context context, Intent intent) {
// Do this when the system sends the intent
Bundle b = intent.getExtras();
Location loc = (Location) b
.get(android.location.LocationManager.KEY_LOCATION_CHANGED);
if (loc == null)
return;
if (gc == null)
gc = new Geocoder(context);
update(loc, context);
}
public void update(Location loc, Context context) {
// Here I am checking if 10 minutes passed from last update to now.
// and if so, I am uploading my location to my server.
if (latestUpdate != 0
&& latestUpdate + ((LaunchReceiver.interval - 2) * 1000) > SystemClock
.elapsedRealtime()) {
// duplicate (ignore)
count_ignored++;
} else {
// Upload to server on an async task.
// ...
LocationReceiver.latestUpdate = SystemClock.elapsedRealtime();
count_upload++;
}
}
}
LaunchReceiver.Java
public class LaunchReceiver extends BroadcastReceiver {
public static boolean registered = false;
public static LocationManager lm;
public static int interval = 600000;
public static PendingIntent pendingIntent;
SharedPreferences sharedPrefs = null;
@Override
public void onReceive(Context context, Intent intent) {
if (registered)
return;
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
interval = Integer.parseInt(sharedPrefs.getString("updates_interval",
"600000"));
Intent in = new Intent("bdd.sanalmusavir.LOCATION_READY");
pendingIntent = PendingIntent.getBroadcast(context, 0, in,
PendingIntent.FLAG_UPDATE_CURRENT);
lm = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
// Register for broadcast intents
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, interval,
0, pendingIntent);
registered = true;
}
}
AndroidManifest.xml中
<application
<receiver
android:name=".LaunchReceiver"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<receiver android:name=".LocationReceiver" >
<intent-filter>
<action android:name="bdd.sanalmusavir.LOCATION_READY" />
</intent-filter>
</receiver>
</application>
當然,這只是我的代碼部分。我通過週期性地添加警報來嘗試與服務相同的事情,但也導致電池耗盡。在這個練習中,我們假設我將間隔設置爲10分鐘,並且當我註冊位置更新(requestLocationUpdates)時,我正在獲取位置更新隨機間隔(每隔30秒左右)。我怎樣才能擺脫它?檢查10分鐘是否通過並上傳到服務器有什麼問題?
當我在1天后檢查count_ignored和count_uploaded時,忽略計數爲2100〜,上傳計數爲50〜(上傳計數爲真)。我的應用程序使用了90分鐘的CPU,這是不可接受的。 (上傳應用程序的一部分只是使用HttpRequest在Web上調用URL)。
如何實現更好的設計?有什麼建議麼?
這只是爲了測試目的。對不起忘了在我的帖子上提到它。我從我的偏好是600 * 1000使用它。修復了我的帖子。 – EvanBlack 2012-02-03 08:12:00