can we open download folder via. intent? - android

Actually, I need to open the default Download folder from my application. Is it possible? If yes, then please provide some reference.
I am able to get the path of Download folder with the help of:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
Any help will be well appreciated.

You can show the recent downloads activity with the following Intent
startActivity(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS));
Available since API 9

Samsung solution:
public static void openDownloads(#NonNull Activity activity) {
if (isSamsung()) {
Intent intent = activity.getPackageManager()
.getLaunchIntentForPackage("com.sec.android.app.myfiles");
intent.setAction("samsung.myfiles.intent.action.LAUNCH_MY_FILES");
intent.putExtra("samsung.myfiles.intent.extra.START_PATH",
getDownloadsFile().getPath());
activity.startActivity(intent);
}
else activity.startActivity(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS));
}
public static boolean isSamsung() {
String manufacturer = Build.MANUFACTURER;
if (manufacturer != null) return manufacturer.toLowerCase().equals("samsung");
return false;
}
public static File getDownloadsFile() {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
}
Found by decompiling the Samsung My Files app dex and seeing how the MainActivity deals with intents.
public static final String MYFILES_NOTIFICATION_LAUNCH_INTENT_NAME = "samsung.myfiles.intent.action.LAUNCH_MY_FILES";
public static final String NOTIFICATION_START_PATH = "samsung.myfiles.intent.extra.START_PATH";
public static final String START_PATH = "FOLDERPATH";
if (Constant.MYFILES_NOTIFICATION_LAUNCH_INTENT_NAME.equals(intent.getAction())) {
String startNotificationPath = intent.getStringExtra(Constant.NOTIFICATION_START_PATH);
if (startNotificationPath != null) {
Bundle newArgument = new Bundle();
newArgument.putString(Constant.START_PATH, startNotificationPath);
if (new File(startNotificationPath).exists()) {
startBrowser(513, newArgument);
}
}
intent.removeExtra(Constant.NOTIFICATION_START_PATH);
}

I had similar problem showing files in Downloads in Samsung and LG and i just added file-parameter "downloaded" for DownloadManager and file showing in Downloads:
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
downloadManager.addCompletedDownload(file.getName(), file.getName(), true,
"application", file.getPath(), file.length(), true);

Related

How to delete a file from external storage android studio, using only Uri

