我从这里的许多线程中研究了在Android OS中获取位置信息,并尝试了一些设计。但是,我每次都会大量耗电,只是无法摆脱它。这是我的代码的一部分。
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)。
如何实施更好的设计?有什么建议吗?
答案 0 :(得分:0)
LocationManager.requestLocationUpdates上的字段minInterval需要一毫秒的时间。你正在通过600,这将导致经理每600毫秒或基本上尽可能快地开火。我想你在那里错过了一个* 1000。