共享失败,请重试(仅适用于WhatsApp)。

7
当我分享内容到WhatsApp时,它会返回分享页面并显示提示通知“分享失败,请重试”。
我的代码:
if (url.startsWith("share://")) {
            Uri requestUrl = Uri.parse(url);
            String pContent = requestUrl.toString().split("share://")[1];
            Toast toast=Toast.makeText(getApplicationContext(),pContent, Toast.LENGTH_LONG);
            toast.setMargin(50,50);
            toast.show();
            StringBuilder sb = new StringBuilder();
            String [] parts = pContent.split("<br />");
            for (int i = 0; i < parts.length; i++) {
                String part = parts[i];
                sb.append(part);
                sb.append('\n');
            }
            Intent share = new Intent();
            share.setAction(Intent.ACTION_SEND);
            share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            share.putExtra(android.content.Intent.EXTRA_TEXT, (Serializable) sb);
            share.setType("*/*");
            try {
            startActivity(Intent.createChooser(share, "Share On"));
            } catch (android.content.ActivityNotFoundException ex) {
                toast = Toast.makeText(getApplicationContext(), "whatsapp not installed", Toast.LENGTH_LONG);
                toast.setMargin(50,50);
                toast.show();
            }
            return true;

和我的日志记录

08-01 14:37:42.081 1472-1514/com.example.myactivity I/MaliEGL: [Mali]window_type=1, is_framebuffer=0, errnum = 0
08-01 14:37:42.081 1472-1514/com.example.myactivity I/MaliEGL: [Mali]surface->num_buffers=4, surface->num_frames=3, win_min_undequeued=1
08-01 14:37:42.081 1472-1514/com.example.myactivity I/MaliEGL: [Mali]max_allowed_dequeued_buffers=3

除 WhatsApp 外,它适用于其他应用程序,如 Hangout、邮件、Hike、文本等。我的编译 SDK 和目标 SDK 均为 23,在 Android One 物理设备上进行测试。 - Shubham
嗨,Harry,到目前为止有什么解决方案吗? - Rishabh Bhatia
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Shubham
在我的例子中,我使用了错误的示例代码intent.setType("plain/text"),而应该使用intent.setType("text/plain") [参见] (https://faq.whatsapp.com/en/android/28000012)。 - Style-7
5个回答

8

我也遇到了同样的问题 - 解决方法是定义MIME类型:当尝试共享一个包含文本和附加图片的意图时,设置sharingIntent.setType("*/*")将会很好地工作,但是在分享只有文本时会失败,如上所述。

解决方案:如果只共享文本,则设置sharingIntent.setType("text/plain")

public void sendShareToWhatsAppIntent() {

    //setup intent:
    Intent sharingIntent = new Intent(Intent.ACTION_SEND);

    //setup image extra, if exists:
    Bitmap picBitmap = getMyBitmap();
    if (picBitmap != null) {
        String url = MediaStore.Images.Media.insertImage(context.getContentResolver(), picBitmap, "", "");
        sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));
        sharingIntent.setType("*/*");
    } else {
    //if no picture, just text set - this MIME
        sharingIntent.setType("text/plain");
    }

    //setup sharing message
    String message = "My Message - hey whatsapp!"

    sharingIntent.putExtra(Intent.EXTRA_TEXT, message.toString());

   //target WhatsApp:
   sharingIntent.setPackage("com.whatsapp");


    if (sharingIntent.resolveActivity(context.getPackageManager()) != null) {
        startActivity(sharingIntent);
    } else {
        Log.w(TAG, "sendShareIntent: cant resolve intent");
        Toast.makeText(context, "whatsapp not installed", Toast.LENGTH_SHORT).show();
    }

}

1

share.setType("text/plain");并重试。


虽然这是一个答案,但最好解释一下为什么你认为这是解决问题的方法。 - Gert Arnold
1
因为我遇到了同样的问题,只需添加settype("text/plain")即可解决。 - Nikul Vaghani

0

这是我的方法。

private fun openShareDialog(iC: Context, //
                            iPath: String)
{
    MediaScannerConnection.scanFile( //
            iC.applicationContext, //
            arrayOf(iPath), null //
    ) { _, iUri ->
        var shareIntent = Intent(Intent.ACTION_SEND).apply {
            putExtra(Intent.EXTRA_STREAM, iUri)
            type = "image/*"
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            putExtra(Intent.EXTRA_TEXT, iC.getString(R.string.screenshot_sharing_text))
        }

        shareIntent = Intent.createChooser(shareIntent, iC.resources.getText(R.string.send_to)) //
                .apply {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                }

        iC.startActivity(shareIntent)
    }
}