So I have taken a look at examples from other people and implemented this.
File delete= new File(uri.getPath());
if(delete.exists()){
Log.d("Delete", "File Exists");
if(delete.delete()){
Log.d("Deleted", ""+uri);
}
else{
Log.d("Unable to delete", ""+uri);
}
}
else{
Log.d("Delete", "File is not found");
}
Now the only problem is that the path name i get is "content://downloads/all_downloads/644", and according to my printed logcat, This file could not be found. Note: This file does exist and I used the same uri to actually play the video. Thank you for your help. EDIT: OK This is how I got my URI.
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Log.d("REFERENCE", "E"+"Entering Broadcast");
long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
uri=( manager.getUriForDownloadedFile(referenceId));
}
};
Now I appreciate very much for the suggestions given bellow, but I am still stuck even after reading the documentation. Suppose I cannot delete using a Uri, is there a way to convert my uri into something useful instead. I don't want to manually enter the address to the location of my files.
#Here is my entire code...
public class Cacher {
private DownloadManager manager;
private Uri uri;
public Cacher(String urlIn , Context context){
Log.d("REFERENCE", "A1- casher");
manager= (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Log.d("REFERENCE", "A");
Uri temp=Uri.parse(urlIn);
Log.d("REFERENCE", "B");
DownloadManager.Request request= new DownloadManager.Request(temp);
//
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference=manager.enqueue(request);
// Toast.makeText(this,""+reference,Toast.LENGTH_LONG);
Log.d("REFERENCE", "C"+"Downloading video");
Log.d("REFERENCE", "D"+"Setting broadcast");
context.registerReceiver(onComplete,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Log.d("REFERENCE", "F"+"Now Setting the uri table with");
}
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Log.d("REFERENCE", "E"+"Entering Broadcast");
long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
uri=( manager.getUriForDownloadedFile(referenceId));
}
};
//TODO: Add Utility to remove all Cached Videos
//TODO: Add Utility to delete a single cached video after it has been watched.
public Uri getUri() {
return uri;
}
}
So I have taken a look at examples from other people and implemented this.
That would only work if the Uri has a file scheme and you have write access to the directory that holds the file.
How to delete a file from external storage android studio, using only Uri
Most likely, you don't.
If you get the Uri from ACTION_OPEN_DOCUMENT or ACTION_CREATE_DOCUMENT, wrap the Uri in a DocumentFile using fromSingleUri(), then call delete() on the DocumentFile.
For any other content Uri, you are welcome to try calling delete() on a ContentResolver, but do not expect it to work. There is no requirement that a ContentProvider offer you any way to delete a piece of content. The app that supplies the ContentProvider should have its own way of allowing users to delete things.
So here is the solution to my problem for those who do not want to read through our comments. First, chose a directory to download to. Then use that files path and use the delete() functionality. Keep in mind that once you create a directory with a folder name, you only need to reference the folder name and not the entire path. Here is the code I hope it helps:
String in= GenerateDirectory.createVideoDirectory(context);// Might be useless here.
manager= (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri temp=Uri.parse(urlIn);
Ringtone r= RingtoneManager.getRingtone(context, temp);
String filename=(r.getTitle(context));
DownloadManager.Request request= new DownloadManager.Request(temp);
request.setDestinationInExternalPublicDir("/secretVideos", filename);
uri=Uri.parse(in+"/"+filename);
Log.d("REFERENCE", "Uri that is returned "+uri);
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
manager.enqueue(request);
// And then
public void removeCache(){
//TODO: Fix this. For some reason the Uri used gives invalid path name.
Log.d("Delete", "Directory to find ... "+uri);
File delete= new File(uri.getPath());
if(delete.exists()){
Log.d("Delete", "File Exists");
if(delete.delete()){
Log.d("Deleted", ""+uri);
}
}
}
// Where I create the directory
private int RESULT=0;
public static String createVideoDirectory(Context context){
String pathToExternalStorage = Environment.getExternalStorageDirectory().toString();
File appDirectory = new File(pathToExternalStorage + "/" + "secretVideos");
if(!appDirectory.exists()){
Log.d("Directory","Directory DNE");
if(appDirectory.mkdir()) {
Log.d("Directory", "Directory Created");
//Log.d("Directory","Unable to create directory, using default directory");
}
else if(appDirectory.canWrite()){
Log.d("Directory", "Permission given");
}
else{
Log.d("Directory", "Lack of permission");
}
}
else{
Log.d("Directory","Already Exists");
}
return appDirectory.toString();
}
private void writeAndReadPermissions(Context context){
if(ContextCompat.checkSelfPermission(context, permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions((Activity) context, new String[]{permission.WRITE_EXTERNAL_STORAGE, permission.READ_EXTERNAL_STORAGE}, RESULT);
}
}

Trying to send a pdf using cwac provider

I can't quite get cwac to work, and looking at the demo code hasn't helped. I'm simply trying to export a pdf through a share intent. Currently the output is a "Can't attach empty file" error. But the file does exist, and I can't tell if the problem is with the file name, location, or cwac provider usage.
Here is how I've set up the provider.
<provider
android:name="com.commonsware.cwac.provider.StreamProvider"
android:authorities="com.anothergamedesigner.CatVimeoTest.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="com.commonsware.cwac.provider.STREAM_PROVIDER_PATHS"
android:resource="#xml/file_paths"/>
</provider>
This is my xml resource the provider is using. I set path to "" because I don't have any subdirectories. I don't know if those are required, but ideally I don't want to have to switch up my code elsewhere for the file restructure necessary to put the files in subdirectories. Although, if that's the problem, I suppose I could, but I don't see why the root shouldn't work.
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<asset name="assets" path=""/>
</paths>
Here is my PDFActivity (extends AppCompatActivity):
Variables:
private String pdfName //set in onCreate; ex. "This is my.pdf"
private static final String AUTHORITY = "com.anothergamedesigner.CatVimeoTest";
private static final Uri PROVIDER = Uri.parse("content://"+AUTHORITY);
private static final String ASSET_PATHS ="assets/";
Methods definitions:
private Intent getOpenPDFShareIntent(String name){
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("application/pdf");
shareIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {""});
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getResources().getString(R.string.default_share_subject));
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, getResources().getString(R.string.default_share_text));
shareIntent.putExtra(Intent.EXTRA_STREAM, getURI());
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.setType("text/plain");
return shareIntent;
}
private Uri getURI(){
String path = ASSET_PATHS + pdfName;
return(PROVIDER
.buildUpon()
.appendPath(StreamProvider.getUriPrefix(AUTHORITY))
.appendPath(path)
.build());
}
In getURI(), an example return for System.out.println(path) is: "assets/my.pdf"
The code runs via a menu button that on selection:
Intent shareIntent = getOpenPDFShareIntent(pdfName);
StartActivity(Intent.createChooser(shareIntent, getResources().getString(R.string.contact_send_mail));
EDIT:
Attempting to remove null URIPrefix:
private Uri getURI(){
//String path = ASSET_PATHS + pdfName;
if(StreamProvider.getUriPrefix(AUTHORITY) != null){
return(PROVIDER
.buildUpon()
.appendPath(StreamProvider.getUriPrefix(AUTHORITY))
.appendPath(ASSET_PATHS)
.appendPath(pdfName)
.build());
} else{
return(PROVIDER
.buildUpon()
.appendPath(ASSET_PATHS)
.appendPath(pdfName)
.build());
}
}
EDIT 2 - Testing with DocumentFile:
I used these new methods from another SO answer and altered it to return the file.
private File CopyReadAssets()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "my.pdf");
try
{
in = assetManager.open("my.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
return file;
}
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);
}
}
Then I tested using:
DocumentFile aFile = DocumentFile.fromFile(CopyReadAssets());
DocumentFile file = DocumentFile.fromSingleUri(this, getURI());
System.out.println(aFile.getName());
System.out.println(aFile.length());
System.out.println(file.getName());
System.out.println(file.length());
It returns "my.pdf" and "33528" for aFile and "my.pdf" and "FileNotFoundException" for file.
content://com.anothergamedesigner.CatVimeoTest/null/assets%2FCEGA%20OnBoard%20Su‌​pport%201.6.compressed.pdf
There are two problems here that I can see.
First, StreamProvider.getUriPrefix(AUTHORITY) is returning null. I don't know why, as you do not appear to be subclassing StreamProvider. That being said, you should check for null and skip that appendPath() statement if it is null.
Second, rather than ASSET_PATHS + pdfName, use two appendPath() statements. This should prevent the / from being converted into %2F.
Note that I have not tried files with spaces in the name, or anything else that has to get escaped, as you have in your filename. It's possible that there are bugs related to this. If changing the two items above do not help, try renaming the PDF temporarily to something simple. If that then works, I have a bug that I'll need to fix.
FINAL CODE
The problem is seems was with ASSET_PATHS. Appending the pdfName to "assets" proved to be problematic for some reason. Because of this I chose to change ASSET_PATHS from a final and then set it in the onCreate method. This would be one way to do it, or you could hard code in the different pdfs such as in the demo project.
public class PDFViewActivity extends AppCompatActivity {
private String pdfName;
...
private static final String AUTHORITY = "com.your.provider";
private static final Uri PROVIDER = Uri.parse("content://"+AUTHORITY);
private static String ASSET_PATHS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
pdfName = extras.getString("pdfName");
...
ASSET_PATHS = "assets/" + pdfName;
// Place an PDFViewFragment as our content pane
PDFViewFragment f = new PDFViewFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, f).commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_pdf, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_button_share:
Intent shareIntent = getOpenPDFShareIntent();
startActivity(Intent.createChooser(shareIntent, "Send Email"));
return true;
...
default:
return super.onOptionsItemSelected(item);
}
}
private Intent getOpenPDFShareIntent(){
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("application/pdf");
shareIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {""});
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getResources().getString(R.string.default_share_subject));
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, getResources().getString(R.string.default_share_text));
shareIntent.putExtra(Intent.EXTRA_STREAM, getURI());
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
return shareIntent;
}
private Uri getURI(){
return(PROVIDER
.buildUpon()
.appendPath(StreamProvider.getUriPrefix(AUTHORITY))
.appendPath(ASSET_PATHS)
.build());
}
}

