Download Util File
Above i have provided the util links which will work for requests of any type of file.
- if you want to install packages or something else you have to mention permissions like this in your manifest file..
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="32" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="29" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
android:name="androidx.core.content.FileProvider"
android:authorities="com.prologic.invoice.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
- you will also need object file which is down below:-
import android.content.ActivityNotFoundException
import android.content.ClipData
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.widget.Toast
import androidx.core.content.FileProvider
import com.prologic.invoice.BuildConfig
import java.io.File
object FileOpen {
fun shareFIle(context: Context, file: File) {
val shareIntent = Intent(Intent.ACTION_SEND)
shareIntent.type = "application/pdf"
val uri = FileProvider.getUriForFile(context, context.packageName + ".provider", file)
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
shareIntent.putExtra(Intent.EXTRA_STREAM, uri)
context.startActivity(Intent.createChooser(shareIntent, "Share Shop Certificate"))
}
fun openFile(context: Context, file: File) {
try {
val uri: Uri
val intent = Intent(Intent.ACTION_VIEW)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(context, context.packageName + ".provider", file)
intent.clipData = ClipData.newRawUri("", uri)
} else {
uri = Uri.fromFile(file)
}
if (file.toString().contains(".doc") || file.toString().contains(".docx")) {
intent.setDataAndType(uri, "application/msword")
} else if (file.toString().contains(".pdf")) {
intent.setDataAndType(uri, "application/pdf")
} else if (file.toString().contains(".ppt") || file.toString().contains(".pptx")) {
intent.setDataAndType(uri, "application/vnd.ms-powerpoint")
} else if (file.toString().contains(".xls") || file.toString().contains(".xlsx")) {
intent.setDataAndType(uri, "application/vnd.ms-excel")
} else if (file.toString().contains(".zip")) {
intent.setDataAndType(uri, "application/zip")
} else if (file.toString().contains(".rar")) {
intent.setDataAndType(uri, "application/x-rar-compressed")
} else if (file.toString().contains(".rtf")) {
intent.setDataAndType(uri, "application/rtf")
} else if (file.toString().contains(".wav") || file.toString().contains(".mp3")) {
intent.setDataAndType(uri, "audio/x-wav")
} else if (file.toString().contains(".gif")) {
intent.setDataAndType(uri, "image/gif")
} else if (file.toString().contains(".jpg") || file.toString()
.contains(".jpeg") || file.toString().contains(".png")
) {
intent.setDataAndType(uri, "image/jpeg")
} else if (file.toString().contains(".txt")) {
intent.setDataAndType(uri, "text/plain")
} else if (file.toString().contains(".3gp") || file.toString()
.contains(".mpg") || file.toString().contains(".mpeg") || file.toString()
.contains(".mpe") || file.toString().contains(".mp4") || file.toString()
.contains(".avi")
) {
intent.setDataAndType(uri, "video/*")
} else if (file.toString().contains(".apk")) {
installApp(context, file)
return
} else {
intent.setDataAndType(uri, "*/*")
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(
context, "No application found which can open the file", Toast.LENGTH_SHORT
).show()
}
}
fun installApp(context: Context, file: File) {
val install = Intent(Intent.ACTION_VIEW)
install.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val uri = FileProvider.getUriForFile(
context, BuildConfig.APPLICATION_ID + ".provider", file
)
install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
install.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true)
install.data = uri
context.startActivity(install)
} else {
val appInstallPath = "application/vnd.android.package-archive"
install.setDataAndType(Uri.fromFile(file), appInstallPath)
context.startActivity(install)
}
}
} you will also need this function in your constant or common class
fun getDialog(context: Context, layoutId: Int): Dialog {
val dialog = Dialog(context)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.window?.setBackgroundDrawableResource(R.color.trans)
val width = Utils.getScreenWidth(context)
dialog.setContentView(layoutId)
val layout = dialog.findViewById<ConstraintLayout>(R.id.main_layout)
val params = layout.layoutParams
params.width = width - (width * 13 / 100)
layout.layoutParams = params
return dialog
}fun isNetworkAvailable(context: Context): Boolean {
val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val capabilities = manager.getNetworkCapabilities(manager.activeNetwork)
if (capabilities == null) return false
else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) return true
else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) return true
else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) return true
} else {
val activeNetworkInfo = manager.activeNetworkInfo
if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {
return true
}
}
return false
}you will need download layout also
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/edit_layout_input_box"
android:elevation="@dimen/_1sp"
android:padding="@dimen/_25sp"
android:orientation="vertical">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="@font/medium"
android:lineSpacingExtra="@dimen/_3sp"
android:text="Downloading ..."
android:textColor="#25233C"
android:textSize="@dimen/_14sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/_15sp"
app:layout_constraintEnd_toEndOf="@+id/title"
app:layout_constraintStart_toStartOf="@+id/title"
app:layout_constraintTop_toBottomOf="@+id/title">
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="@dimen/_17sp"
android:max="100"
android:progress="50"
android:progressDrawable="@drawable/line_progressbar" />
<TextView
android:id="@+id/percent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:fontFamily="@font/medium"
android:text="0%"
android:textColor="@color/white"
android:textSize="@dimen/_9sp" />
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
for line_progressbar use this
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Define the background properties like color etc -->
<item android:id="@android:id/background">
<shape android:shape="rectangle">
<solid android:color="#8098A0A7" />
<corners android:radius="@dimen/_10sp" />
</shape>
</item>
<item android:id="@android:id/progress">
<clip>
<shape android:shape="rectangle">
<corners android:radius="@dimen/_10sp" />
<solid android:color="#EC1C24" />
</shape>
</clip>
</item>
</layer-list>you will also need this FileUtil.class
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.OpenableColumns;
import android.util.Log;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class FileUtil {
private static final int EOF = -1;
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
public static File from(Context context, Uri uri) throws IOException {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
String fileName = getFileName(context, uri);
String[] splitName = splitFileName(fileName);
File tempFile = File.createTempFile(splitName[0], splitName[1]);
tempFile = rename(tempFile, fileName);
tempFile.deleteOnExit();
FileOutputStream out = null;
try {
out = new FileOutputStream(tempFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (inputStream != null) {
copy(inputStream, out);
inputStream.close();
}
if (out != null) {
out.close();
}
return tempFile;
}
public static String fileExt(String fileName) {
int i = fileName.lastIndexOf(".");
return fileName.substring(i);
}
private static String[] splitFileName(String fileName) {
String name = fileName;
String extension = "";
int i = fileName.lastIndexOf(".");
if (i != -1) {
name = fileName.substring(0, i);
extension = fileName.substring(i);
}
return new String[]{name, extension};
}
@SuppressLint("Range")
private static String getFileName(Context context, Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf(File.separator);
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
private static File rename(File file, String newName) {
File newFile = new File(file.getParent(), newName);
if (!newFile.equals(file)) {
if (newFile.exists() && newFile.delete()) {
Log.d("FileUtil", "Delete old " + newName + " file");
}
if (file.renameTo(newFile)) {
Log.d("FileUtil", "Rename file to " + newName);
}
}
return newFile;
}
private static void copy(InputStream input, OutputStream output) throws IOException {
int n;
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
while (EOF != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
}
@SuppressLint("Range")
public static String getDownloadFile(Context context, Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
result = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) +"/"+
cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (result == null) {
result = uri.getPath();
}
return result;
}
}now you will use like this
val downloader=DownloadFIle() downloader.download(requireContext(),dowloadUrl,param,fileName)
0 Comments