Android中分享内容的方式很多,有时需要同时分享文字内容和图片,下面是图文分享的关键代码:
/**
* 图文分享
*
* @param imgPath
* :图片路径,如:/mnt/sdcard/NiMei/image/imageName.jpg
* @param content
* :文本内容
* @param context
*/
public static void share(String imgPath, String content, Context context) {
File f = new File(imgPath);
Uri uri = Uri.fromFile(f);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
if (uri != null&&imgPath!=null&&imgPath!="") {
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/jpeg");
// 当用户选择短信时使用sms_body取得文字
shareIntent.putExtra("sms_body", content);
} else {
shareIntent.setType("text/plain");
}
shareIntent.putExtra(Intent.EXTRA_TEXT, content);
// 自定义选择框的标题
// context.startActivity(Intent.createChooser(shareIntent, "选择分享方式"));
// 系统默认标题
context.startActivity(shareIntent);
}
如果想在分享的图片上添加水印,则使用下面的代码实现:
/**
* 添加水印后再分享图片
*/
public static void share(String filepath, String content, Context context) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
if (filepath != null && filepath != "") {
// 水印图片
Bitmap bmpLogo = BitmapFactory.decodeResource(
context.getResources(), R.drawable.bmp_logo);
// 源图片
Bitmap mBitmap = BitmapFactory.decodeFile(filepath);
// 与水印图片合成
Bitmap drawingBitmap = Bitmap.createBitmap(mBitmap.getWidth(),
mBitmap.getHeight(), bmpLogo.getConfig());
Canvas canvas = new Canvas(drawingBitmap);
Paint paint = new Paint();
// 设置水印图片在源图片上显示的位置
canvas.drawBitmap(bmpLogo, mBitmap.getWidth() - bmpLogo.getWidth()
- 20, mBitmap.getHeight() - bmpLogo.getHeight() - 20, paint);
paint.setXfermode(new PorterDuffXfermode(
android.graphics.PorterDuff.Mode.DST_OVER));
canvas.drawBitmap(mBitmap, 0, 0, paint);
// 将合成好的图片保存到SD卡再取出分享
String imgpath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/" + "mfnote.jpg";
File document = new File(imgpath);
try {
FileOutputStream fos = new FileOutputStream(document);
drawingBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);// 把数据写入文件
} catch (Exception e) {
e.printStackTrace();
}
File f = new File(imgpath);
Uri uri = Uri.fromFile(f);
if (uri != null) {
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/jpeg");
// 当用户选择短信时使用sms_body取得文字
shareIntent.putExtra("sms_body", content);
}
} else {
shareIntent.setType("text/plain");
}
shareIntent.putExtra(Intent.EXTRA_TEXT, content);
// 自定义选择框的标题
// context.startActivity(Intent.createChooser(shareIntent, "邀请好友"));
// 系统默认标题
context.startActivity(shareIntent);
}
有时候需要调用短信分享:
/**
* 以短信形式分享
*/
public static void sendSMS(Context context,String phoneNumber, String message){
Uri uri = Uri.parse("smsto:" + phoneNumber);
Intent sendIntent = new Intent(Intent.ACTION_VIEW, uri);
sendIntent.putExtra("sms_body", message);
context.startActivity(sendIntent);
}