Выполнение фоновых процессов на android

Activity Lifecycle, Saving Activity State, Managing Tasks, Intent, Intent Filter
Ответить
Kronos1026
Сообщения: 2
Зарегистрирован: 26 ноя 2015, 13:00

Выполнение фоновых процессов на android

Сообщение Kronos1026 » 30 ноя 2015, 16:09

Добрый день, уважаемые пользователи, вопрос:
Есть 2 активности MainActivity и ProgressbarActivity? на MainActivity находится кнопка для перехода на ProgressbarActivity. На ProgressbarActivity находится кнопка для загрузки файла из интернета и прогрессбар для отображения процесса загрузки файла, загрузка файла выполняется через AsyncTask. Когда я нахожусь на ProgressbarActivityто все прекрасно работает, но если загрузка файла не завершена и перейти на MainActivity, то загрузка файла прерывается. Как реализовать механизм загрузки файла таким образом чтобы неважно какая активность открыта загрузка все равно идет, но если открыта активность ProgressbarActivity, то прогресс выполнения загрузки файла выводился бы в его прогресс бар?

activity_main.xml
[syntax=xml]<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.alexey.tvclub4.MainActivity">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="json"
android:id="@+id/button1"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:onClick="chanche_activity_to_json" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="download file"
android:id="@+id/button2"
android:layout_below="@+id/button1"
android:layout_alignParentStart="true"
android:onClick="chanche_activity_to_downloadfile" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="sqlite"
android:id="@+id/button3"
android:layout_below="@+id/button2"
android:layout_alignParentStart="true"
android:onClick="chanche_activity_to_sqlite" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Progress bar"
android:id="@+id/button15"
android:layout_below="@+id/button3"
android:layout_alignParentStart="true"
android:nestedScrollingEnabled="false"
android:onClick="chanche_activity_to_progress_bar" />
</RelativeLayout>
[/syntax]

activity_progressbar.xml
[syntax=xml]<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.alexey.tvclub4.ProgressbarActivity">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Загрузить файл"
android:id="@+id/button16"
android:layout_below="@+id/progressBar2"
android:layout_alignParentStart="true"
android:onClick="download_file" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Удалить файл"
android:id="@+id/button17"
android:layout_below="@+id/button16"
android:layout_alignParentStart="true"
android:onClick="delete_file" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Проверить наличие файла"
android:id="@+id/button18"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:onClick="check_exist_file" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Получить хеш"
android:id="@+id/button19"
android:layout_above="@+id/button18"
android:layout_alignParentEnd="true"
android:onClick="get_hash" />

<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progressBar2"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="@+id/textView4"
android:layout_below="@+id/button17"
android:layout_alignParentStart="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/textView5"
android:layout_below="@+id/progressBar2"
android:layout_alignParentEnd="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="на главную"
android:id="@+id/button20"
android:layout_below="@+id/textView5"
android:layout_alignParentEnd="true"
android:onClick="chanche_activity_to_main" />

</RelativeLayout>
[/syntax]

MainActivity.class
[syntax=java]package com.example.alexey.tvclub4;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void chanche_activity_to_json(View view) {
Intent intent = new Intent(this, JsonActivity.class);
startActivity(intent);
}

public void chanche_activity_to_downloadfile(View view) {
Intent intent = new Intent(this, DownloadActivity.class);
startActivity(intent);
}

public void chanche_activity_to_sqlite(View view) {
Intent intent = new Intent(this, SqliteActivity.class);
startActivity(intent);
}

public void chanche_activity_to_progress_bar(View view) {
Intent intent = new Intent(this, ProgressbarActivity.class);
startActivity(intent);
}
}
[/syntax]

ProgressbarActivity.class
[syntax=java]package com.example.alexey.tvclub4;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.ExecutionException;

public class ProgressbarActivity extends ActionBarActivity {
Button bDownloadFile, bDeleteFile;
ProgressBar vProgressDownload;
TextView tOutput, tProgressPercent;
String fileName = "reklama_armii_rf.mp4";
//String filemd5 = "5E5EE089033672052B3DC5386C7453C9";
//String filemd5 = "2a1f6694843f1243557e0b934f4244b3";
String filemd5 = "5e5ee089033672052b3dc5386c7453c9";
//максимальное количество попыток загрузить файл
int counter = 5;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progressbar);
bDownloadFile = (Button) findViewById(R.id.button16);
bDeleteFile = (Button) findViewById(R.id.button17);
vProgressDownload = (ProgressBar) findViewById(R.id.progressBar2);
tOutput = (TextView) findViewById(R.id.textView4);
tProgressPercent = (TextView) findViewById(R.id.textView5);
new File("/sdcard/tvclub").mkdirs();
}

