我从很多主题研究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