I'm using the DownloadManager to download the apk from url. Download completes, I get the onReceive in my BroadcastReceiver for DownloadManager.ACTION_DOWNLOAD_COMPLETE.
Some Coding: I download the apk file from an url to the download directory.
DownloadManager.Request r = new DownloadManager.Request(mUri);
r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "myapp.apk");
r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager dm = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
SharedPreferences mSharedPref = activity.getSharedPreferences("package", Context.MODE_PRIVATE);
mSharedPref.edit().putLong("downloadID", dm.enqueue(r)).commit();
onReceive
File apkFile = new File(Environment.DIRECTORY_DOWNLOADS + "myapp.apk");
Intent promptInstall = new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
startActivity(promptInstall);
Problems:
The file is there, I want to execute it but I package-installer is not shown
Even though I see the file in my phones download folder, I if I want to install it there is no package-installer to choose
I'm not sure if I do the file and pathing stuff right..
I get an parsing error from android when I try to open the file
Someone got an idea please?
I recently had to do something like this, hope it helps:
EDIT: Couple of notes,
apkurl is a string to the download location.
Make the byte buffer big enough for your response
try {
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH);
file.mkdirs();
// Create a file on the external storage under download
File outputFile = new File(file, "app.apk");
FileOutputStream fos = new FileOutputStream(outputFile);
HttpGet m_httpGet = null;
HttpResponse m_httpResponse = null;
// Create a http client with the parameters
HttpClient m_httpClient = setupHttpClient();
String result = null;
try {
// Create a get object
m_httpGet = new HttpGet(apkurl);
// Execute the html request
m_httpResponse = m_httpClient.execute(m_httpGet);
HttpEntity entity = m_httpResponse.getEntity();
// See if we get a response
if (entity != null) {
InputStream instream = entity.getContent();
byte[] buffer = new byte[1024];
// Write out the file
int len1 = 0;
while ((len1 = instream.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
instream.close();// till here, it works fine - .apk is download to my sdcard in download file
}
} catch (ConnectTimeoutException cte) {
// Toast.makeText(MainApplication.m_context, "Connection Timeout", Toast.LENGTH_SHORT).show();
return false;
} catch (Exception e) {
return false;
} finally {
m_httpClient.getConnectionManager().closeExpiredConnections();
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")),
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApplication.getApp().getApplicationContext().startActivity(intent);
// System.exit(0);
} catch (IOException e) {
Debug.ERROR(CLASSNAME, METHODNAME, "Failed to update new apk");
return false;
} catch (Exception e1) {
Debug.ERROR(CLASSNAME, METHODNAME, "Failed to update new apk");
return false;
}
return true;
Make sure you have the android.permission.INSTALL_PACKAGES permission declared in your AndroidManifest.xml.
Then get your APK path:
File apkFile = new File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk");
Now run the Intent:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
All downloads you do with the device...
To clarify what I mean with "Downloads" here is a screenshot. This is the standart download folder for Android 5 on Nexus 4. When I click on the apk inside this, I dont get the prompt to install a .apk. Instead the HTML-Viewer or other useless stuff shows up to choose...
One possible mistake could be the DownloadManager.. maybe he "tags" the downloaded file wrong so its not interpreted as an apk file, I don't know... but I call
promptInstall.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/myapp.apk")), "application/vnd.android.package-archive");
Related
After reading multiple post concerning this subject I have been able to put together the info needed to download an update for my apk and have it install. This is successful for versions under 23. After reading more post I discovered for versions 23> there is a slight difference in the way to execute the install. I have put together this info in the following code but I am still encountering a problem with the version 23>. I pretty much understand what the code is doing, but I have no idea why it fails to run.
try {
URL url = new URL(arg0[0]);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath() +"/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "maga.apk");
if(outputFile.exists()){
Log.i("SCROLLS ", "file exist-delete");
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
if(outputFile.exists()){
Log.i("SCROLLS ", "file exist");
}
if (Build.VERSION.SDK_INT >= 23) {
File toInstall=new File(Uri.parse(PATH+"maga.apk").getPath());
Log.i("SCROLLS ", "toInstall "+ toInstall);
Uri apkUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", toInstall);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
} else {
File toInstall = new File(PATH, "maga" + ".apk");
Uri apkUri = Uri.fromFile(toInstall);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
} catch (Exception e) {
Log.e("SCROLLS ", "Update error! " + e.getMessage());
}
return null;
}
}
When executed on an emulator with Version <23 all works. On an emulator over 23, the progress gets into the If statement and sets the toInstall value but nothing happens after that. The only thing I see in Logcat resembling and error that pertains to this is
03-24 01:35:16.562 5300-5300/com.google.android.packageinstaller E/InstallStart: Requesting uid 10079 needs to declare permission android.permission.REQUEST_INSTALL_PACKAGES
Looking into this it's my understanding that this permission is for system apps so adding it to Manifest does no good. Is there something missing from my code or a permission? I have added the provider to the manifest and the provider_paths.xml file to the project. Thanks for any help.
I'm currently trying to download a file (Word, PDF or Image) from my server to my phone and open it after. It all works when I download an Image it shows up and is saved. When I click on a PDF File, it downloads but when I try to open it only shows a black screen with an exclamation mark. When I open it with Adobe Acrobat it shows a Toast that it cant reach the file So I have the following questions:
1) Why can't a 3rd party application has access to my downloaded file and how can I fix that?
2) Where can I save my files with what code in Order to have my files in a folder where anyone can access it? (I have no sd card) And what exactly do I have to change to what in my code?
I was working on that issue for 10h+ now and tried 5+ solutions from StackOverflow but none worked for me.
The outcommented code was another solution where none was shown after even the images because the data was not found on the device.
URL url = new URL(path);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
// this will be useful to display download percentage
// might be -1: server did not report the length
file_length = urlConnection.getContentLength();
/**
* Create new Folder
*/
File new_Folder = new File("/sdcard/MY DOWNLOADED FILES/" + subFolder);
//File new_Folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), subFolder);
if (!new_Folder.exists()) {
if (!new_Folder.mkdir()) {
return "ERROR: mkdirs() failed for directory" + new_Folder.getAbsolutePath();
}
} else {
Log.i("Info:", "Folder already exists");
}
/**
* Create an output file to store the file for download
*/
inputoutput_file = new File(new_Folder, fileName);
InputStream inputStream = new BufferedInputStream(url.openStream(), 8192);
//this will read the information in 1 KB
byte[] data = new byte[1024];
int total = 0;
int count;
OutputStream outputStream = new FileOutputStream(inputoutput_file);
while ((count = inputStream.read(data))!= -1){
total+=count;
if (file_length>0) {
int progress = total * 100 / file_length;
publishProgress(progress);
outputStream.write(data, 0, count);
Log.i("Info:", "Progress: " + Integer.toString(progress));
}
}
inputStream.close();
outputStream.close();
/* //make the file visible
MediaScannerConnection
.scanFile(context, new String[]
{inputoutput_file.getAbsolutePath()},
new String[] {null}, null);
*/
return "Download Complete...";
} catch (MalformedURLException e) {
e.printStackTrace();
return "ERROR MalformedURLException" + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "ERROR IOException" + e.getMessage();
}
This is part of a class where I open my files:
switch (format) {
case "PDF":
Intent pdfIntent = new Intent();
pdfIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
pdfIntent.setAction(android.content.Intent.ACTION_VIEW);
Uri contentPDFUri = FileProvider.getUriForFile(context,
"com.ndlp.socialstudy.provider",
my_clicked_file);
pdfIntent.setDataAndType(contentPDFUri,"application/pdf");
Intent intentpdfChooser = pdfIntent.createChooser(pdfIntent, "Open With");
try {
context.startActivity(intentpdfChooser);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "Please install a PDF app to view your file!", Toast.LENGTH_LONG).show();
// Instruct the user to install a PDF reader here, or something
}
case "Word":
case "Image":
Intent imageIntent = new Intent();
imageIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
imageIntent.setAction(android.content.Intent.ACTION_VIEW);
//Uri uri = Uri.parse("file://" + my_clicked_file.getAbsolutePath());
Uri contentimageUri = FileProvider.getUriForFile(context,
"com.ndlp.socialstudy.provider",
my_clicked_file);
imageIntent.setDataAndType(contentimageUri,"image/*");
//imageIntent.setDataAndType(Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + subFolder + "/" + fileName), "image/*");
context.startActivity(imageIntent);
This is part of the code where I call the Downloader or the OpenFileClass:
File my_clicked_file = new File("/sdcard/MY DOWNLOADED FILES/" + subFolder + "/" + fileName);
if (my_clicked_file.exists()) {
OpenFileClass openFileClass = new OpenFileClass(context, whichFormat, my_clicked_file, fileName, subFolder);
openFileClass.openFile();
}
else {
FileDownloader fileDownloader = new FileDownloader(context, fileName, subFolder, whichFormat, my_clicked_file);
fileDownloader.execute(url);
}
Have you mentioned fileprovider element in app manifest? If not please add the below tags:--
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.mydomain.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
For more info please follow this link
I'm downloading a PDF from my server.
The server send me a HttpResponse with the InputStream of file's body.
I'm able to write it into a file but, when I try to read it with a PDF reader, it tells me that the file might be corrupted.
I've also noticed that the size of the PDF downloaded directly from web service is twice the size of the PDF downloaded via my application.
The code I use to download and write the PDF file is this:
String fileName = //FILENAME + ".pdf";
fileName = fileName.replaceAll("/", "_");
String extPath = Environment.getExternalStorageDirectory().toString();
String folderName = //FOLDERNAME;
try {
File folder = new File(extPath, folderName);
folder.mkdir();
File pdfFile = new File(folder, fileName);
pdfFile.createNewFile();
URL url = new URL(downloadURL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(pdfFile);
byte[] buffer = new byte[MEGABYTE];
int bufferLength;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No Application available to view PDF", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}
//otherStuff
Where I go wrong?
I've also noticed that inside the Headers of HttpResponse contains Content-type:text/html. It shoudld be something like text/pdf?
Your Downloading code seems correct. Based on that and on your comment:
I've also noticed that the size of the PDF downloaded directly from web service is twice the size of the PDF downloaded via my application."
I would suggest checking your URL. It appears that you might be downloading an html page instead of the pdf. To verify you are downloading correctly, change the download directory as follows:
//Default download directory
String extPath = Environment.DIRECTORY_DOWNLOADS;
And check the directory (via the file system, e.g. mount the phone to your computer or a file manager app) for the downloaded content to verify it is a pdf.
I have one requirement in my Android application. I need to download and save file in specific folder of SD card programmatically. I have developed source code, which is
String DownloadUrl = "http://myexample.com/android/";
String fileName = "myclock_db.db";
DownloadDatabase(DownloadUrl,fileName);
// and the method is
public void DownloadDatabase(String DownloadUrl, String fileName) {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/myclock/databases");
if(dir.exists() == false){
dir.mkdirs();
}
URL url = new URL("http://myexample.com/android/");
File file = new File(dir,fileName);
long startTime = System.currentTimeMillis();
Log.d("DownloadManager" , "download url:" +url);
Log.d("DownloadManager" , "download file name:" + fileName);
URLConnection uconn = url.openConnection();
uconn.setReadTimeout(TIMEOUT_CONNECTION);
uconn.setConnectTimeout(TIMEOUT_SOCKET);
InputStream is = uconn.getInputStream();
BufferedInputStream bufferinstream = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while((current = bufferinstream.read()) != -1){
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream( file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Log.d("DownloadManager" , "download ready in" + ((System.currentTimeMillis() - startTime)/1000) + "sec");
int dotindex = fileName.lastIndexOf('.');
if(dotindex>=0){
fileName = fileName.substring(0,dotindex);
}
catch(IOException e) {
Log.d("DownloadManager" , "Error:" + e);
}
}
Now the issue is only empty file with filename myclock_db.db is saving in the path. but I need to download and save content of file in the specific folder. Tried several ways to get the file download, but I can't.
Your download URL is not a link to any file. It's a directory. Make sure its a file and exists. Also check your logcat window for error logs. One more suggestion, its always better to do a printStackTrace() in catch blocks instead of Logs. Its gives a more detailed view of the error.
Change this line:
URL url = new URL("http://myexample.com/android/");
to:
URL url = new URL("http://myexample.com/android/yourfilename.txt"); //some file url
Next, in catch block, add this line:
e.printStackTrace();
Also in the directory path, it should be something like this:
File dir = new File(root.getAbsolutePath() + "/mnt/sdcard/myclock/databases");
instead of
File dir = new File(root.getAbsolutePath() + "/myclock/databases");
Next, make sure you have acquired permission for writing to external storage in Android manifest.
I am using following code to download and read a PDF file from internal storage on device.
I am able to download the files successfully to the directory:
data/data/packagename/app_books/file.pdf
But I am unable to read the file using a PDF reader application like Adobe Reader.
Code to download file
//Creating an internal dir;
File mydir = getApplicationContext().getDir("books", Context.MODE_WORLD_READABLE);
try {
File file = new File(mydir, outputFileName);
URL downloadUrl = new URL(url);
URLConnection ucon = downloadUrl.openConnection();
ucon.connect();
InputStream is = ucon.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
byte data[] = new byte[1024];
int current = 0;
while ((current = is.read(data)) != -1) {
fos.write(data, 0, current);
}
is.close();
fos.flush();
fos.close();
isFileDownloaded=true;
} catch (IOException e) {
e.printStackTrace();
isFileDownloaded = false;
System.out.println(outputFileName + " not downloaded");
}
if (isFileDownloaded)
System.out.println(outputFileName + " downloaded");
return isFileDownloaded;
Code to read the file
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent,
PackageManager.MATCH_DEFAULT_ONLY);
try {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
File fileToRead = new File(
"/data/data/com.example.filedownloader/app_books/Book.pdf");
Uri uri = Uri.fromFile(fileToRead.getAbsoluteFile());
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
} catch (Exception ex) {
Log.i(getClass().toString(), ex.toString());
Toast.makeText(MainActivity.this,
"Cannot open your selected file, try again later",
Toast.LENGTH_SHORT).show();
}
All works fine but the reader app says "File Path is not valid".
Your path is only valid for your app. Place the file in a place where other apps can 'see' it. Use GetExternalFilesDir() or getExternalStorageDirectory().
Note about files which are created inside the directory created by Context.getDir(String name, int mode) that they will only be accessible by your own application; you can only set the mode of the entire directory, not of individual files.
So you can use Context.openFileOutput(String name, int mode). I'm re-using your code for an example:
try {
// Now we use Context.MODE_WORLD_READABLE for this file
FileOutputStream fos = openFileOutput(outputFileName,
Context.MODE_WORLD_READABLE);
// Download data and store it to `fos`
// ...
You might want to take a look at this guide: Using the Internal Storage.
If you would like to keep the file app specific, you can use PdfRenderer available for Lollipop and above builds. There are great tutorials on google and youtube that work well. The method you are using is a secure way to store a PDF file that is only readable from inside the app ONLY. No outside application like Adobe PDF Reader will be able to even see the file.It took me a lot of seaching but I found a solution to my specific usage by using this site and especially youtube.
How to download PDF file from asset folder to storage by making folder
make sure you have storage permission are given like marshmallow device support etc then follow these steps
private void CopyReadAssets()
{
AssetManager assetManager = getContext().getAssets();
FileInputStream in = null;
FileOutputStream out = null;
File sdcard = Environment.getExternalStorageDirectory();
File dir = new File(Environment.getExternalStorageDirectory()+File.separator+ "A_level");
File dir2;
if (dir.exists() && dir.isDirectory()){
Log.e("tag out", ""+ dir);
}else {
dir.mkdir();
Log.e("tag out", "not exist");
}
File file = new File(dir, mTitle+".pdf");
try
{
Log.e("tag out", ""+ file);
out = new FileOutputStream(file);
in = new FileInputStream (new File(mPath));
Log.e("tag In", ""+ in);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag out", ""+ out);
Log.e("tag In", ""+ in);
Log.e("tag", e.getMessage());
Log.e("tag", ""+file);
Log.i("tag",""+sdcard.getAbsolutePath() + "A_level");
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}