[英]How can I invoke a method every 5 seconds in android?
我正在使用一个应用程序,当我选择(自动发送按钮打开)时,该应用程序必须每5秒向服务器发送一次GPS位置。 我是android的新手,所以我不知道如何制作开/关按钮,以及如何在打开按钮时调用每5秒发送一次数据的方法。
它必须每5秒调用一次的方法:
public void postData() throws ClientProtocolException, IOException, Exception {
String longitude="UK";
String latitude="UK";
String altitiude="UK";
String time="";
String speed="";
getCurrentLocation(); // gets the current location and update mobileLocation variables
if (mobileLocation != null) {
locManager.removeUpdates(locListener); // This needs to stop getting the location data and save the battery power.
longitude = ""+mobileLocation.getLongitude();
latitude = "" + mobileLocation.getLatitude();
altitiude = "" + mobileLocation.getAltitude();
String accuracy = "Accuracy" + mobileLocation.getAccuracy();
time = "" + mobileLocation.getTime();
speed =""+ (int)(4*mobileLocation.getSpeed());
editTextShowLocation.setText(longitude + "\n" + latitude + "\n"
+ altitiude + "\n" + accuracy + "\n" + time+ "\n" + speed);
} else {
editTextShowLocation.setText("Sorry, location is not determined");
}
String url = "http://www.itrack.somee.com/post.aspx?id="+"f1"+"&long="+longitude+"&lat="+latitude+"&alt="+altitiude+"&speed="+speed;
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
我遇到了完全相同的问题,需要定期发送位置信息。 我使用了处理程序及其postDelayed
方法。
我的代码的定期调用部分如下所示:
private final int FIVE_SECONDS = 5000;
public void scheduleSendLocation() {
handler.postDelayed(new Runnable() {
public void run() {
sendLocation(); // this method will contain your almost-finished HTTP calls
handler.postDelayed(this, FIVE_SECONDS);
}
}, FIVE_SECONDS);
}
然后,当您要开始scheduleSendLocation
呼叫时,只需要调用scheduleSendLocation
即可。
Ridcully是正确的,可能没有理由每5秒发送一次当前位置。 这是其背后的原因:
您实际上只关心用户位置的两件事:
他们现在在哪里?
自从我到达第一个位置以来,他们有没有搬家?
因此,一旦您获得满意的初始位置,就可以在用户移动时进行注册以获取回调,如下所示:
private LocationListener mLocationListener;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
updateLocation(location);
}
@Override
public void onStatusChanged(final String provider,
final int status, final Bundle extras) {
}
@Override
public void onProviderEnabled(final String provider) {
}
@Override
public void onProviderDisabled(final String provider) {
}
};
}
话虽如此,您显然可以执行其他人所说的,并每5秒运行一次计时器。 问题是,大多数好的位置都需要10到20秒才能运行,因此您可能只想在此间隔内运行它。 仅供参考,这会杀死电池
查看AlarmManager类http://developer.android.com/reference/android/app/AlarmManager.html ,尤其是setRepeating函数。 它会比您想要的复杂一些。
您可以使用Timer
。 但是我认为,如果只发送其位置与上次发送的位置相距一定距离,会更好。 这样,您可以发送更少的数据而不会丢失任何信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.