我有一个类,我用它从我的应用程序发送数据到一个网站。有多种方法迎合不同类型的数据,我想送,代码提取物在这里:数据库从AsyncTask更新onPostExecute
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类(送出数据),这与不能在运行的HttpURLConnection的东西交易mainUI线程,这里的部分代码:
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这种类型的功能。
谢谢,这是更有意义的,我打算将HTTP位移出一个新的类,但唯一的问题是,异步任务不在onPostExecute()方法中为您提供很大的灵活性,因为它仅用于UI更新。如果我有一个单独的HTTP和数据库操作类,我可以用onPostExecute()方法调用具有有效上下文的数据库类吗? – bazza2000
使用Handler/Thread类会更好吗? – bazza2000
*异步任务不会为onPostExecute()方法提供很大的灵活性,因为它只能用于UI更新*您可以在onPostExecute()方法中返回自定义对象,并且您可以灵活使用。您可以创建一个自定义的'HttpResponseObject'类,其中包含响应代码,失败细节以及您需要的任何内容。如果您需要额外的灵活性,可以在UI线程上返回并评估。这足够灵活吗? – gunar