public void download_file(View view) {
tOutput.setText("Начинаю загрузку файла.");
counter = 10;
downloading_file();
//BackgroundAsyncTask start_progress = new BackgroundAsyncTask();
//start_progress.execute();
//количество попыток скачки файла
/*BackgroundAsyncTask download_file = new BackgroundAsyncTask();
tOutput.setText("Начинаю загрузку файла.");
int counter = 10;
String current_hash = "";
String url = "http://alexeypruglov.ru/reklama_armii_rf.mp4";
String output_path = url.substring(url.lastIndexOf('/')+1, url.length());


do {
download_file.execute(url, output_path);
bDownloadFile.setClickable(false);
bDownloadFile.setEnabled(false);
bDeleteFile.setClickable(false);
bDeleteFile.setEnabled(false);
tOutput.setText(tOutput.getText().toString() + "\n" + "Процесс проверки HASH файла.");
File file = new File("/sdcard/"+fileName);
boolean exists = file.exists();
if (exists) {
try {
current_hash = download_file.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}

if (filemd5.equals(current_hash)) {
tOutput.setText(tOutput.getText().toString() + "\n" + "Хеш суммы совпадают");
} else {
tOutput.setText(tOutput.getText().toString() + "\n" + "Хеш суммы не совпадают!");
}
} else {
tOutput.setText(tOutput.getText().toString() + "\n" + "Файл не найден!");
}

counter--;
} while (counter > 0 || filemd5.equals(current_hash));*/

/*String current_hash = "";
tOutput.setText("Процесс проверки HASH файла.");
File file = new File("/sdcard/"+fileName);
boolean exists = file.exists();
if (exists) {
try {
current_hash = GetHash("/sdcard/"+fileName);
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
tOutput.setText(tOutput.getText().toString() + "\n" + "Текущих хеш: " + current_hash);
tOutput.setText(tOutput.getText().toString() + "\n" + "Необходимый хеш: " + filemd5);
if (filemd5.equals(current_hash)) {
tOutput.setText(tOutput.getText().toString() + "\n" + "Хеш суммы совпадают");
} else {
tOutput.setText(tOutput.getText().toString() + "\n" + "Хеш суммы не совпадают!");
}
} else {
tOutput.setText(tOutput.getText().toString() + "\n" + "Файл не найден!");
}*/
}

public void downloading_file(){
BackgroundAsyncTask download_file = new BackgroundAsyncTask();
String current_hash = "";
String url = "http://alexeypruglov.ru/reklama_armii_rf.mp4";
String output_path = url.substring(url.lastIndexOf('/')+1, url.length());
boolean start_dow = false;
counter--;

try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}

if (counter > 0) {
//tOutput.setText(tOutput.getText().toString() + "\n" + "Процесс проверки HASH файла.");
File file = new File("/sdcard/" + fileName);
boolean exists = file.exists();
if (exists) {
try {
current_hash = GetHash("/sdcard/" + fileName);
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
tOutput.setText(tOutput.getText().toString() + "\n" + filemd5 + "\n" + current_hash);
if (filemd5.equals(current_hash)) {
tOutput.setText(tOutput.getText().toString() + "\n" + "Хеш суммы совпадают");
} else {
tOutput.setText(tOutput.getText().toString() + "\n" + "Хеш суммы не совпадают!");

start_dow = true;
boolean file_delete = file.delete();
if (file_delete) tOutput.setText(tOutput.getText().toString() + "\n" + "файл удален )");
else tOutput.setText(tOutput.getText().toString() + "\n" + "Ошибка: файл не удален!");
}
} else {
tOutput.setText(tOutput.getText().toString() + "\n" + "Файл не найден!");
start_dow = true;
}

if (start_dow) {
tOutput.setText(tOutput.getText().toString() + "\n" + "Начат процесс загрузки файла.");
download_file.execute(url, output_path);
bDownloadFile.setClickable(false);
bDownloadFile.setEnabled(false);
bDeleteFile.setClickable(false);
bDeleteFile.setEnabled(false);
}
} else {
tOutput.setText(tOutput.getText().toString() + "\n" + "Превышен лимит загрузок фала.");
}

}

public void delete_file(View view) {
tOutput.setText("Процесс удаления запущен.");
vProgressDownload.setProgress(0);
File file = new File("/sdcard/"+fileName);
boolean exists = file.exists();
if (exists) {
tOutput.setText(tOutput.getText().toString() + "\n" + "Файл найден, пытаюсь удалить...");
boolean file_delete = file.delete();
if (file_delete) tOutput.setText(tOutput.getText().toString() + "\n" + "файл удален )");
else tOutput.setText(tOutput.getText().toString() + "\n" + "Ошибка: файл не удален!");
} else {
tOutput.setText(tOutput.getText().toString() + "\n" + "Ошибка: файл не найден!");
}

}

