Android一键分享——原生分享图片
16lz
2021-01-26
有些东西还是记下来比较好,记记随笔,欢迎批评建议。
Android分享的实现大多可以用第三方的分享,友盟、ShareSDK等。这里介绍的是Android系统自带的分享。调用原生的分享时,系统会调出手机中所有具有分享功能的APP,当然你也可以用代码进行筛选,分享界面也是根据系统的风格。
~
注意:如果是分享本地图片,获取图片地址拼成uri即可;若不是本地图片,分享需先将图片保存到本地并获取uri,若直接分享会出现报错提示图片不存在。
保存图片到本地
Android SDK中 Environment类 提供了getExternalStorageDirectory()方法来获取外部存储的根路径。由于需要在外部存储中写文件,需要在AndroidManifest.xml中增加如下的权限声明。
保存图片文件时,通过Bitmap的compress()方法将Bitmap对象压缩到一个文件输出流中,然后flush()即可。
/** * 将图片存到本地 */private static Uri saveBitmap(Bitmap bm, String picName) { try { String dir=Environment.getExternalStorageDirectory().getAbsolutePath()+"/renji/"+picName+".jpg"; File f = new File(dir); if (!f.exists()) { f.getParentFile().mkdirs(); f.createNewFile(); } FileOutputStream out = new FileOutputStream(f); bm.compress(Bitmap.CompressFormat.PNG, 90, out); out.flush(); out.close(); Uri uri = Uri.fromFile(f); return uri; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null;}
从assets中获取图片
/** * 从Assets中读取图片 */private Bitmap getImageFromAssetsFile(String fileName){ Bitmap image = null; AssetManager am = getResources().getAssets(); try { InputStream is=am.open(fileName); image=BitmapFactory.decodeStream(is); is.close(); } catch (IOException e) { e.printStackTrace(); } return image;}
原生分享图片
/** * 分享图片 */ Bitmap bgimg0 = getImageFromAssetsFile("ic_launcher.png"); Intent share_intent = new Intent(); share_intent.setAction(Intent.ACTION_SEND);//设置分享行为 share_intent.setType("image/*"); //设置分享内容的类型 share_intent.putExtra(Intent.EXTRA_STREAM, saveBitmap(bgimg0,"img")); //创建分享的Dialog share_intent = Intent.createChooser(share_intent, dialogTitle); getActivity().startActivity(share_intent);
原生分享文字内容
/** * 分享文字内容 */ Intent share_intent = new Intent(); share_intent.setAction(Intent.ACTION_SEND);//设置分享行为 share_intent.setType("text/plain");//设置分享内容的类型 share_intent.putExtra(Intent.EXTRA_SUBJECT, contentTitle);//添加分享内容标题 share_intent.putExtra(Intent.EXTRA_TEXT, content);//添加分享内容 //创建分享的Dialog share_intent = Intent.createChooser(share_intent, dialogTitle); activity.startActivity(share_intent);
对分享项的筛选可参考: Android-原生系统分享小记
第一次写随笔,写的比较匆忙,欢迎批评建议。
更多相关文章
- 开源一款android 偷拍 app【静拍】豌豆荚、flyme商店已经上线
- 在android上实施不会OOM的内存管理方案
- android 类似微信朋友圈图片点击放大的ImageView
- Android使用 LruCache 缓存图片
- 「Android」 APK瘦身探索
- Android自定义导览地图组件(一)
- 基于Android的记事本的设计与开发(实验报告+源代码)
- Android中AS创建点9图片与使用
- android 点击字体,图片背景效果一起变换Demo