这适用于图像共享以及视频共享(只需不要忘记将type更改为(例如)video/*

如果您需要将共享用作Pending Intent(例如作为通知中的操作按钮),则可以使用此类

它是适用的

class ShareScreenshotService : IntentService(SHARE_VIDEO_RECORD_SERVICE)
{
    override fun onCreate()
    {
        super.onCreate()
        startService(Intent(this, ShareScreenshotService::class.java))
    }

    override fun onHandleIntent(intent: Intent?)
    {
        if (intent != //
            null && intent.hasExtra(EXTRA_SHARE_VIDEO_RECORD_PATH))
        {
            val path = intent.getStringExtra(EXTRA_SHARE_VIDEO_RECORD_PATH)
            Logger.log(Log.ERROR, TAG, path!!)

            openShareDialog(this, path)

            PushNotificationManager.getInstance(this).getVideoRecordingNotificator(this).closeNotification()
        }
    }

    private fun openShareDialog(iC: Context, //
                                iPath: String)
    {
        MediaScannerConnection.scanFile( //
                iC.applicationContext, //
                arrayOf(iPath), null //
        ) { _, iUri ->
            var shareIntent = Intent(Intent.ACTION_SEND).apply {
                putExtra(Intent.EXTRA_STREAM, iUri)
                type = "image/*"
                addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                putExtra(Intent.EXTRA_TEXT, iC.getString(R.string._screenshot_sharing_text))
            }

            shareIntent = Intent.createChooser(shareIntent, iC.resources.getText(R.string._send_to)) //
                    .apply {
                        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    }

            iC.startActivity(shareIntent)
        }
    }

    companion object
    {
        private val TAG = ShareScreenshotService::class.java.simpleName
        private const val SHARE_VIDEO_RECORD_SERVICE_REQUEST_CODE = 3

        const val EXTRA_SHARE_VIDEO_RECORD_PATH = "_extra_share_video_record_path"
        const val SHARE_VIDEO_RECORD_SERVICE = "_share_video_record_service"

        @JvmStatic
        fun pendingIntent(context: Context, //
                          iPath: String): PendingIntent
        {
            val intent = Intent(context, ShareScreenshotService::class.java)
            intent.putExtra(EXTRA_SHARE_VIDEO_RECORD_PATH, iPath)

            return PendingIntent.getService( //
                    context, //
                    SHARE_VIDEO_RECORD_SERVICE_REQUEST_CODE, //
                    intent, //
                    PendingIntent.FLAG_UPDATE_CURRENT //
            )
        }
    }
}

使用方法

NotificatonBuilder.addAction(R.drawable.ic_share, iC.getString(R.string.share), ShareScreenshotService.pendingIntent(iC, iImagePath))

同时别忘了将Service添加到清单文件


0

我曾经遇到过这个问题,后来找到了适合我的正确答案。你只需要提供者。

在 Android 8.0 及以上版本中,您无法使用 Uri uri5 = Uri.parse(myuri) 获取 URI,您需要在应用程序中使用文件提供程序来获取文件的 URI,还需要将 Intent.FLAG_GRANT_READ_URI_PERMISSION 添加到共享意图中,然后第三方应用程序才能访问该文件。

例如:res->xml->provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
</paths>

创建一个虚拟类,该类扩展 FileProcider,在我们的情况下是 GenericFileProvider.java。
import android.support.v4.content.FileProvider;
public class GenericFileProvider extends FileProvider {
}

在你的 manifest.xml 文件中,在 application 标签内添加以下代码行。
<provider
            android:name=".GenericFileProvider"
            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>

现在,您可以在应用程序中使用以下代码获得文件的Uri。
Uri screenshotUri = FileProvider.getUriForFile(SelectedImageActivity1.this, getApplicationContext().getPackageName() + ".provider", file);

"

参考资料:solution


是的,@blackgreen,你说得对,但我想引用这个解决方案,如果引用被删除或编辑了,应该有一个旧版本的解决方案。这个解决方案帮助了我,希望也能帮助其他人。感谢你的评论。 - Begmyrat Mammedov

-1
在我的设备上,Android 6.0以下的版本都可以正常工作。但是在Android 6.0上出现了问题,原因是用户没有授予外部存储权限。现在,在启动共享意图之前,请检查外部存储权限...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接