import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import org.mozilla.geckoview.GeckoSession;
import org.mozilla.geckoview.GeckoView;
public class DownloadHandler extends BroadcastReceiver {
private GeckoView geckoView;
private DownloadManager downloadManager;
private long downloadId;
public DownloadHandler(GeckoView geckoView) {
this.geckoView = geckoView;
this.downloadManager = (DownloadManager) geckoView.getContext().getSystemService(Context.DOWNLOAD_SERVICE);
}
public void register() {
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
geckoView.getContext().registerReceiver(this, filter);
}
public void unregister() {
geckoView.getContext().unregisterReceiver(this);
}
@Override
public void onReceive(Context context, Intent intent) {
// Check if the received intent is for our download
long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (id == downloadId) {
// Get the downloaded file's URI
Uri uri = downloadManager.getUriForDownloadedFile(id);
// Open the downloaded file
Intent openIntent = new Intent(Intent.ACTION_VIEW);
openIntent.setDataAndType(uri, mimeTypeFromUri(uri));
openIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(openIntent);
}
}
public void handleDownload(GeckoSession session, String url, String userAgent, String contentDisposition, String mimeType) {
// Create a request for the download
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
// Set the user agent for the download
request.addRequestHeader("User-Agent", userAgent);
// Set the content disposition for the download
request.addRequestHeader("Content-Disposition", contentDisposition);
// Set the mime type for the download
request.setMimeType(mimeType);
// Set the destination for the download
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "downloaded_file.ext");
// Enqueue the download
downloadId = downloadManager.enqueue(request);
}
private String mimeTypeFromUri(Uri uri) {
String mimeType = null;
if (uri.getScheme().equals("content")) {
mimeType = geckoView.getContext().getContentResolver().getType(uri);
} else {
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri.toString());
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
}
return mimeType;
}
}