Android Open gallery to folder and slide through images

I'm able to open Gallery in a specific folder and image; however, when I try to slide through the images that functionality does not seem to work. Since I'm opening the Gallery app I figured that Gallery should handle this functionality. Anyone have any ideas? Can't seem to figure out what to do.
Below is my code
public OpenGalleyToSpecificFolder( Context _context, String path, String fileName){
mContext = _context;
mMediaScannerConnection = null;
mPath = path;
mFileName = fileName;
}
public void OpenGallary( ){
File folder_name = new File(mPath);
allFiles = folder_name.listFiles();
for(int i = allFiles.length - 1; i > 0; --i){
if(allFiles[i].getName().equals(mFileName)){
index = i;
break;
}
}
if(mMediaScannerConnection == null)
mMediaScannerConnection = new MediaScannerConnection(mContext, this);
mMediaScannerConnection.connect();
}
#Override
public void onMediaScannerConnected() {
mMediaScannerConnection.scanFile(allFiles[index].getAbsolutePath(), null);
}
#Override
public void onScanCompleted(String path, Uri uri) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
mContext.startActivity(intent);
mMediaScannerConnection.disconnect();
}
There are thousands of Android device models. There will be hundreds of different "gallery apps" pre-installed across those models, let alone other apps that support ACTION_VIEW that users install themselves. What those apps do, in response to your Intent, is up to the developers of those apps, not you.
If you want a specific look-and-feel to browsing images, implement your own image-browsing UI in your app.

