A seguir, está o código corrigido com as sugestões mencionadas acima. Este código assume que você está trabalhando em um aplicativo Android com as permissões necessárias para download e notificações, e que o ícone R.drawable.lock_icon_green existe em seus recursos. Não esqueça de definir a variável appVersion com a string do User-Agent:
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public static void startDownload(Context context, String downloadUrl, Uri fileUri, String mimeType, String fileName) {
Log.e("save", "Request to download and save file");
try {
// Cria o canal de notificação (necessário para Android API 26+)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence channelName = "Downloads";
String channelDescription = "Notificações de download de arquivos";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("download_channel", channelName, importance);
channel.setDescription(channelDescription);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
// Construindo a URI do diretório usando a URI da árvore
Uri directoryUri = DocumentsContract.buildDocumentUriUsingTree(fileUri, DocumentsContract.getTreeDocumentId(fileUri));
Log.e("save", "directoryUri: " + directoryUri);
// Criando um novo documento (arquivo) no diretório especificado
Uri newFileUri = DocumentsContract.createDocument(context.getContentResolver(), directoryUri, mimeType, fileName);
Log.e("save", "newFileUri: " + newFileUri);
// Verificando se a URI do novo arquivo foi criada com sucesso
if (newFileUri != null) {
try (OutputStream os = context.getContentResolver().openOutputStream(newFileUri)) {
// Conectando ao URL para baixar o arquivo
URL url = new URL(downloadUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// User-Agent deve ser definido corretamente
String appVersion = "MyAppVersion"; // Substitua pela sua versão do aplicativo
connection.setRequestProperty("User-Agent", appVersion);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "download_channel")
.setContentTitle("Download iniciado")
.setContentText("Baixando " + fileName)
.setSmallIcon(R.drawable.lock_icon_green)
.setProgress(100, 0, true);
int notificationId = 1;
notificationManager.notify(notificationId, builder.build());
// Obtém o tamanho total do arquivo, se conhecido
int totalSize = connection.getContentLength();
try (InputStream is = connection.getInputStream()) {
// Lendo dados do InputStream e escrevendo no OutputStream
byte[] buffer = new byte[4096];
int bytesRead, progress = 0;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
progress += bytesRead;
// Calcula a porcentagem de progresso
int percentage = totalSize > 0 ? (int) ((progress / (float) totalSize) * 100) : -1;
// Atualiza a notificação
builder.setProgress(100, percentage, false);
builder.setContentText(percentage + "%");
notificationManager.notify(notificationId, builder.build());
}
// Download finalizado
builder.setContentText("Download finalizado")
.setProgress(0, 0, false);
notificationManager.notify(notificationId, builder.build());
Log.e("save", "File download and save successful");
} finally {
connection.disconnect();
}
} catch (Exception e) {
Log.e("FileDownloader", "Failed to download or save file: " + e.getMessage());
e.printStackTrace();
}
} else {
Log.e("FileDownloader", "Failed to create new file URI.");
}
} catch (Exception e) {
Log.e("FileDownloader", "Exception: " + e.getMessage());
e.printStackTrace();
}
}