Proper Way To Separate Class - Download Manager - java

Can I separate DownloadManager in a separate class? I want to reused it in my several class. In Volley we can make a class extending StringRequest or ImageRequest.
For example:
public class VolleyStringRequest extends StringRequest{
public VolleyStringRequest(Response.Listenter<String> listener,
Response.ErrorListener errorListener)
{
super(Method.POST, " " , listener, errorListener);
} }
I came across with this link. All of it is directly declare. How can I achieve this in a separate class by extends DownloadManager?
DownloadManager dm= (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("https://www.google.com.tw/images/srpr/logo4w.png"));
dm.enqueue(request);
DownloadManager dm= (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("https://www.google.com.tw/images/srpr/logo4w.png"));
dm.enqueue(request);

wrap following downloadThroughManager(String imageUrl, Context context) method in class, so that you can use it in several places in your project.
public static void downloadThroughManager(String imageUrl, Context context) {
File path = new File(imageUrl);
String fileName = path.getName();
final DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(imageUrl);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle(fileName);
request.setDescription(fileName);
request.setVisibleInDownloadsUi(true);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
long ref = downloadManager.enqueue(request);
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
long downloadReference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
Log.i("GenerateTurePDfAsync", "Download completed");
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadReference);
Cursor cur = downloadManager.query(query);
if (cur.moveToFirst()) {
int columnIndex = cur.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == cur.getInt(columnIndex)) {
String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
Toast.makeText(context, "File has been downloaded successfully.", Toast.LENGTH_SHORT).show();
} else if (DownloadManager.STATUS_FAILED == cur.getInt(columnIndex)) {
int columnReason = cur.getColumnIndex(DownloadManager.COLUMN_REASON);
int reason = cur.getInt(columnReason);
switch(reason){
case DownloadManager.ERROR_FILE_ERROR:
Toast.makeText(context, "Download Failed.File is corrupt.", Toast.LENGTH_LONG).show();
break;
case DownloadManager.ERROR_HTTP_DATA_ERROR:
Toast.makeText(context, "Download Failed.Http Error Found.", Toast.LENGTH_LONG).show();
break;
case DownloadManager.ERROR_INSUFFICIENT_SPACE:
Toast.makeText(context, "Download Failed due to insufficient space in internal storage", Toast.LENGTH_LONG).show();
break;
case DownloadManager.ERROR_UNHANDLED_HTTP_CODE:
Toast.makeText(context, "Download Failed. Http Code Error Found.", Toast.LENGTH_LONG).show();
break;
case DownloadManager.ERROR_UNKNOWN:
Toast.makeText(context, "Download Failed.", Toast.LENGTH_LONG).show();
break;
case DownloadManager.ERROR_CANNOT_RESUME:
Toast.makeText(context, "ERROR_CANNOT_RESUME", Toast.LENGTH_LONG).show();
break;
case DownloadManager.ERROR_TOO_MANY_REDIRECTS:
Toast.makeText(context, "ERROR_TOO_MANY_REDIRECTS", Toast.LENGTH_LONG).show();
break;
case DownloadManager.ERROR_DEVICE_NOT_FOUND:
Toast.makeText(context, "ERROR_DEVICE_NOT_FOUND", Toast.LENGTH_LONG).show();
break;
}
}
}
}
};
context.registerReceiver(receiver, filter);
}