Opening shared image via Gmail Intent

I have the following code that correctly attaches the image to the email and sends:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Set tht type to image/* and add the extra text field for the message to send
sharingIntent.setType(Application2.instance().getResString(R.string.share_intent_type_text_image));
sharingIntent.putExtra(Intent.EXTRA_TEXT, String.format(Application2.instance().getResString(R.string.share_intent_body_question), question.question));
if (destFile != null)
{
Uri uri = Uri.fromFile(destFile);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
((ActivityMain) getActivity()).startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
R.string.share_intent_type_text_image is defined as "image/png"
destFile is an image grabbed from the external cache directory of the app, (((ActivityMain) getActivity()).getExternalCacheDir()
However, when I attempt to open the file in Gmail, a dialog appears that says: Info - No app can open this attachment for viewing. I've downloaded the file via my PC and the extension comes up as .File. I can open it with paint and other image viewers.
Anyone experience this before?
Considering the FileProvider problems, and also because I wanted to implement a max cache size for collected temp files, I went with a ContentProvider solution and it works a treat. Basically, you're allowed to use your internal cache without any problem but still provide third party apps with a URI they can use to reference your temporary files you want to share with them. Because you use your internal cache, there will be no unnecessary WRITE_EXTERNAL_STORAGE permission to ask for.
The added max cache size limit (that you can remove from the class by simply deleting everything from checkSize() to the end of the class, for instance, if you can make sure you delete all files directly after sharing, so they won't remain on the device) works by checking the cumulated max size upon each call and clearing up half the cache (deleting the oldest files) if necessary.
public class TemporaryFile extends ContentProvider {
private static final long MAX_SIZE = 512 * 1024;
// commented out on purpose so that you don't forget to rewrite it...
// public static final String AUTHORITY = "com.example.tempfile";
private UriMatcher uriMatcher;
#Override
public boolean onCreate() {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, "*", 1);
return true;
}
#Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
if (uriMatcher.match(uri) == 1) {
final String file = getContext().getCacheDir() + File.separator + uri.getLastPathSegment();
return ParcelFileDescriptor.open(new File(file), ParcelFileDescriptor.MODE_READ_ONLY);
}
else
throw new FileNotFoundException(uri.toString());
}
#Override
public int update (Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
#Override
public int delete (Uri uri, String selection, String[] selectionArgs) {
return 0;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
#Override
public String getType(Uri uri) {
return null;
}
#Override
public Cursor query (Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return null;
}
public static File getFile(Context context, String prefix, String extension) throws IOException {
checkSize(context);
File file = File.createTempFile(prefix, extension, context.getCacheDir());
file.setReadable(true);
file.deleteOnExit();
return file;
}
public static Uri getPublicUri(File file) {
return Uri.withAppendedPath(Uri.parse("content://" + AUTHORITY), file.getName());
}
public static void checkSize(Context context) throws IOException {
File dir = context.getCacheDir();
if (getDirSize(dir) > MAX_SIZE)
cleanDir(dir, MAX_SIZE / 2);
}
private static long getDirSize(File dir) {
long size = 0;
for (File file : dir.listFiles())
if (file.isFile())
size += file.length();
return size;
}
private static void cleanDir(File dir, long atLeast) {
long deleted = 0;
File[] files = dir.listFiles();
Arrays.sort(files, new Comparator<File>() {
public int compare(File f1, File f2) {
return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
}
});
for (File file : files) {
deleted += file.length();
file.delete();
if (deleted >= atLeast)
break;
}
}
}
Using it couldn't be simpler, just call
File file = TemporaryFile.getFile(this, "prefix", ".extension");
whenever you want to create a new file and
TemporaryFile.getPublicUri(file)
whenever you want to get a public Uri to the file, eg. to pass it to an intent as data or Intent.EXTRA_STREAM.
Being a provider, don't forget to add the necessary manifest entry, either:
<provider
android:name=".TemporaryFile"
android:authorities="com.example.tempfile"
android:exported="true"
tools:ignore="ExportedContentProvider" >
</provider>
This works but requires external storage and the relating permissions. When downloading an app, a dialog will show that the app is requesting to be able to read/write data which may turn users away. Use the FileProvider as Simon suggested in my initial post if that's a concern.
Useful links:
https://developer.android.com/reference/android/support/v4/content/FileProvider.html
I attempted to use the File Provider as Simon suggested in my initial post to no avail. I received a NullPointerException on the following line:
final ProviderInfo info = context.getPackageManager()
.resolveContentProvider(authority, PackageManager.GET_META_DATA);
I was unable to track the problem after following the guide at:
https://developer.android.com/reference/android/support/v4/content/FileProvider.html
as well as the other thread at:
How to use support FileProvider for sharing content to other apps?
At this point I realized there is no file type set for the images being used. I simply added .png to the files and the attachments work correctly in Gmail as well as the previous apps that already worked.
I provided the following code if anyone was curious how I shared an internal file. It's not complete and does not handle errors completely but it may be useful for someone as a start.
// Copy image file to external memory and send with the intent
File srcFile = getImage();
File destDir = new File(((ActivityMain) getActivity()).getExternalCacheDir(),
Application2.instance().getResString(R.string.temporary_external_image_path));
if(!destDir.exists())
{
destDir.mkdirs();
}
if(destDir != null && srcFile != null)
{
File destFile = new File(destDir, srcFile.getName());
if (!destFile.exists())
{
try
{
Application2.instance().copy(srcFile, destFile);
}
catch (IOException e)
{
if (BuildConfig.DEBUG) Log.e("Failed to copy file '" + srcFile.getName() + "'");
}
}
if (destFile != null)
{
Uri uri = Uri.fromFile(destFile);
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
((ActivityMain) getActivity()).startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
}

Launch Adobe Reader in Android App

I have an Android app where I intercept a PDF file download event in the WebView, download it using the DownloadManager, and launch a new intent with the Adobe Reader to display the file. It works fine, except that when the Adobe Reader starts, it displays the following message prior to displaying the actual file:
Read-only document | To modify this document save a copy on your device.
Save | View Read-only
After I dismiss this prompt, the document gets displayed correctly. How can I get rid of the Read-only prompt?
Here is my code:
public class MyDownloadListener implements DownloadListener {
MainActivity activity;
BroadcastReceiver receiver;
DownloadManager downloadManager;
public MyDownloadListener(MainActivity a) {
activity = a;
downloadManager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
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(downloadId);
Cursor c = downloadManager.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_FILENAME));
File fileSrc = new File(uriString);
Intent intentPdf = new Intent(Intent.ACTION_VIEW);
intentPdf.setDataAndType(Uri.fromFile(fileSrc), "application/pdf");
intentPdf.setPackage("com.adobe.reader");
intentPdf.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(intentPdf);
}
}
}
}
};
activity.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
Request request = new Request(Uri.parse(url));
downloadManager.enqueue(request);
}
}
As per the official documentation of class DownloadManager.Request
This class contains all the information necessary to request a new
download. The URI is the only required parameter. Note that the
default download destination is a shared volume where the system might
delete your file if it needs to reclaim space for system use. If this
is a problem, use a location on external storage (see
setDestinationUri(Uri).
So default location is more of a cache location and system can delete the file if it require more space. So if you want to kep the file then you can use setDestinationUri to provide the path in the SD card..
And it looks like the default space does not allow any other thread/process other then the download manager to write file in that space, hence the read only message from the adobe reader..

Categories

Resources