How to download a file on click of a view in android - android

What i am having ?
Here patientAttachment.getFile_path() have the link of the url that has image
.
vObjPatientMedication.downloadId.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent myWebLink = new Intent(android.content.Intent.ACTION_VIEW);
myWebLink.setData(Uri.parse(patientAttachment.getFile_path()));
activity.startActivity(myWebLink);
}
});
What now is happening: i am displaying the image in browser
What i am trying to achieve: i want to initiate the download of that file(file can be pdf/image/word) to any default location where downloading is taken care by android.
How to achieve this ?

You can use DownloadManager:
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(uriString));
downloadManager.enqueue(request);
You should also register a receiver to know when a download completes:
registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
//Your code
}
}
};

Related

How to close the WebBrowser once the download starts and shows the app?

I'm using intent to pass my URL to WebBrowser from my android app to download files. But once the download starts, it stays in WebBrowser. So I would like to close the WebBrowser and show app once the download starts.
Here is the code I'm using to pass my URL:
js hide: false console: true babel:
} else if (tabId == R.id.tab_b) {
webView.loadUrl("file:///android_asset/D.html");
webView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
Toast.makeText(getApplicationContext(), "Downloading File", To notify the Client that the file is being downloaded
Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
Finally, if possible, can I download my app without opening the WebBrowser?
Force download :
webView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String aUrl, String userAgent, String contentDisposition, String mimetype, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(aUrl));
request.allowScanningByMediaScanner();
CookieManager cookieManager = CookieManager.getInstance();
String cookie = cookieManager.getCookie(aUrl);
request.addRequestHeader("Cookie", cookie);
request.addRequestHeader("User-Agent", userAgent);
Environment.getExternalStorageDirectory();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
});
and don't forget to add those methods to open pdf after download :
BroadcastReceiver onComplete=new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
// HERE YOU ADD WHAT YOU WANT AFTER DONWLOAD
}
};
Also don't forget declaring perrmission in the :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

On progress seekbar notification not showing in DownloadManager android

I am downloading the file from webview. But it's not displaying the on going download notification similar to this when using DownloadManager. It just doing in background operation.
How to display the status bar notification when downloading is in progress.
I can able to get the downloaded file but how to display the on going process in notification?
I used "request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);" but it's not displaying the on going process. Please guide me what mistake I am doing.
Here is my code which I used.
mWebview.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("pdf");
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,
"pdf"));
request.allowScanningByMediaScanner();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//clueless why it's not working..
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
} else {
request.setShowRunningNotification(true);
}
//request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
url, contentDisposition, "pdf"));
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadReference = dm.enqueue(request);
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadReceiver, filter);
}
});
}
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (downloadReference == referenceId) {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1));
Cursor c = dm.query(q);
if (c.moveToFirst()) {
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
// process download
String title = c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE));
File file = new File(Environment.getExternalStorageDirectory()
+ "/Download/" + title);//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");
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
//testIntent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
testIntent.setDataAndType(uri, "application/pdf");
try {
startActivity(testIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(MainActivity.this, "No application available to view PDF",
Toast.LENGTH_SHORT).show();
}
// get other required data by changing the constant passed to getColumnIndex
}
}
}
}
};
I checked in Android 7.1.1.
Yes I found solution. The problem is didn't enabled download manager.
Go to the Settings > App
In the options click 'Show System Apps'
Find 'Download Manager' and open it
Click 'Notifications' under App Settings
Switch on Allow Notifications
Reference:
https://stackoverflow.com/a/43841708/1921263

Why cannot I install an .apk after downloading it

I make an Android App, and i make a feature about update.
I download an .apk file and use intent to install it.But it always has an error like "there was a problem when parsing the package"
my code is
I use a receiver to listen the action when download complete ,code is
private BroadcastReceiver mBroadcaseReceiver;
protected void onCreate(#Nullable Bundle savedInstanceState) {
mCheckUpdateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("AboutUsActivity","check update");
downloadApk();
}
});
mBroadcaseReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){
Log.d("aboutusactivity","下载完成");
//下载完毕后安装
installApk();
}
}
};
registerReceiver(mBroadcaseReceiver,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
private void downloadApk() {
Log.d("AboutusActivity","update");
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("XXXXXX"));
request.setDescription("updating");
request.setTitle("title");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "yuedong.apk");
// 获得下载服务和队列文件
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
private void installApk() {
Intent mIntent = new Intent(Intent.ACTION_VIEW);
mIntent.setDataAndType(Uri.fromFile(new File(Environment.DIRECTORY_DOWNLOADS,"yuedong.apk")),
"application/vnd.android.package-archive");
this.startActivity(mIntent);
}
But it always like
So what's wrong with my code?
The app file .apk, that you have downloaded might be corrupted. If you try to install the corrupted apps, you will get the parse error "There was a problem parsing the package". So, try again downloading the app completely and install it.
Its may be because that file having private mode protection(access permission).Try this link.
I know the reason now
because my path which download the apk is not match the path that i choose to install the apk. so stupid i am.
i change it like
private void downloadApk(String url) {
Log.d(TAG,"download");
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("updating");
request.setTitle("My app");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
}
request.setDestinationInExternalPublicDir("/xxx/","update.apk");
// 获得下载服务和队列文件
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
private void installApk() {
File mFile;
mFile = new File(Environment.getExternalStorageDirectory()+"/xxx/update.apk");
if (mFile.exists()){
Intent mIntent = new Intent(Intent.ACTION_VIEW);
mIntent.setDataAndType(Uri.parse("file://"+mFile.getAbsolutePath()),
"application/vnd.android.package-archive");
startActivity(mIntent);
}else {
Log.d(TAG,"the file is not exist");
}
}

Receiving No apps can perform this actions error

I am attempting to get my app to offer me a choice of what browser to use. I have assigned the URL to http://google.com. When I run it, I get a 'No apps can perform this actions' error. I'm missing something and i cant figure it out.
public class myClass{
static private final String URL = "http://www.google.com";
..
..
implicitActivationButton.setOnClickListener(new OnClickListener() {
// Call startImplicitActivation() when pressed
#Override
public void onClick(View v) {
startImplicitActivation();
}
});
private void startImplicitActivation() {
Log.i(TAG, "Entered startImplicitActivation()");
Intent baseIntent = new Intent(Intent.ACTION_SEND,Uri.parse(URL));
String title = "Choose Browser";
Intent chooserIntent = Intent.createChooser(baseIntent, title);
Log.i(TAG,"Chooser Intent Action:" + chooserIntent.getAction());
startActivity(chooserIntent);
}
...
...
}
To view a Web page, use ACTION_VIEW, not ACTION_SEND.

android: download a pdf file and open after

I'm trying to download a pdf doc from internet and after that, when download ends, open it automatically throught a package.
I found some solutions for downloading by DownloadManager but no answer to open it after. One of the codes I've tested is:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
String uriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
Uri uri = Uri.parse(uriString);
intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClick(View view) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(
Uri.parse("http://www.xxxxxxx.org/directory/abc.pdf"));
enqueue = dm.enqueue(request);
}
but when the download ends successfully, the package don't find the file.
I need your help. I have spent two weeks looking for a solutions via google and android books with no success.
Thanks.
Create this method and call it in your code
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();
}
}
Or else you can refer my answer here.
How to use Asynchronous task for download progress dialog in fragment?
Its for downloading file and displaying progress diolog.Here i used asynch task.Call above method in onpost() method of asynch task.
Hope it helps you too

Categories

Resources