You can create a global Download class which extends Application class and declare a public method which takes the Uri as the input.
class DownloadClass extends Application {
public void startDownload(String url)
{
DownloadManager dm= (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new
DownloadManager.Request(Uri.parse(url));
dm.enqueue(request);
}
}
then whereever you need to access this data, get Application object by:
DownloadClass download=(DownloadClass)context.getApplication();
download.startDownload("https://www.google.com.tw/images/srpr/logo4w.png");

Related

Check if a file exists in Android

Android/Java, API level 12.
I'm trying to check if a .zip file exists in the Downloads folder. If it doesn't exist then I'm downloading it from the internet using DownloadManager. For the purposes of testing I'm running my checkIfFileExists immediately after the onReceive method of the DownloadManager, subject to the download being successful. My issue is that checkIfFileExists is returning false every time, even after I've just downloaded the file and I've checked manually that it does exist.
The relevant code is below.
DownloadManager dm;
long queueid;
String filename = "myfile.zip", url = "http://myurl/", uriString = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
[...]
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action))
{
DownloadManager.Query req_query = new DownloadManager.Query();
req_query.setFilterById(queueid);
Cursor c = dm.query(req_query);
if (c==null)
{
Toast.makeText(context, "Download not found!", Toast.LENGTH_SHORT).show();
}
else
{
if (c.moveToFirst())
{
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL==c.getInt(columnIndex))
{
uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
Toast.makeText(context, "Download finished.", Toast.LENGTH_SHORT).show();
Toast.makeText(context, uriString, Toast.LENGTH_LONG).show();
checkIfFileExists();
}
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClickDownload(View v) // this method seems to be working with no issues.
{
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, filename);
queueid = dm.enqueue(request);
}
private boolean checkIfFileExists()
{
File file = new File(uriString);
if(file.exists())
{
Toast.makeText(this, "Exists", Toast.LENGTH_SHORT).show();
return true;
}
else
{
Toast.makeText(this, "Doesn't exist", Toast.LENGTH_SHORT).show();
return false;
}
}
I was expecting if(file.exists()) to evaluate to true since the file does exist.
What actually happens is if(file.exists()) always evaluates as false.
Can anyone see what I'm doing wrong?
Change your method like this.:
private boolean checkIfFileExists(String zipName /*ex: fileName.zip*/) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), zipName);
if(file.exists()) {
Toast.makeText(this, "Exists", Toast.LENGTH_SHORT).show();
return true;
} else {
Toast.makeText(this, "Doesn't exist", Toast.LENGTH_SHORT).show();
return false;
}
}

How To Have Notification When Download Complete

I have a download feature in my android app. When I download a file, it will notify me by toast. I want to know how to have a toast notification when the download complete. I have trying other suggestions but haven't succeed in finding the result I expected.
Here is the download code.
webView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition,
String mimeType, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie",cookies);
request.addRequestHeader("User-Agent",userAgent);
request.setDescription("Downloading File");
request.setTitle(URLUtil.guessFileName(url,contentDisposition,mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
URLUtil.guessFileName(url, contentDisposition, mimeType));
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadManager.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_SHORT).show();
}
});
Thank you in advance.
You can create a Broadcast Receiver to handle any file that had completed downloading :
Main Activity
public class MainActivity extends AppCompatActivity {
// create an object
OnComplete onComplete ;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = null;
webView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition,
String mimeType, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie",cookies);
request.addRequestHeader("User-Agent",userAgent);
request.setDescription("Downloading File");
request.setTitle(URLUtil.guessFileName(url,contentDisposition,mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
URLUtil.guessFileName(url, contentDisposition, mimeType));
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadManager.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_SHORT).show();
}
});
// the broadcast receiver object
onComplete = new OnComplete();
}
#Override
protected void onResume() {
super.onResume();
// to start handling any download that completes
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
#Override
protected void onPause() {
super.onPause();
// to stop handling download complete when exit app
unregisterReceiver(onComplete);
}
}
The Broadcast Receiver (OnComplete)
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class OnComplete extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// these codes will run when download completed
// And you can do some thing
}
}
and please don't forget to add this in your Mainfest.xml at the <application/> tag
<receiver android:name=".OnComplete" />
Thanks to #a7d.24_ for the answer given.
I have simplified the answer so I didn't need to create new Java Class (OnComplete) and therefore no need to add it to the Manifest.XML.
I just have to add single line of code inside webView.setDownloadListener and create new BroadcastReceiver in the WebView Class.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
webView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition,
String mimeType, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie",cookies);
request.addRequestHeader("User-Agent",userAgent);
request.setDescription("Downloading File");
request.setTitle(URLUtil.guessFileName(url,contentDisposition,mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
URLUtil.guessFileName(url, contentDisposition, mimeType));
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
//Registering receiver in Download Manager
registerReceiver(onCompleted, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
downloadManager.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_SHORT).show();
}
});
...
BroadcastReceiver onCompleted = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context.getApplicationContext(), "Download Finish", Toast.LENGTH_SHORT).show();

Reading Database File from External Storage

