RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 840244
Accepted
V.March
V.March
Asked:2020-06-10 21:53:47 +0000 UTC2020-06-10 21:53:47 +0000 UTC 2020-06-10 21:53:47 +0000 UTC

图像不会通过 Intent 传输到另一个 Android 应用程序

  • 772

我正在尝试从 Internet 获取图片,将其保存到我的手机中,然后通过任何信使或邮件程序立即发送,而无需打开图库来选择图片。

活动:

public class MainActivity extends AppCompatActivity {

    private String remoteUrlString = "https://upload.wikimedia.org/wikipedia/commons/b/b5/Extreme_QR_code_to_Wikipedia_mobile_page.png";
    private Button btnStart;
    private Context context;

    private static final int PERMISSIONS_REQUEST_SENDER = 14222;

    private File file = null;
    public File getFile() {
        return file;
    }
    public void setFile(File file) {
        this.file = file;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnStart = findViewById(R.id.button);
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                resendImage();
            }
        });
    }

    private void resendImage() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {

            System.out.println("PERMISSION_GRANTED == WRITE_EXTERNAL_STORAGE: true");
            Picasso.with(this)
                    .load(remoteUrlString)
                    .into(target);
            sendImg();
        } else {

            System.out.println("PERMISSION_GRANTED == WRITE_EXTERNAL_STORAGE: false");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        PERMISSIONS_REQUEST_SENDER);
            }
        }
    }

    private Target target = new Target() {

        @Override
        public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {

            new Thread(new Runnable() {
                @Override
                public void run() {

                    try {
                        file = new File(Environment.getExternalStorageDirectory().getPath() + "/Extreme_QR_code_to_Wikipedia_mobile_page.jpg");

                        FileOutputStream ostream = null;
                        ostream = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 75, ostream);
                        ostream.close();
                        galleryAddPic(file);
                        setFile(file);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {

        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
            if (placeHolderDrawable != null) {
            }
        }
    };

    private void galleryAddPic(File file) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);

        Uri contentUri = Uri.fromFile(file);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }

    private void sendImg() {

        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_STREAM, getFile());
        sendIntent.setType("image/jpg");
        startActivity(sendIntent);
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == PERMISSIONS_REQUEST_SENDER && grantResults.length == 1) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                resendImage();

            } else {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        PERMISSIONS_REQUEST_SENDER);
            }
        }
    }
}

显现:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.devtolife.myapp">
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.READ_PROFILE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="START" />

</android.support.constraint.ConstraintLayout>

When the choice of applications to send opens, the picture is not in the attachment: 在此处输入图像描述

我检查了图库 - 图片已加载并正常打开。可能是什么?

android
  • 2 2 个回答
  • 10 Views

