在各种版本的Android中发生共享文本和图像错误时

时间:2012-12-16 07:49:12

标签: java android android-intent share

代码编写如下:

        final Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("*/*");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Intent.EXTRA_SUBJECT, subject.toString());
        intent.putExtra(Intent.EXTRA_TEXT, text.toString());
        intent.putExtra(Intent.EXTRA_STREAM, "file://" + path);

         startActivityForResult(
                Intent.createChooser(intent, title.toString()), REQUEST_CODE);

结果如下

  1. API 10:工作
  2. API 14:错误

2 个答案:

答案 0 :(得分:2)

使用此方法与文本共享照片。调用此方法并传递参数nameofapp和imagepath。应用程序名称意味着您要分享的内容,如gmail,facebook,twitter。

private void share(String nameApp, String imagePath) {
    try
    {
        List<Intent> targetedShareIntents = new ArrayList<Intent>();
        Intent share = new Intent(android.content.Intent.ACTION_SEND);
        share.setType("image/jpeg");
        List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(share, 0);
        if (!resInfo.isEmpty()){
            for (ResolveInfo info : resInfo) {
                    Intent targetedShare = new Intent(android.content.Intent.ACTION_SEND);
                    targetedShare.setType("image/jpeg"); // put here your mime type
                    if (info.activityInfo.packageName.toLowerCase().contains(nameApp) || info.activityInfo.name.toLowerCase().contains(nameApp)) {
                        targetedShare.putExtra(Intent.EXTRA_SUBJECT, "Text");
                        targetedShare.putExtra(Intent.EXTRA_TEXT,"This photo is created by APP");
                        targetedShare.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(imagePath)) );
                        targetedShare.setPackage(info.activityInfo.packageName);
                        targetedShareIntents.add(targetedShare);
                    }
                }
                Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), "Select app to share");
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
                startActivity(chooserIntent);
        }
    }
    catch(Exception e){
    }
 }

使用它: -

try {
    File filePath = "/mnt/sdcard/vmphoto.jpg"; //This is imagefile path in your change it acc. to your requirement.
    share("facebook",filePath.toString());

}
catch(Exception e) {
           //exception occur might your app like gmail , facebook etc not installed or not working correctly.
}

答案 1 :(得分:1)

final Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("*/*");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject.toString());
    intent.putExtra(Intent.EXTRA_TEXT, text.toString());
    intent.putExtra(Intent.EXTRA_STREAM,
            Uri.fromFile(new File("/" + path)));