0
我有以下assynctask实施。它的使用非常简单,并且按照预期工作。获取一个url,发布到它,获取它的内容,将它们写入一个文件。困难的部分现在开始android异步任务返回类型和锁定
问题: 我需要多次重复使用这段代码多个不同的文件。如何将文件作为变量传递给url的assynctask调用?
//class to call a url and save it to a local file
private class url_to_file extends AsyncTask<String, Integer, String> {
protected String[] doInBackground(String... input) {
//function to call url and postback contents
return callpost(input[0]);
}
protected void onProgressUpdate(Integer... progress) {
//Yet to code
}
protected void onPostExecute(String result) {
//function to write content to text file
writeStringAsFile(result, "file.xml" ,getApplicationContext());
}
}
编辑: Purelly作为参考,我用它来读取,从文件和呼叫URL写函数
//saves a txt (etc, xml as well) file to directory,replacing previous. if directory is left empty, save to assets
public static void writeStringAsFile(final String fileContents, String fileName ,Context context) {
try {
FileWriter out = new FileWriter(new File(context.getFilesDir(), fileName));
out.write(fileContents);
out.close();
} catch (IOException e) {
}
}
//read file, returns its contents
public static String readFileAsString(String fileName,Context context) {
StringBuilder stringBuilder = new StringBuilder();
String line;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName)));
while ((line = in.readLine()) != null) stringBuilder.append(line);
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
return stringBuilder.toString();
}
//calls a page. Returns its contents
public String callpost (String... strings)
{
StringBuilder content = new StringBuilder();
try
{
// create a url object
URL url = new URL(strings[0]);
// create a urlconnection object
URLConnection urlConnection = url.openConnection();
// wrap the urlconnection in a bufferedreader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
// read from the urlconnection via the bufferedreader
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return content.toString();
}
编辑: 删除第二个问题,因为它没有任何关系,其余的和会搞乱人们看到了线程
Q1:也许创建一个构造函数和传递需要的值... [详细](http://stackoverflow.com/a/11335798/4577762) - Q2:你想要某种甩干过程酒吧,直到它完成? [更多](http://stackoverflow.com/questions/18069678/how-to-use-asynctask-to-display-a-progress-bar-that-counts-down) - 这最后一个链接,我没有完全检查。你还需要检查所有的任务。 – FirstOne
Q1我可以看到它为我的需要工作,字符串属性和设置功能将归结为相同的成就。将尝试接下来的事情。至于第二季度,我对这个视觉部分并不那么挑剔,我会弄清楚。问题是我怎么能让主线程了解所有的通话都已完成,并且可以继续。 – Elentriel