2 个回答

  • Voted
  1. Best Answer
    Shwarz Andrei
    2020-06-11T01:35:53Z2020-06-11T01:35:53Z

    我不会通过代码,我会这样回答:

    用 FutureTask 包装你的线程将很快让你摆脱这里的标准,AsyncTask 的代码多一点,但 Rx 看起来更好。与毕加索共舞会消失,显然不是为了那个,并且在将图片写入文件结束时,您通常可以调用您的乐趣 sendImg()。为了快速检查,您可以执行以下操作:

    setFile(file);
    sendImg();
    

    虽然这很糟糕,但 startActivity 总是在 MainThread 上发布......所以它应该可以工作。

    • 2
  2. V.March
    2020-06-18T06:05:39Z2020-06-18T06:05:39Z

    使用RXJava 2.1.6和的解决方案Picasso 2.5.2。

    简而言之:
    用于Picasso将文件上传到本地存储。
    为了维护流程的顺序,我将其全部包装在RXJava2.
    在文件下载结束时,我将其传递给意图发送。
    接下来,选择您要发送此照片 的应用程序(从列表中) 。

    链接到 github:ImageResender

    代码本身的详细信息:

    清单:(注意提供者和权限)

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.devtolife.imageresender">
    
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.INTERNET" />
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
    
            <provider
                android:name="android.support.v4.content.FileProvider"
                android:authorities="${applicationId}.provider"
                android:exported="false"
                android:grantUriPermissions="true">
                <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/provider_paths" />
            </provider>
    
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    </manifest>  
    

    布局:(只需一个按钮即可开始接收和传输图片)。

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="START" />
    </android.support.constraint.ConstraintLayout>  
    

    提供者:(provider_paths.xml沿途躺着res/xml)

    <?xml version="1.0" encoding="utf-8"?>
    <paths>
        <external-path
            name="external_files"
            path="." />
    </paths>  
    

    Gradle:(包括库)。

    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'io.reactivex.rxjava2:rxjava:2.1.6'
    

    活动:
    注释: 1)14222是取自天花板的临时数字。
    2) B photoURL- 图片的链接是从互联网上任意获取的,没有宣传或冒犯任何人的目的。

    package com.devtolife.imageresender;
    
    import android.Manifest;
    import android.content.Context;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.graphics.Bitmap;
    import android.graphics.drawable.Drawable;
    import android.net.Uri;
    import android.os.Build;
    import android.os.Bundle;
    import android.os.Environment;
    import android.support.annotation.NonNull;
    import android.support.annotation.RequiresApi;
    import android.support.v4.content.ContextCompat;
    import android.support.v4.content.FileProvider;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    
    import com.squareup.picasso.Picasso;
    import com.squareup.picasso.Target;
    
    import java.io.File;
    import java.io.FileOutputStream;
    
    import io.reactivex.Observable;
    import io.reactivex.ObservableEmitter;
    import io.reactivex.ObservableOnSubscribe;
    import io.reactivex.Observer;
    import io.reactivex.disposables.Disposable;
    
    import static android.os.Environment.getExternalStoragePublicDirectory;
    
    public class MainActivity extends AppCompatActivity {
    
        private static final int PERMISSIONS_REQUEST_SENDER = 14222; // 14222 it is the fictional number.
    
        private static final String TAG = "log";
        private Button btnStart;
        private Context context;
        private String imgName;
        private String photoURL = "http://www.freepngimg.com/thumb/color_effects/1-2-color-effects-free-download-png-thumb.png"; // just for example.
    
        Uri photoUriForGalleryIndexation;
        Uri photoUri;
    
        File storageDir;
        private File imgFile = null;
    
        public File getImgFile() {
            return imgFile;
        }
    
        public void setImgFile(File imgFile) {
            this.imgFile = imgFile;
        }
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            context = getApplicationContext();
    
            btnStart = findViewById(R.id.button);
            btnStart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    getRemoteUrlString();
    
                    if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
    
                        createEmptyFile();
                        shareImage();
    
                    } else {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                    PERMISSIONS_REQUEST_SENDER);
                        }
                    }
                }
            });
        }
    
        private void getRemoteUrlString() {
    
            String nameWithExtension = Uri.parse(photoURL).getLastPathSegment();
    
            int pos = nameWithExtension.lastIndexOf(".");
            if (pos > 0)
                imgName = nameWithExtension.substring(0, pos);
            else
                imgName = nameWithExtension;
        }
    
        private void createEmptyFile() {
    
            storageDir = new File(getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "MyImages");
            if (!storageDir.exists()) {
                storageDir.mkdirs();
                storageDir = new File(getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "MyImages");
            }
    
            setImgFile(new File(storageDir + "/" + imgName + ".jpg"));
    
            createPhotoUriForIndexation(getImgFile());
            createPhotoUriForSharing(getImgFile());
        }
    
        private void createPhotoUriForIndexation(File fileIndex) {
    
            String contentPathString = "imgFile:" + fileIndex.getAbsolutePath();
            photoUriForGalleryIndexation = Uri.parse(contentPathString);
    
        }
    
        private void createPhotoUriForSharing(File fileShare) {
    
            if (Build.VERSION.SDK_INT <= 19) {
                photoUri = Uri.fromFile(fileShare);
            } else {
                photoUri = FileProvider.getUriForFile(getApplicationContext(),
                        BuildConfig.APPLICATION_ID + ".provider", fileShare);
            }
        }
    
        private void shareImage() {
    
            Observable<File> observable = Observable
                    .create(new ObservableOnSubscribe<File>() {
                                @Override
    
                                public void subscribe(final ObservableEmitter<File> emitt) {
    
                                    Picasso.with(context).load(photoURL)
                                            .into(new Target() {
    
                                                @Override
                                                public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
    
                                                    try {
    
                                                        FileOutputStream ostream = new FileOutputStream(getImgFile());
                                                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
    
                                                        if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream)) {
                                                            galleryAddPic();
                                                            emitt.onComplete();
                                                        } else {
                                                            emitt.onNext(getImgFile());
                                                        }
                                                        ostream.close();
    
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                    }
                                                }
    
                                                @Override
                                                public void onBitmapFailed(Drawable errorDrawable) {
                                                }
    
                                                @Override
                                                public void onPrepareLoad(Drawable placeHolderDrawable) {
                                                }
                                            });
                                }
                            }
                    );
    
    
            Observer<File> observer = new Observer<File>() {
                @Override
                public void onSubscribe(Disposable d) {
                    Log.e(TAG, "onSubscribe: ");
                }
    
                @Override
                public void onNext(File value) {
                    Log.e(TAG, "onNext: ");
                }
    
                @Override
                public void onError(Throwable e) {
                    Log.e(TAG, "onError: ");
                }
    
                @Override
                public void onComplete() {
                    Log.e(TAG, "onComplete: All Done!");
                    sendImg();
                }
            };
    
            observable.subscribe(observer);
        }
    
        private void galleryAddPic() {
            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            mediaScanIntent.setData(photoUriForGalleryIndexation);
            this.sendBroadcast(mediaScanIntent);
    
        }
    
        private void sendImg() {
    
            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_STREAM, photoUri);
            sendIntent.setType("image/jpg");
            startActivity(sendIntent);
        }
    
        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                               @NonNull int[] grantResults) {
            if (requestCode == PERMISSIONS_REQUEST_SENDER && grantResults.length == 1) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    
                    createEmptyFile();
                    shareImage();
    
                } else {
                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            PERMISSIONS_REQUEST_SENDER);
                }
            }
        }
    }
    

    也许这会为某人节省几个小时。

    • 1

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    是否可以在 C++ 中继承类 <---> 结构?

    • 2 个回答
  • Marko Smith

    这种神经网络架构适合文本分类吗?

    • 1 个回答
  • Marko Smith

    为什么分配的工作方式不同?

    • 3 个回答
  • Marko Smith

    控制台中的光标坐标

    • 1 个回答
  • Marko Smith

    如何在 C++ 中删除类的实例?

    • 4 个回答
  • Marko Smith

    点是否属于线段的问题

    • 2 个回答
  • Marko Smith

    json结构错误

    • 1 个回答
  • Marko Smith

    ServiceWorker 中的“获取”事件

    • 1 个回答
  • Marko Smith

    c ++控制台应用程序exe文件[重复]

    • 1 个回答
  • Marko Smith

    按多列从sql表中选择

    • 1 个回答
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Suvitruf - Andrei Apanasik 什么是空? 2020-08-21 01:48:09 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5