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