open file in another app from my apps file directory android - android

Hi i am downloading a file from URL to my files directory using download manager and then trying to open it with Action_View intent. When i run the Action_View it lets me select quick office and but says can't open file. but when i click on the file from the notification bar it opens fine. Does anyone know how to correctly open a file from an app? what i'm trying to achieve is download a file from url detect when it has finished downloading and allow the user to choose which app to open it in.
heres what i have tried so far
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(filename);
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
ContextWrapper c = new ContextWrapper(getBaseContext());
final String filePath = c.getFilesDir().getPath() + "/";
Log.v("Search", "filePath = " + filePath);
request.setDestinationInExternalFilesDir(getBaseContext(), filePath, filename);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
Toast.makeText(getBaseContext(), "Downloading...", Toast.LENGTH_LONG).show();
BroadcastReceiver onComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
openFile(filename);
}
protected void openFile(String fileName) {
String path = getFilesDir().getPath() +"/" + fileName;
File f = new File(path);
String Extension = Global.getFileExt(fileName);
MimeTypeMap myMime = MimeTypeMap.getSingleton();
String mimeType = myMime.getMimeTypeFromExtension(Extension);
try {
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File(path);
intent.setDataAndType(Uri.fromFile(file),mimeType);
startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
Toast.makeText(getBaseContext(), "No handler for this type of file.", 4000).show();
}
}
};
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
} else{
}
return false;
}else{
view.loadUrl(url);
return true;
}
}

Related

Download Manager cannot download APK

I'm trying to download an apk file from the server, but the manager writes waiting for a connection and then writes that the download failed. But this file can be downloaded via Chrome or Retrofit + InputStream. Also i tried to download jpg for test and all works
const val APK_NAME = "test-apk.apk"
val downloadRequest = DownloadManager
.Request(Uri.parse(remoteUpdateConf.newAppStoreUrl))
.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
or DownloadManager.Request.NETWORK_MOBILE
)
.setAllowedOverRoaming(false)
.setTitle(getString(R.string.update_downloading))
.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED
)
.setShowRunningNotification(true)
.setVisibleInDownloadsUi(true)
.setMimeType("application/vnd.android.package-archive")
.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS,
APK_NAME
)
downloadManager.enqueue(downloadRequest)
Use this code for download apk using Download Manager:
step 1: Download Apk:
private void DownloadFile(String urlPath, String fileName) {
try {
String OutputDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
outputFile = new File(OutputDir, fileName);
if (outputFile.exists()) {
outputFile.delete();
}
OutputFullPATH = outputFile.toString();
// Download File from url
Uri uri = Uri.parse(urlPath + fileName);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setTitle("Application Name apk download");
request.setDescription("Downloading Application Name apk");
//Setting the location to which the file is to be downloaded
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
//request.setDestinationInExternalFilesDir(UserAuthenticationActivity.this, Environment.DIRECTORY_DOWNLOADS, fileName + System.currentTimeMillis());
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadID = downloadManager.enqueue(request);
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(receiver, filter);
//return output;
} catch (Exception e) {
}
}
step 2: After Download if you want to check status
public int getDownloadedStatus() {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(DownloadID);
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
int columnOndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status = cursor.getInt(columnOndex);
return status;
}
return DownloadManager.ERROR_UNKNOWN;
}
public void CancelDownload() {
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadManager.remove(DownloadID);
}
step 3: Notification for Install
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
try {
ShowProgressBar(false);
Long DownloadedID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (DownloadedID == DownloadID) {
if (getDownloadedStatus() == DownloadManager.STATUS_SUCCESSFUL) {
Toast.makeText(context, "Download Completed", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", new File(OutputFullPATH));
Intent openFileIntent = new Intent(Intent.ACTION_VIEW);
openFileIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
openFileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
openFileIntent.setData(contentUri);
startActivity(openFileIntent);
unregisterReceiver(this);
finish();
} else {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
install.setDataAndType(Uri.parse(OutputFullPATH),
"application/vnd.android.package-archive");
startActivity(install);
unregisterReceiver(this);
finish();
}
} else {
Toast.makeText(context, "Download Not Completed", Toast.LENGTH_LONG).show();
}
}
} catch (Exception ex) {
CrashAnalytics.CrashReport(ex);
}
}
};

How can I read the file after the download and display in pdf viewer in android

