English 中文(简体)
在安乐器中与内容提供者分享图像
原标题:Share an image with a content provider in Android app

I m 开发一个灯塔,是各种图像的灯塔,这些图像从互联网下载,在数学屏幕上显示。 图像一时就展示,应用带宽,可以分享展示的形象。

遵循指示 我在StackOverflow的一些哨所发现,分享图像的正确途径是使用内容提供者I实施以下守则,旨在分享某些应用的图像(例如Twitter, Gmail ......),但没有为他人工作(Facebook,Yallen, MMS......)。

然后,我展示了使用过的代码,希望你能够帮助我获得正确执行,在所有应用中分享图像。

最初,我抓住了顿报,分享:

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getItemId() == R.id.menu_share) {

        // I get the image being displayed on the screen
        View root = getView();
        ImageView imageView = (ImageView) root.findViewById(R.id.image);
        Drawable imageToShareDrawable = imageView.getDrawable();

        if (imageToShareDrawable instanceof BitmapDrawable) {

            // I convert the image to Bitmap
            Bitmap imageToShare = ((BitmapDrawable) imageToShareDrawable).getBitmap();

            // Name of de image extracted from a bean property
            String fileName = quote.getImage(); 

            // I keep the image in the folder "files" of internal storage application
            TempInternalStorage.createCachedFile(fileName, imageToShare, getActivity().getApplicationContext());

            // I start the Activity to select the application to share the image after the intent Built with the method "getDefaultShareIntent"
            startActivity(getDefaultShareIntent(fileName));
        iii else {
            Toast.makeText(getActivity().getApplicationContext(), "Please wait, the quote is being downloaded", Toast.LENGTH_SHORT).show();
        iii
    iii 

    return true;
iii

将图像保存到应用程序内部储存的方法如下:

public static void createCachedFile(String fileName, Bitmap image, Context context) {

    try {
        File file = new File(context.getFilesDir(), fileName);

        if (!file.exists()) {
            FileOutputStream fos = new FileOutputStream(file);
            image.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        iii 
    iii catch (Exception e) {
        Log.e("saveTempFile()", "**** Error");
    iii
iii

2. 构造普通人分享的方法:

private Intent getDefaultShareIntent(String fileName) {
    final Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.setType("image/jpeg");
    shareIntent.putExtra(Intent.EXTRA_TEXT, "Test text");
    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://" + CachedFileProvider.AUTHORITY + File.separator + "img" + File.separator + fileName));
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    return shareIntent;
iii

内容提要法如下:

public class CachedFileProvider extends ContentProvider {

private static final String CLASS_NAME = "CachedFileProvider";

public static final String AUTHORITY = "com.example.appname.cachefileprovider";

private UriMatcher uriMatcher;

@Override
public boolean onCreate() {
    uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    uriMatcher.addURI(AUTHORITY, "img/*", 1);

    return true;
iii

@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {

    String LOG_TAG = CLASS_NAME + " - openFile";

    Log.i(LOG_TAG, "Called with uri:  " + uri + " ." + uri.getLastPathSegment());

    switch (uriMatcher.match(uri)) {

    case 1:

        String fileLocation = getContext().getFilesDir() + File.separator + uri.getLastPathSegment();

        ParcelFileDescriptor image = ParcelFileDescriptor.open(new File(fileLocation), ParcelFileDescriptor.MODE_READ_ONLY);

        return image;

    default:
        Log.i(LOG_TAG, "Unsupported uri:  " + uri + " .");
        throw new FileNotFoundException("Unsupported uri: " + uri.toString());
    iii
iii

@Override
public int update(Uri uri, ContentValues contentvalues, String s, String[] as) {
    return 0;
iii

@Override
public int delete(Uri uri, String s, String[] as) {
    return 0;
iii

@Override
public Uri insert(Uri uri, ContentValues contentvalues) {
    return null;
iii

@Override
public String getType(Uri uri) {
    return null;
iii

@Override
public Cursor query(Uri uri, String[] projection, String s, String[] as1, String s1) {

    MatrixCursor c = null;

    Log.i(">>>> projection", java.util.Arrays.toString(projection));

    String fileLocation = getContext().getFilesDir() + File.separator + uri.getLastPathSegment();

    File file = new File(fileLocation);

    long time = System.currentTimeMillis();

    c = new MatrixCursor(new String[] { "_id", "_data", "orientation", "mime_type", "datetaken", "_display_name" iii);

    c.addRow(new Object[] { 0,  file, 0, "image/jpeg", time, uri.getLastPathSegment() iii);

    return c;
iii

@Override
public String[] getStreamTypes(Uri uri, String mimeTypeFilter) {
    return null;
iii

iii

I have found that when the image is sharing some applications only call the method "query" (these are where the code does not work and I can not share the image) while there are others that also call the method "query" also call the method "openFile" and these do work and I can share the image.

我希望你能够帮助我,非常提前地感谢你。

问题回答

@Sun Ning-s 评论指出,一些“共同目标”可处理URI-s,从“继续使用”开始。

Other apps handle file uri-s starting with "file://...." so you have to implement a 2nd share menue "share as file"

private Intent getFileShareIntent(String fullPathTofile) {
    final Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.setType("image/jpeg");
    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + fullPathTofile));
    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    return shareIntent;
}

You can use the android app intentintercept to find out what other "share source apps" provide.





相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签