У меня реализована следующая assynctask. Его использование довольно простое, и поэтому работает так, как предполагалось. получить URL-адрес, опубликовать его, получить его содержимое, записать в файл. твердая часть начинается сейчасandroid async возвращаемый тип задачи и блокировка
ВОПРОС: Мне требуется повторное использование этого фрагмента кода несколько раз для нескольких разных файлов. Как передать файл как переменную в вызов assynctask вместе с URL?
//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());
}
}
EDIT: 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();
}
EDIT: Удалены второй вопрос, как это не имеет ничего общего с остальными и просто запутать людей, чтобы увидеть поток
Q1: может создать конструктор и передать необходимые значения ... [MORE] (http://stackoverflow.com/a/11335798/4577762) - Q2: Вы хотите какой-то спиннинг прогресса бар, пока он не закончит? [MORE] (http://stackoverflow.com/questions/18069678/how-to-use-asynctask-to-display-a-progress-bar-that-counts-down) - эта последняя ссылка, которую я не полностью проверил , Вам также нужно будет проверить все задачи. – FirstOne
Q1 я мог видеть, что он работает для моих потребностей со строкой атрибута и функцией набора, которая будет сводиться к тому же oucome. Попробуй следующую вещь завтра. Что касается Q2, то я не настолько суетлив к визуальной части, и я это соображу. Вопрос в том, как я могу дать основному потоку понять, что все звонки закончены, и он может продолжаться. – Elentriel