目前我有一个在按下按钮时将数据发送到服务器的类,我希望自动执行此服务,以便它每 4 小时将数据发送到服务器而无需按下按钮。 POST 服务目前正在后台运行,有什么指点吗??我是否必须实现一个计时器,不知道它超出了我的领域??提前致谢!!
Button btnCreateUser = (Button) findViewById(R.id.btnSend);
// button click event
btnCreateUser.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// creating new product in background thread
new CreateNewUser().execute();
}
});
}
class CreateNewUser extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... args) {
String lat=latitude, lng=longitude;
SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
String newtime = sdfDateTime.format(new Date(System.currentTimeMillis()));
EditText username = (EditText) findViewById(R.id.myText);
String newString= (String)username.getText().toString();
String created_at=newtime;
String timezone="UTC";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_create_user);
String responseBody = "";
HttpResponse response = null;
try {
String base64EncodedCredentials = "Basic " + Base64.encodeToString(
(username + ":" + created_at +":"+timezone+":"+lat+":"+lng).getBytes(),
Base64.NO_WRAP);
httppost.setHeader("Authorization", base64EncodedCredentials);
httppost.setHeader(HTTP.CONTENT_TYPE,"application/json");
JSONObject obj = new JSONObject();
obj.put("username", String.valueOf(newString));
obj.put("created_at",String.valueOf(newtime));
obj.put("timezone", String.valueOf(timezone));
obj.put("lat", String.valueOf(latitude));
obj.put("lng", String.valueOf(longitude));
httppost.setEntity(new StringEntity(obj.toString(), "UTF-8"));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == 200) {
Log.d("response ok", "Reached Server ok");
startActivity(new Intent("com.xxxxx.CLEARSCREEN"));
} else {
Log.d("response not ok", "Something went wrong :/");
}
responseBody = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
return responseBody;
}
最佳答案
你可以通过这段代码解决它:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
btnCreateUser.post(new Runnable() {
@Override
public void run() {
btnCreateUser .performClick();
}
});
}
}, 0, 14400); // for 4 hours
关于Android 无需按下按钮即可将 Gps 数据发送到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25060024/