So, this program downloads a file from firebase storage,
my downloading code is:
private void downloadFiles(Context context, String fileName, String destinationDirectory, String url) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalFilesDir(context, String.valueOf(destinationDirectory), fileName);
downloadManager.enqueue(request);
}
public void downloading(final String name) {
downloadRef = storage.getInstance().getReference().child(name);
downloadRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String url = uri.toString();
downloadFiles(Main2Activity.this, name, getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), url);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Main2Activity.this, "Failed!!!", Toast.LENGTH_LONG).show();
}
});
}
and then I want to use this database so I tried to open it with:
database = SQLiteDatabase.openDatabase(myPath, null, 0);
How can I solve this one? It would be really helpful guys.
I thought your problem was accessibility.
That's why I brought a activity back to get permission from the user.
You test this code
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.putExtra("name", arrayList.get(position));
startActivity(intent);
}
}
});
You are using Environment.getExternalStorageState() which returns the current state of the primary shared/external storage media. It cannot be used to get the path as string of any file. Use context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) to get the string value of the path to the Download directory.

Java: How to automatically open pdf after Download

I've been looking for various tutorials but no one can solve my case. I hope here is something that can make me understand, about how to open PDF file automatically after finished download from database to android.
This is my download script.
#Override
public void onBindViewHolder(HolderData holder, int position) {
final ModelData md = mItems.get(position);
holder.txtname.setText(md.getName());
holder.txtwaktu.setText(md.getWaktu());
//Proses Downloading
holder.relativeLayoutMateri.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
uri = String.valueOf(Uri.parse("http://192.168.43.144/MLearning/crud/"+md.getPath()));
dm = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(uri));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
longid = dm.enqueue(request);
Toast.makeText(context, md.getName()+" Berhasil Di Download"+md.getPath(), Toast.LENGTH_SHORT).show();
}
});
}
Here is the solution please use ACTION_VIEW Intent to open all you need the path of downloaded pdf.
private static String filepath = Environment.getExternalStorageDirectory().getPath()+"/myfile.pdf";
File file = new File(filepath);
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Log.d(TAG,e.getMessage());
}
}

Android open downloaded file

I have a question about downloading a pdf file and opening it with an pdf reader application installed on the phone. I'm new to android and working my way up but got stuck on this part.
So what i have now:
I have an activity that for now starts downloading a pdf file and tries to open is with an intent. For now everything is static so thats why i have a set url.
private void DownloadFile(){
DownloadManager downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
Uri Download_Uri = Uri.parse("http://awebiste.adomain/afile.pdf");
DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedOverRoaming(false);
request.setTitle("My Data Download");
request.setDescription("Android Data download using DownloadManager.");
request.setDestinationInExternalFilesDir(this,Environment.DIRECTORY_DOWNLOADS,"test.pdf");
Long downloadReference = downloadManager.enqueue(request);
if (downloadReference != null){
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.parse(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/test.pdf"), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Log.v("OPEN_FILE_PATH", getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/test.pdf");
startActivity(target);
} else {
//TODO something went wrong error
}
}
Now the file is downloaded and saved in the application folder under /storage.sdcard0/Android/data/<application>/files/download and from the documents browser the file can be opent. But when i use the intent at the button of my code i get a toast that the file can not be opent. After some searching on google i think its a permission problem because these files are private to the application. So how do I make these files public?
Here's How I did it after a long day of search,Your code helped me a little to solve it:
String name;
DownloadManager mManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_interview);
Button down = (Button) findViewById(R.id.download);
down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
down();
}
});
}
public void down() {
mManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = Uri.parse(DOWNLOAD_FILE);
DownloadManager.Request request = new DownloadManager.Request(
downloadUri)
.setAllowedOverRoaming(false)
.setTitle("Downloading")
.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, name + "CV.pdf")
.setDescription("Download in progress").setMimeType("pdf");
}
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(broadcast, intentFilter);
}
public void showPdf() {
try {
File file = new File(Environment.getExternalStorageDirectory()
+ "/Download/" + name + "CV.pdf");//name here is the name of any string you want to pass to the method
if (!file.isDirectory())
file.mkdir();
Intent testIntent = new Intent("com.adobe.reader");
testIntent.setType("application/pdf");
testIntent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
testIntent.setDataAndType(uri, "application/pdf");
startActivity(testIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
BroadcastReceiver broadcast = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
showPdf();
}
};

Categories

Resources