简体   繁体   English

如何通过Android应用程序在谷歌加分享图像?

[英]How to share image in google Plus through an android app?

I have already tried this code, but i didn't saw photo shared in my account. 我已经尝试过此代码,但我没有在帐户中看到共享照片。

File file = new File("sdcard/1346249742258.jpg");
String photoUri = null;
photoUri = file.getAbsolutePath();

Intent shareIntent = ShareCompat.IntentBuilder.from(this)
        .setText("Sharing an image on Google!").setType("image/jpeg")
        .setStream(Uri.parse(photoUri)).getIntent()
        .setPackage("com.google.android.apps.plus");
startActivity(shareIntent);

The Google+ app only supports content:// URIs . Google+应用仅支持内容:// URI You will need to use the MediaStore API for this purpose. 您需要使用MediaStore API来实现此目的。

 File tmpFile = new File("/path/to/image");
 final String photoUri = MediaStore.Images.Media.insertImage(
         getContentResolver(), tmpFile.getAbsolutePath(), null, null);

 Intent shareIntent = ShareCompat.IntentBuilder.from(this)
         .setText("Hello from Google+!")
         .setType("image/jpeg")
         .setStream(Uri.parse(photoUri))
         .getIntent()
         .setPackage("com.google.android.apps.plus");

Integrate ForGooglePlus Activity in your code and put URL(imageUrl) ,Description(description text) and contentUrl(URL) for the same. 在代码中集成ForGooglePlus Activity,并为其添加URL(imageUrl),Description(描述文本)和contentUrl(URL)。 Note : bellow code also worked in my app. 注意:波纹管代码也适用于我的应用程序。

public class ForGooglePlus extends Activity
{
    private String imageUrl, description, contentUrl;
    private Context mContext;
    private int REQUEST_FOR_GOOGLE_PLUS = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        mContext = this;
        imageUrl = getIntent().getStringExtra("URL");
        description = getIntent().getStringExtra("Description");
        contentUrl = getIntent().getStringExtra("contentUrl");

        if (isPackageInstalled("com.google.android.apps.plus", mContext)) {
            if (imageUrl == null) {
                imageUrl = "";
            }
            if (description == null) {
                description = "";
            }
            // Intent shareIntent = new PlusShare.Builder(this)
            // .setType("image/jpeg")
            // .setText(description)
            // .setStream(getUriFromUrl(imageUrl))
            // .setContentUrl(Uri.parse(contentUrl))
            // .getIntent();

            Uri uri = getUriFromUrl(imageUrl);
            if (uri != null) {
                Intent shareIntent = ShareCompat.IntentBuilder
                        .from(ForGooglePlus.this)
                        .setText(description + "\n" + contentUrl)
                        .setType("image/jpeg").setStream(uri).getIntent()
                        .setPackage("com.google.android.apps.plus");
                startActivityForResult(shareIntent, REQUEST_FOR_GOOGLE_PLUS);
            } else {
                Intent shareIntent = ShareCompat.IntentBuilder
                        .from(ForGooglePlus.this)
                        .setText(description + "\n" + contentUrl)
                        .setType("image/jpeg").getIntent()
                        .setPackage("com.google.android.apps.plus");
                startActivityForResult(shareIntent, REQUEST_FOR_GOOGLE_PLUS);
            }
        } else {
            Toast.makeText(mContext, "Application not found", Toast.LENGTH_LONG)
                    .show();
            finish();
        }
    }

    public Uri getUriFromUrl(String thisUrl) {
        try {

            Bitmap inImage = ImageLoader.getInstance().loadImageSync(thisUrl);
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            String path = Images.Media.insertImage(
                    mContext.getContentResolver(), inImage, "Title", null);
            return Uri.parse(path);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();

        }
        return null;
    }

    private boolean isPackageInstalled(String packagename, Context context) {
        PackageManager pm = context.getPackageManager();
        try {
            pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
            return true;
        } catch (NameNotFoundException e) {
            return false;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_FOR_GOOGLE_PLUS) {
            if (resultCode == RESULT_OK) {
                finish();
            } else {
                Toast.makeText(mContext,
                        mContext.getString(R.string.msg_gp_cancel),
                        Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }

}

I am also posting image on google plus through android using intent i am taking screen shot of device and posting it on google plus, i used your code i am getting exception FileNotFoundException() and as you mention to use absolute path i got error, The method getAbsolutePath() is undefined for the type String my code is given below please suggest me correction in code 我也在谷歌上发布图像加上通过Android使用意图我正在拍摄设备的屏幕截图并将其发布在谷歌加上,我使用你的代码我得到异常FileNotFoundException()并且当你提到使用绝对路径我得到错误,方法getAbsolutePath()未定义类型String我的代码如下所示,请建议我修改代码

    package com.testproject;


    import java.io.File;
    import java.io.FileNotFoundException;

    import android.app.Activity;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.net.Uri;
    import android.os.Bundle;
    import android.provider.MediaStore;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.RelativeLayout;

    public class TestProjectActivity extends Activity {

        private Button share_btn = null; 
        private String url=null;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            share_btn = (Button)findViewById(R.id.share_btn);
            share_btn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    Intent intent=new Intent(TestProjectActivity.this,ShareDialogActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);    
                    startActivityForResult(intent, 1);  
                }
            });
        }
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            String url =takeScreenShot();
            super.onActivityResult(requestCode, resultCode, data);
            switch (resultCode) {
            case 1:
                String share = data.getExtras().getString("NAME");
                if(share!=null && share.equalsIgnoreCase("Share with Instagram")){
                    Intent i = new Intent(Intent.ACTION_SEND);
                    i.setType("image/jpg");
                    i.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));
                    startActivity(Intent.createChooser(i, "Share Image"));
                }

                if(share!=null && share.equalsIgnoreCase("Share with GooglePlus")){
                    Intent shareIntent = new Intent(Intent.ACTION_SEND);
                    File tmpFile = new File(url);
                    String photoUri=null;
                    photoUri = url.getAbsolutePath();
                    try {
                        photoUri = MediaStore.Images.Media.insertImage(
                                getContentResolver(), tmpFile.getAbsolutePath(), null, null);
                        shareIntent = ShareCompat.IntentBuilder.from(this)
                        .setText("Hello from Google+!")
                        .setType("image/jpeg")
                        .setStream(Uri.parse(photoUri))
                        .getIntent()
                        .setPackage("com.google.android.apps.plus");
                        startActivity(shareIntent);
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                break;
            }
        }
        public String takeScreenShot(){
            try{
                RelativeLayout  view = (RelativeLayout)findViewById(R.id.icflag_layout);
                View v1 = view.getRootView();
                System.out.println("Root View : "+v1);
                v1.setDrawingCacheEnabled(true);
                Bitmap bm = v1.getDrawingCache();
                url =MediaStore.Images.Media.insertImage(getContentResolver(), bm,"screeshot.jpg", 1233+ ".jpg Card Image");
            }
            catch(OutOfMemoryError e){

            }
            return url;
        }
    }

