Проблема отображения загрузки файла в progressBar

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

Проблема отображения загрузки файла в progressBar

Сообщение Kronos1026 » 26 ноя 2015, 13:19

Добрый день, уважаемые пользователи форума, возникла такая проблема:
Есть class DownloadActivity extends ActionBarActivity на которой есть 1 прогресс бар, 3 кнопки (загрузка, просмотр, удаление), TextView (для вывода данных), SurfaceView для вывода видео. Есть мой класс class DownloadPlay, в котором я создал методы для загрузки файла и использую их в DownloadActivity. Что делает приложение - скачивает видеофайл, по кнопке скачать. по кнопке просмотр показывает видео. по кнопке удаления - останавливает воспроизведение и удаляет файл. Вопроса 2:
1 - почему при загрузке файла "виснет" приложение, не работают другие элементы интерфейса (AsyncTask вроде как должен его выполнять в отдельном потоке)
2 - как мне обновлять прогресс бар DownloadActivity из DownloadPlay в методе onPostExecute я не могу получить доступ к прогрессбару на DownloadActivity...?

Исходники:

activity_downlod.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.DownloadActivity">

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

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="download"
android:id="@+id/button6"
android:onClick="download_file"
android:layout_marginRight="30dp"
android:layout_below="@+id/progressBar"
android:layout_alignParentStart="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="view"
android:id="@+id/button7"
android:onClick="view_file"
android:layout_marginRight="30dp"
android:layout_below="@+id/button6"
android:layout_alignParentStart="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="delete"
android:id="@+id/button8"
android:onClick="delete_file"
android:layout_marginRight="30dp"
android:layout_below="@+id/button7"
android:layout_alignParentStart="true"
android:layout_marginTop="60dp" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/textView3"
android:layout_below="@+id/button8"
android:layout_alignParentStart="true" />

<SurfaceView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/surfaceView"
android:layout_below="@+id/textView3"
android:layout_alignParentStart="true"
android:layout_marginTop="55dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true" />

</RelativeLayout>
[/syntax]

DownloadActivity.java :

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

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.ExecutionException;

public class DownloadActivity extends ActionBarActivity {
TextView tInformation;
DownloadPlay my_file;
ProgressBar dfprogress;
String fileName = "reklama_armii_rf.mp4";
AudioManager am;
MediaPlayer mediaPlayer;
SurfaceView video;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
tInformation = (TextView)findViewById(R.id.textView3);
dfprogress = (ProgressBar)findViewById(R.id.progressBar);
am = (AudioManager) getSystemService(AUDIO_SERVICE);
video = (SurfaceView)findViewById(R.id.surfaceView);
}

public void download_file(View view) {
tInformation.setText("Ждем результатов...");
String download_file = "http://alexeypruglov.ru/reklama_armii_rf.mp4";
fileName = download_file.substring(download_file.lastIndexOf('/')+1, download_file.length());
my_file = new DownloadPlay();
my_file.DownloadFile(download_file, fileName);
tInformation.setText(fileName+" загружен");
}

public void view_file(View view) {
tInformation.setText("Открываю файл...");
dfprogress.setProgress(0);
File file = new File("/sdcard/"+fileName);
boolean exists = file.exists();
if (exists) {
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource("/sdcard/" + fileName);
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.setDisplay(video.getHolder());
mediaPlayer.start();
} else tInformation.setText("файл не найден");

}

public void delete_file(View view) {
tInformation.setText("Удаляю файл...");
dfprogress.setProgress(0);
mediaPlayer.stop();
File file = new File("/sdcard/"+fileName);
boolean file_delete = file.delete();
if (file_delete) tInformation.setText("файл удален");
else tInformation.setText("файл не удален");
}
}
[/syntax]

DownloadPlay.java :

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

import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.ProgressBar;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.ExecutionException;

/**
* Created by alexey on 26.11.2015.
*/
public class DownloadPlay {
public String DownloadFile(String url, String output_path){
String file_sdcard = "";
DownloadFileFromURL my_file;
my_file = new DownloadFileFromURL();
my_file.execute(url, output_path);
try {
file_sdcard = my_file.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return file_sdcard;
}

class DownloadFileFromURL extends AsyncTask<String, Integer, String> {
String file_sdcard = "";

//1 парам - урл для загрузки
//2 парам - имя выходного файла
@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));

// 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());
}

return null;
}

/**
* Updating progress bar
* */
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress[0]);
}

@Override
protected void onPostExecute(String file_sdcard) {
super.onPostExecute(file_sdcard);
}

}
}
[/syntax]

Ответить