public void check_exist_file(View view) {
tOutput.setText("Процесс проверки наличия файла.");
File file = new File("/sdcard/"+fileName);
boolean exists = file.exists();
if (exists) {
tOutput.setText(tOutput.getText().toString() + "\n" + "Файл найден");
} else {
tOutput.setText(tOutput.getText().toString() + "\n" + "Файл не найден!");
}
}

public void get_hash(View view) {
String current_hash = "";
tOutput.setText("Процесс проверки HASH файла.");
File file = new File("/sdcard/"+fileName);
boolean exists = file.exists();
if (exists) {
try {
current_hash = GetHash("/sdcard/"+fileName);
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
tOutput.setText(tOutput.getText().toString() + "\n" + "Текущих хеш: " + current_hash);
tOutput.setText(tOutput.getText().toString() + "\n" + "Необходимый хеш: " + filemd5);
if (filemd5.equals(current_hash)) {
tOutput.setText(tOutput.getText().toString() + "\n" + "Хеш суммы совпадают");
} else {
tOutput.setText(tOutput.getText().toString() + "\n" + "Хеш суммы не совпадают!");
}
} else {
tOutput.setText(tOutput.getText().toString() + "\n" + "Файл не найден!");
}
}

static String GetHash(String fileName) throws IOException, NoSuchAlgorithmException
{
MessageDigest md = MessageDigest.getInstance("MD5");
FileInputStream fis = new FileInputStream(fileName);

byte[] dataBytes = new byte[1024];

int nread = 0;
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
};
byte[] mdbytes = md.digest();

//convert the byte to hex format
StringBuffer sb = new StringBuffer();
for (int i = 0; i < mdbytes.length; i++) {
sb.append(Integer.toString((mdbytes & 0xff) + 0x100, 16).substring(1));
}

fis.close();
return sb.toString();
}

public void chanche_activity_to_main(View view) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}


public class BackgroundAsyncTask extends AsyncTask<String, Integer, String> {
int myProgress;
String file_sdcard = "";

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
//Toast.makeText(AndroidAsyncTaskProgressBar.this, "onPostExecute", Toast.LENGTH_LONG).show();
bDownloadFile.setClickable(true);
bDownloadFile.setEnabled(true);
bDeleteFile.setClickable(true);
bDeleteFile.setEnabled(true);
tProgressPercent.setText("100%");
vProgressDownload.setProgress(100);
tOutput.setText(tOutput.getText().toString() + "\n" + "Процесс загрузки завершился.");
downloading_file();
}

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
//Toast.makeText(AndroidAsyncTaskProgressBar.this, "onPreExecute", Toast.LENGTH_LONG).show();
myProgress = 0;
}

/*@Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
while(myProgress<100){
myProgress++;
publishProgress(myProgress);
SystemClock.sleep(100);
}
return null;
}*/

@Override
protected String doInBackground(String... info_file) {
int count;
try {
URL url = new URL(info_file[0].toString());
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();

// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);

// Output stream to write file
file_sdcard = "/sdcard/"+info_file[1].toString();
OutputStream output = new FileOutputStream(file_sdcard);

byte data[] = new byte[1024];

long total = 0;

while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress((int)((total*100)/lenghtOfFile));
//(ProgressBar)findViewById(R.id.info_file[2]).setProgress(""+(int)((total*100)/lenghtOfFile));


// writing data to file
output.write(data, 0, count);
}

// flushing output
output.flush();

// closing streams
output.close();
input.close();

} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
String current_hash = "";
try {
current_hash = GetHash("/sdcard/"+fileName);
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return current_hash;
}

@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
vProgressDownload.setProgress(values[0]);
tProgressPercent.setText(values[0].toString() + "%");
}

}
}
[/syntax]

Скриншот MainActivity
скрин MainActivity
скрин MainActivity
device-mainactivity.png (26.62 КБ) 2021 просмотр
Скриншот ProgressbarActivity
Скрин ProgressbarActivity
Скрин ProgressbarActivity
device-progressbaractivity.png (59.03 КБ) 2021 просмотр

Аватара пользователя
klblk
Сообщения: 1097
Зарегистрирован: 18 окт 2012, 11:17
Откуда: г. Красноярск

Re: Выполнение фоновых процессов на android

Сообщение klblk » 01 дек 2015, 05:44

Загрузку выполнять в сервисе

Ответить