Thank you and regards Nitin 谢谢你,并对Nitin表示感谢

Don't use absolute path. 不要使用绝对路径。

OnActivityResult() use this after capturing image from camera. OnActivityResult()在从相机捕获图像后使用此功能。

Uri photoUri = intent.getData();                
Intent shareIntent = ShareCompat.IntentBuilder.from(this)
                         .setText("Hello From Google+!")
                             .setType("image/jpeg")
                             .setStream(photoUri)
                             .getIntent()
                     .setPackage("com.google.android.apps.plus");
startActivity(shareIntent);

This is working for me. 这对我有用。

HEy Deepika you are getting file nor found exception because that google plus app is not present on the device the way you have coded is just to start the native app from the device HEy Deepika您收到文件或发现异常,因为您编码的方式设备上没有google plus应用程序只是为了从设备启动本机应用程序

it will work only if the native ap is actully present 它只有在本机ap存在的情况下才有效

otherway is to have google plus sdk which is small jar file with that you can share image 另外就是要谷歌加sdk这是一个小jar文件,你可以共享图像

https://developers.google.com/+/mobile/android/ https://developers.google.com/+/mobile/android/

You can share image using below api's. 您可以使用以下api分享图像。 For detailed steps check tutorial 详细步骤检查教程

http://androidsrc.net/integrating-google-plus-sign-in-into-your-android-application/ http://androidsrc.net/integrating-google-plus-sign-in-into-your-android-application/

 /**
     * API to process media post request start activity with MIME type as video
     * and image
     */
    private void processShareMedia() {
        Intent photoPicker = new Intent(Intent.ACTION_PICK);
        photoPicker.setType("video/*, image/*");
        startActivityForResult(photoPicker, PICK_MEDIA_REQUEST_CODE);

    }

/**
 * Handle results for your startActivityForResult() calls. Use requestCode
 * to differentiate.
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PICK_MEDIA_REQUEST_CODE) {
        // If picking media is success, create share post using
        // PlusShare.Builder
        if (resultCode == RESULT_OK) {
            Uri selectedImage = data.getData();
            ContentResolver cr = this.getContentResolver();
            String mime = cr.getType(selectedImage);

            PlusShare.Builder share = new PlusShare.Builder(this);
            share.setText("Hello from AndroidSRC.net");
            share.addStream(selectedImage);
            share.setType(mime);
            startActivityForResult(share.getIntent(),
                    SHARE_MEDIA_REQUEST_CODE);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM