Загрузка видео переднего плана в Android очень медленнаяAndroid

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 Загрузка видео переднего плана в Android очень медленная

Сообщение Anonymous »

Я хочу загрузить фрагменты видео на переднем плане, но по какой-то причине загрузка идет медленно, например: чтобы загрузить 100 МБ, моему телефону требуется около 1 минуты. В Netflix загрузка 230 МБ занимает менее 2 секунд. Это не проблема производительности сети, потому что это локальная сеть. Есть ли лучший способ сделать это, или в моем коде ошибка?
Спасибо.
package pt.spacelabs.experience.epictv.utils;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import androidx.annotation.Nullable;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import pt.spacelabs.experience.epictv.R;

public class BackgroundDownload extends Service {

private static final String CHANNEL_ID = "Transferências";
private static final int NOTIFICATION_ID = 1001;
private Notification.Builder notificationBuilder;
private NotificationManager notificationManager;
private ExecutorService executorService;

private long totalBytesToDownload = 0;
private long totalDownloadedBytes = 0;
private final Object lock = new Object();

@Override
public void onCreate() {
super.onCreate();
int availableProcessors = Runtime.getRuntime().availableProcessors();
executorService = Executors.newFixedThreadPool(availableProcessors * 2);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
createNotificationChannel();
initializeNotification();

String[] fileUrls = {
"data00.ts", "data01.ts", "data02.ts", .... more chunks, "stream_0.m3u8" };

if (fileUrls != null && fileUrls.length > 0) {
calculateTotalBytes(fileUrls);

for (String url : fileUrls) {
executorService.submit(() -> downloadFile("https://vis-ipv-cda.epictv.spacelabs.pt ... /stream_0/" + url));
}
}

return START_STICKY;
}

private void calculateTotalBytes(String[] fileUrls) {
executorService.submit(() -> {
for (String url : fileUrls) {
try {
URL fileUrl = new URL("https://vis-ipv-cda.epictv.spacelabs.pt ... /stream_0/" + url);
HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection();
connection.setRequestMethod("HEAD");
totalBytesToDownload += connection.getContentLength();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"Download Channel",
NotificationManager.IMPORTANCE_LOW
);
notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}

private void initializeNotification() {
notificationBuilder = new Notification.Builder(this, CHANNEL_ID)
.setContentText("A preparar o download...")
.setContentTitle("Homem aranha")
.setSmallIcon(R.drawable.ic_launcher_background);

startForeground(NOTIFICATION_ID, notificationBuilder.build());
}

private void downloadFile(String fileUrl) {
try {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();

if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return;
}

// Get file size
int fileLength = connection.getContentLength();

InputStream input = new BufferedInputStream(connection.getInputStream());
String fileName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
FileOutputStream output = openFileOutput(fileName, Context.MODE_PRIVATE);

byte[] data = new byte[4096];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
updateGlobalProgress(count);
}

output.flush();
output.close();
input.close();

} catch (Exception e) {
e.printStackTrace();
}
}

private void updateGlobalProgress(int downloadedBytes) {
synchronized (lock) {
totalDownloadedBytes += downloadedBytes;

int progress = (int) ((totalDownloadedBytes * 100) / totalBytesToDownload);
String progressText = String.format("Total Progress: %d%% (%dMB de %dMB)", progress, totalDownloadedBytes / (1024 * 1024), totalBytesToDownload / (1024 * 1024));

notificationBuilder.setContentTitle("Homem Aranha")
.setContentText(progressText)
.setProgress(100, progress, false);

notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
}

@Override
public void onDestroy() {
super.onDestroy();
if (executorService != null) {
executorService.shutdown();
}
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}


Подробнее здесь: https://stackoverflow.com/questions/790 ... in-android
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Исключение Android 14 при запуске службы переднего плана с типами переднего плана
    Anonymous » » в форуме Android
    0 Ответы
    60 Просмотры
    Последнее сообщение Anonymous
  • Android Glide + okHttp — у некоторых пользователей очень медленная загрузка изображений и скорость сети по Wi-Fi, но с м
    Anonymous » » в форуме Android
    0 Ответы
    16 Просмотры
    Последнее сообщение Anonymous
  • Служба переднего плана в чистом коде MVVM в Android
    Гость » » в форуме Android
    0 Ответы
    65 Просмотры
    Последнее сообщение Гость
  • Получить название активности приложения переднего плана на Android
    Anonymous » » в форуме Android
    0 Ответы
    38 Просмотры
    Последнее сообщение Anonymous
  • Android:Разрешения для служб переднего плана — для записи экрана
    Гость » » в форуме Android
    0 Ответы
    29 Просмотры
    Последнее сообщение Гость

Вернуться в «Android»