Open Image from assets using external program - java

I've wrote content provider to open a png file in my app package with an external application (standard image viewer of Android). Image is stored in asset folder.
I cannot understand where is a problem, but it doesn't work for me.
openFile of ContentProvider:
#Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
URI file_uri = URI.create("file:///data/data/com.package/assets/image.png");
File file = new File(file_uri.getPath());
ParcelFileDescriptor parcel = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
return parcel;
}
Starting activity:
Uri uri = Uri.parse("file:///android_asset/image.png");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
Is this approach correct and where is my mistake? Or am I totally wrong?

The new Activity doesn't have access to your internal assets directory. You can either put the image on the sdcard or use your own ImageView that is part of your application.

Related

How to download and immediately open this file in another application

Good day. I am creating an application that downloads a file from firebase. Next, this file will have to open in the application that is installed in advance on the phone. How can I find this file after installation and open it in a new application. Thanks for any answer. sorry for my English
Download code:
public void downloadFiles(Context context, String fileName, String fileExtension, 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, destinationDirectory, fileName + fileExtension);
downloadManager.enqueue(request);
What i tried.
open code:
public void openFile() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("file/*");
File download = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"king.mcpack");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(download));
startActivity(Intent.createChooser(intent, "Open with"));
}

Display photo from FileProvider with Intent.ACTION_VIEW

I am working on a device running Android 8.1.0. I'm trying to open an image from a message attachment. I had a cache of image files working using a FileProvider a week ago and now it just stopped working without me touching the code. I'm trying to share an image from my internal app storage to Intent.ACTION_VIEW outside of my app. The photo viewer does launch, but there's a progress circle that just keeps spinning. Any suggestions? Thanks!
void launchViewer(File f) {
Uri uri = FileProvider.getUriForFile(context, "com.company.secure.provider", f);
Intent intent = new Intent(Intent.ACTION_VIEW);
String mimeType = Attachment.getMimeType(f.getName());
//TODO Test to make sure this works on all devices...
if (mimeType.startsWith("video")) {
mimeType = "video/*";
}
if (mimeType.startsWith("image")) {
mimeType = "image/*";
}
if(mimeType==null || mimeType.length()==0) {
unknownMimeType(f.getName());
return;
}
List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if(resInfoList==null || resInfoList.size()==0)
{
AlertDialog dialog = new AlertDialog.Builder(context).setTitle("Error")
.setMessage(String.format("Cannot find app to open file type(%s)",mimeType)).show();
return;
}
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
context.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
intent.setDataAndType(uri, mimeType);
context.startActivity(intent);
}
So I just had to add the following line right before starting the activity.
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
For some reason, the APK I shipped to testing that doesn't have this line in it works... but any new build does not work without this. I read that using the ResolveInfo method will only work for Lollipop and below and you will have to grant the permission directly to the intent. (Not sure how true this is). For this reason I left both permission granting methods in there to cover all bases. Thanks for all the help!

Loading PDF from internal storage Error invalid format

