java设置程序每五秒访问一下_java – 如何在android中每5秒调用一个方法?

Android应用:定时发送GPS位置到服务器
这篇博客介绍如何在Android应用中实现一个功能,即每5秒自动向服务器发送GPS位置信息。作者提到需要创建一个开关按钮来启动或停止这个定时任务,并提供了获取当前位置、更新变量以及通过HTTP POST请求将数据发送到服务器的代码片段。同时,文章还关注了电池效率,当开关关闭时会停止获取位置更新以节省电量。

我正在使用一个应用程序,当我选择时,它必须每隔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

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值