Android利用系统自带功能分享图片

  在app的开发中,经常会用到分享图片这一功能。今天来说一下如何调用系统自带分享功能分享图片。

主要代码:

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

    }

 public void shareSingleImage(View view) {
        String imagePath = Environment.getExternalStorageDirectory() + File.separator + "3.jpg";//3.jpg是sd卡根目录下的图片
        //由文件得到uri
        Uri imageUri = Uri.fromFile(new File(imagePath));
        Log.d("share", "uri:" + imageUri);
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
        shareIntent.setType("image/*");
        startActivity(Intent.createChooser(shareIntent, "分享到"));
    }

布局文件

<RelativeLayout 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" >

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

</RelativeLayout>
上面的代码还是比较好理解的。调用系统的分享比较方便,理解起来也容易一些。还有一种方法是通过引入sdk来分享的,但是腾讯官方提供的参考代码貌似不可以直接用,我在测试的时候在图片路径(也可能是图片转换问题)上掉过很多次坑,到现在也没解决这个问题,希望如果有大神知道怎么弄的能告诉我一下。

猜你喜欢

转载自blog.csdn.net/hellocode1900/article/details/79551083