Launch intent viewer to display image from url

2019-04-08 07:56发布

I have the url of an image. What i need to do is launch the default image viewer for images using an intent.

I tried launching it by using:

Uri uri = Uri.parse("http://www.google.com/intl/en_ALL/images/srpr/logo1w.png");  
Intent it = new Intent(Intent.ACTION_VIEW);
it.setDataAndType(uri, "image/*")
startActivity(it);

But it doesn't work. If I do not specify the type of data, the intent launches the browser since the data is a url. It works basically (since you can see the image on the browser) but what I would like is to have the gallery display the image for me.

I can also download the image into a Bitmap but I would still not know how to display the Bitmap using the gallery (if that's even possible). Any ideas?

EDIT: I tried saving the bitmap to the cache and then launch the viewer on that file but it doesn't work. Can you spot any mistakes on my code? (The Utilities class is a class i wrote. The method simply creates the Bitmap. It works, that's not the problem)

File temp = File.createTempFile("tempImage", ".jpg", getContext().getCacheDir());
Bitmap bmp = Utilities.loadBitmap(largeUrl.toString());
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(temp));
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.close();
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(temp), "image/jpg");
((Activity) getContext()).startActivity(intent);

EDIT 2: I decided that i may need the downloaded images after all so i decided to first save them on the sd card. That created other problems. I asked a new question for that since it is a different problem.

3条回答
爷的心禁止访问
2楼-- · 2019-04-08 08:42

You can try this code for gridview onItemClickListner to show in default gallery App

OnItemClickListener myOnItemClickListener = new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,

        Intent it = new Intent(Intent.ACTION_VIEW);
        it.setDataAndType(Uri.parse("file://" + (String) parent.getItemAtPosition(position)), "image/*");
        startActivity(it);
    }
};

this is work for me :)

查看更多
啃猪蹄的小仙女
3楼-- · 2019-04-08 08:55

Your code is fine but you need to save the image on the sd card ("temp" File) for the photo viewer to work. Tested on 1.5, 1.6, 2.1.

查看更多
戒情不戒烟
4楼-- · 2019-04-08 09:01

Perhaps the gallery requires that the image is saved to memory.

Why not download the image into a bitmap and then save that as a file, then fire up the image intent on that file?

(If you don't want the file to stick around afterwards, you could just save it in your app data directory)

查看更多
登录 后发表回答