I have created a app which works like if user clicks on any PDF it will download that PDF. Now I want to display that PDF after the download. i don't known how I can display that pdf after the download on onPostExecute method. Storage path of file is Environment.getExternalStorageDirectory() + "/" + "android" + "/" + "Data" + "/"+ "foldername"+"/"+"Filename"
public class DownloadTask {
cutomealertbox cdd;
File apkStorage = null;
File outputFile = null;
private Context context;
private String downloadUrl = "", downloadFileName = "";
public DownloadTask(Context context, String downloadUrl) {
this.context = context;
this.downloadUrl = downloadUrl;
downloadFileName = downloadUrl.substring(downloadUrl.lastIndexOf('/'), downloadUrl.length());
Log.e(TAG, downloadFileName);
cdd=new cutomealertbox((Activity) context);
new DownloadingTask().execute();
}
private class DownloadingTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
cdd.show(); // cdd is alert box
}
#Override
protected void onPostExecute(Void result) {
try {
if (outputFile != null) {
cdd.dismiss();
} else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
}, 3000);
Log.e(TAG, "Cannot load please try again");
}
} catch (Exception e) {
Log.e(TAG, "Download Failed with Exception - " + e);
}
Use below method and pass context and local path as argument.
public static void openFile(Context context, String localPath) {
// Create URI
try {
File file = new File(localPath);
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
// Check what kind of file you are trying to open, by comparing the url with extensions.
// When the if condition is matched, plugin sets the correct intent (mime) type,
// so Android knew what application to use to open the file
if (file.toString().contains(".pdf")) {
// PDF file
intent.setDataAndType(uri, "application/pdf");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
On Post Execute ,
Using Kotlin,
var extension: String? = null
val file = File(Environment.getExternalStorageDirectory().toString() + "/" + "android" + "/" + "Data" + "/"+ "foldername"+"/"+"Filename")
val builder = StrictMode.VmPolicy.Builder()
StrictMode.setVmPolicy(builder.build())
val uri = Uri.fromFile(file)
val intent = Intent(Intent.ACTION_VIEW)
// Check what kind of file you are trying to open, by comparing the url with extensions.
// When the if condition is matched, plugin sets the correct intent (mime) type,
// so Android knew what application to use to open the file
if (uri.toString().contains(".pdf")) {
// PDF file
intent.setDataAndType(uri, "application/pdf")
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
mContext!!.startActivity(intent)
By using Java
String extension = null;
File file = new File(Environment.getExternalStorageDirectory().toString() + "/" + "android" + "/" + "Data" + "/" + "foldername" + "/" + "Filename")
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
// Check what kind of file you are trying to open, by comparing the url with extensions.
// When the if condition is matched, plugin sets the correct intent (mime) type,
// so Android knew what application to use to open the file
if (uri.toString().contains(".pdf")) {
// PDF file
intent.setDataAndType(uri, "application/pdf");
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Assuming you have already integrated the library in your project. Add this to your XML layout in which you want to view the PDF and set the visibility to GONE.
<com.github.barteksc.pdfviewer.PDFView
android:id="#+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"/>
In postExecute(Void result) method set the pdf view according to documentation given here, and set the visibility of pdfView to View.VISIBLE.

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");
}
}

Android auto installation of APKs

I have a webview which basically is capable of intercepting all sorts of links, video, apks, hrefs.
Now, what I want is once I download an APK from a url, that it'll be auto installed:
This is part of the shouldOverrideUrlLoading() code:
else if(url.endsWith(".apk"))
{
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(final String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
}
});
Intent intent = new Intent(Intent.ACTION_VIEW ,Uri.parse(url));
startActivity(intent);
return true;
If I add
intent.setDataAndType(Uri.parse(url), "application/vnd.android.package-archive");
Than the application crashes...
Any ideas as to what to do?
EDIT: I was able to initiate a download and an installation of the package automatically (using a sleep() ):
else if(url.endsWith(".apk"))
{
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(final String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
}
});
Intent intent = new Intent(Intent.ACTION_VIEW ,Uri.parse(url));
startActivity(intent);
String fileName = Environment.getExternalStorageDirectory() + "/download/" + url.substring( url.lastIndexOf('/')+1, url.length() );
install(fileName);
return true;
and, as vitamoe suggested:
protected void install(String fileName) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(Uri.fromFile(new File(fileName)),
"application/vnd.android.package-archive");
startActivity(install);
}
However, I'm unable to capture the exact time that the download is finished, might need to create my own download function and not use the browser's one, any ideas?
To download a file without the browser do sth. like this:
String apkurl = "http://your.url.apk";
InputStream is;
try {
URL url = new URL(apkurl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setDoOutput(true);
con.connect();
is = con.getInputStream();
} catch (SSLException e) {
// HTTPS can end in SSLException "Not trusted server certificate"
}
// Path and File where to download the APK
String path = Environment.getExternalStorageDirectory() + "/download/";
String fileName = apkurl.substring(apkurl.lastIndexOf('/') + 1);
File dir = new File(path);
dir.mkdirs(); // creates the download directory if not exist
File outputFile = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
// Save file from URL to download directory on external storage
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.close();
is.close();
// finally, install the downloaded file
install(path + fileName);
You can temp. download it to an sd card, install it with the package manager and then remove it again.
protected void install(String fileName) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(Uri.fromFile(new File(fileName)),
"application/vnd.android.package-archive");
startActivity(install);
}
Due to Android security model it is not possible to install Apk file automatically.
why not trying with a download manage and a broadcast receiver that would intercept when download is finished? Download manager works for ANDROID 2.3+ though
Example here:
myWebView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Log.d("WEB_VIEW_TEST", "error code:" + errorCode + " - " + description);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// handle different requests for different type of files
// this example handles downloads requests for .apk and .mp3 files
// everything else the webview can handle normally
if (url.endsWith(".apk")) {
Uri source = Uri.parse(url);
// Make a new request pointing to the .apk url
DownloadManager.Request request = new DownloadManager.Request(source);
// appears the same in Notification bar while downloading
request.setDescription("Description for the DownloadManager Bar");
request.setTitle("YourApp.apk");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
// save the file in the "Downloads" folder of SDCARD
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "SmartPigs.apk");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
else if(url.endsWith(".mp3")) {
// if the link points to an .mp3 resource do something else
}
// if there is a link to anything else than .apk or .mp3 load the URL in the webview
else view.loadUrl(url);
return true;
}
});
Full answer here: user bboydflo
Downloading a file to Android WebView (without the download event or HTTPClient in the code)
Broadcast receiver to intercept when download has finished
private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
// toast here - download complete
}
}
};
remember to recister recevier in the main activity like this:
registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

Categories

Resources