So I've been practising download manager and i was trying out some program.
A first button will download a said Pdf to a location in my phone.
The second button is supposed to open the Pdf file with a Pdf reader installed by the user such as WP Reader etc..
The download works fine, but when i open the pdf , it says invalid format.
I uploaded a sample Pdf to the google drive , so I know that the uploaded file isnt corrupted in any case. There muse be some problem when the file is being downloaded from the server. Please help me find the mistake. And I am relatively new to Android.
And the download button uses an Onclicklistener while the loadPdf is given in the xml file android:onClick="downloadPdf" .
public class MainActivity extends AppCompatActivity {
String myHTTPUrl = "https://drive.google.com/open?id=0B5Pev9zz5bVjZTFFZ1dLZVp1WVU";
String TAG = "My app";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button download = (Button) findViewById(R.id.download);
download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG,"download method called");
downloadPdf();
Toast.makeText(MainActivity.this,"Listener Called",Toast.LENGTH_SHORT).show();
Log.v(TAG,"On Click Listener Called");
}
});
}
public void loadPdf(View view) {
Log.v(TAG,"Pdf load called");
File pdfFile = new File(Environment.getExternalStorageDirectory()+"/notes","ssp.pdf");
if(pdfFile.exists())
{
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Intent intent = Intent.createChooser(pdfIntent, "Open File");
try
{
startActivity(intent);
}
catch(ActivityNotFoundException e)
{
Toast.makeText(MainActivity.this, "No Application available to view pdf", Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(MainActivity.this,"Pdf not found",Toast.LENGTH_SHORT).show();
}
}
public void downloadPdf()
{
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myHTTPUrl));
request.setTitle("Solid State Physics");
request.setDescription("File is being Downloaded...");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir("/notes","ssp.pdf");
manager.enqueue(request);
}}
EDITED :
This is the exact error I'm facing with screenshot
Error : File format error , Cannot be opened
Screenshot of the error.
You're not downloading the PDF, you're downloading the web-page displaying the contents of the PDF. If you want to download the PDF file directly, use the following URL:
String myHTTPUrl = "https://drive.google.com/uc?export=download&id=0B5Pev9zz5bVjZTFFZ1dLZVp1WVU";
and your application should work.
(Don't forget to delete the invalid notes/ssp.pdf file first, otherwise the DownloadManager will download the file under a different name, like notes/ssp-1.pdf.)

Open built in gallery app with an album

How to open inbuilt gallery app with a specific album opened on screen ?
I know this code can be used for launching gallery app , but how to filter a specific album ? or open it ?
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
Assume your photos ares stored at youCam folder or it can be any folder
If you are compiling against API 23 or Greater then get runtime permision READ_EXTERNAL_STORAGE
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/youCam);
File[] listFile = file.listFiles();
new HomeScreen.SingleMediaScanner(HomeScreen.this, listFile[0]);
...
public class SingleMediaScanner implements MediaScannerConnection.MediaScannerConnectionClient {
private MediaScannerConnection mMs;
private File mFile;
public SingleMediaScanner(Context context, File f) {
mFile = f;
mMs = new MediaScannerConnection(context, this);
mMs.connect();
}
public void onMediaScannerConnected() {
mMs.scanFile(mFile.getAbsolutePath(), null);
}
public void onScanCompleted(String path, Uri uri) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
mMs.disconnect();
}
}
This will open you all images in that folder in default gallery.

Homescreen shortcuts with icons

Am trying to create a homescreen shortcut programmatically on android. So far I've been able to add the shortcut itself with the following code:
Intent shortcutIntent = new Intent();
shortcutIntent.setClassName(mContext, mContext.getClass().getName());
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
shortcutIntent.putExtra("someParameter", "HelloWorld 123");
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Shortcut Name 123");
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, R.drawable.icon);
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
mContext.sendBroadcast(addIntent);
But, the shortcut is installed using the default icon in my resources. However, I would like to fetch icons from my website and adding an icon to the shortcut.
First, I need to download this shortcut. Under the assumption that I have this done, and the icon is on the sdcard for example, I have been unable to set an drawable icon.
The following code:
try {
Uri contentURI = Uri.parse("http://mnt/sdcard/mytest/test.png");
ContentResolver cr = mContext.getContentResolver();
InputStream in;
in = cr.openInputStream(contentURI);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize=8;
Bitmap thumb = BitmapFactory.decodeStream(in,null,options);
Intent shortcutIntent = new Intent();
shortcutIntent.setClassName(mContext, mContext.getClass().getName());
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
shortcutIntent.putExtra("someParameter", "HelloWorld 123");
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Shortcut Name 123");
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, thumb);
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
mContext.sendBroadcast(addIntent);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
The file definitely exist and I've verified that using adb shell... This piece of code shows the following error:
10-13 16:11:31.184: WARN/System.err(23273): java.io.FileNotFoundException: No content provider: /mnt/sdcard/mytest/test.png
What am I doing wrong?
Thanks
You are trying to get bitmap from local resources (by using content provider).
To download Bitmap from server you should follow this:
Why is this image bitmap not downloading in Android?
It seems like your application unable to access test.png. Make sure it exists. Maybe you can start with local storage rather than sd card.

Categories

Resources