我有一个类,我用它来将我的应用程序中的统计信息发送到网站。有多种方法可以满足我要发送的不同类型的数据,代码摘录在这里:
public class TransmitMetrics {
private final String request = "http://192.168.0.60/post.php";
private String function;
private URL url;
private HttpURLConnection connection;
private String line;
private String urlParameters;
public void updatePhone(String device_id, String country) {
String make = Build.MANUFACTURER;
String model = Build.MODEL;
String sdk = Build.VERSION.SDK;
function = "phoneupdate";
urlParameters = "function=" + function + "&device_id=" + device_id
+ "&make=" + make + "&model=" + model + "&country=" + country
+ "&sdk=" + sdk;
new sendData().execute();
}
然后我有一个嵌套的 AsyncTask 类(sendData),它处理不能在 mainUI 线程上运行的 HTTPURLConnection 东西,这里的部分代码:
private class sendData extends AsyncTask<Void, Void, Integer> {
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
//Proposed DB stuff here based on return code
//stored in the result variable.
}
@Override
protected Void doInBackground(Void... arg0) {
try {
url = new URL(request);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length",
"" + Integer.toString(urlParameters.getBytes().length));
connection.setUseCaches(false);
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
我对代码没有任何问题,它工作正常,但是,我最近一直在尝试通过添加依赖于从 HttpURLConnection 返回的响应代码的数据库更新来改进应用程序。
onPostExecute() 是标准方法,但我不确定是否应该开始声明数据库连接并从 onPostExecute() 方法中执行数据库更新。
如果有更好的方法可以做到这一点,或者我不应该首先使用 AsyncTask 来实现这种类型的功能,我想要一些建议。