我正在尝试创建一个应用程序,在x分钟后将一些数据发送到网络服务器。我被告知警报管理器是最好的解决方案,只需在警报内额外拨打x分钟即可调用相同的警报功能,以便即使在后台也能不断发送数据。
但是我只看到了项目中的警报打开意图。这是否意味着它将在x分钟后切换到新意图,或者一切都在后台运行?
应该发送后台数据而不必在意图之间切换,所以我希望它只是在我的一个活动中调用一个函数。我应该怎么做呢?
这是我想每隔x分钟拨打一次的功能。
由于
public class updateloc extends AsyncTask<Void, Void, Void> {
protected void onPostExecute(String response) {
if (response != null) {
// check if this does anything later
}
progressDialog.dismiss();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(ImTracking.this, "",
"Updating Data...");
}
@Override
protected Void doInBackground(Void... arg0) {
SharedPreferences prefs = getSharedPreferences("Settings", 0);
final String id = prefs.getString("ID", "");
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(
"http://iphone-radar.com/gps/gps_locations");
JSONObject holder = new JSONObject();
try {
holder.put("id", id);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String bestProvider = locationManager.getBestProvider(criteria,
false);
LocationListener loc_listener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
};
try {
Looper.prepare();
locationManager.requestLocationUpdates(bestProvider, 0, 0,
loc_listener);
} catch (Exception e) {
e.printStackTrace();
}
Location location = locationManager
.getLastKnownLocation(bestProvider);
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(
"hh:mmaa MM/dd/yyyy");
holder.put("time", sdf.format(c.getTime()));
holder.put("time_since_epoch", System.currentTimeMillis());
try {
holder.put("lat", location.getLatitude());
holder.put("lon", location.getLongitude());
} catch (NullPointerException e) {
try {
holder.put("lat", -1.0);
holder.put("lon", -1.0);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
StringEntity se = new StringEntity(holder.toString());
httpost.setEntity(se);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
ResponseHandler responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httpost, responseHandler);
org.json.JSONObject obj;
obj = new org.json.JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
progressDialog.dismiss();
return null;
}
}
答案 0 :(得分:1)
如果您希望在后台运行此功能,则需要创建服务。可以使用意图启动服务,因此您可以使用AlarmManager启动服务。看看IntentService,您只需要在servcie的AsyncTask
方法中移动handleIntent()
中当前正在执行的操作。