Android自带API实现分享功能
前言
在做项目的过程中需要实现文字和图片的分享,有两种方式:
1.使用androidsdk中自带的Intent.ACTION_SEND实现分享。
2.使用shareSDK、友盟等第三方的服务。
鉴于使用的方便,此次只介绍使用Androidsdk中自带的方式来实现分享的功能。
分享文字
/**
*分享文字内容
*
*@paramdlgTitle
*分享对话框标题
*@paramsubject
*主题
*@paramcontent
*分享内容(文字)
*/
privatevoidshareText(StringdlgTitle,Stringsubject,Stringcontent){
if(content==null||"".equals(content)){
return;
}
Intentintent=newIntent(Intent.ACTION_SEND);
intent.setType("text/plain");
if(subject!=null&&!"".equals(subject)){
intent.putExtra(Intent.EXTRA_SUBJECT,subject);
}
intent.putExtra(Intent.EXTRA_TEXT,content);
//设置弹出框标题
if(dlgTitle!=null&&!"".equals(dlgTitle)){//自定义标题
startActivity(Intent.createChooser(intent,dlgTitle));
}else{//系统默认标题
startActivity(intent);
}
}
分享单张图片
/**
*分享图片和文字内容
*
*@paramdlgTitle
*分享对话框标题
*@paramsubject
*主题
*@paramcontent
*分享内容(文字)
*@paramuri
*图片资源URI
*/
privatevoidshareImg(StringdlgTitle,Stringsubject,Stringcontent,
Uriuri){
if(uri==null){
return;
}
Intentintent=newIntent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM,uri);
if(subject!=null&&!"".equals(subject)){
intent.putExtra(Intent.EXTRA_SUBJECT,subject);
}
if(content!=null&&!"".equals(content)){
intent.putExtra(Intent.EXTRA_TEXT,content);
}
//设置弹出框标题
if(dlgTitle!=null&&!"".equals(dlgTitle)){//自定义标题
startActivity(Intent.createChooser(intent,dlgTitle));
}else{//系统默认标题
startActivity(intent);
}
}
分享多张图片
//分享多张图片
publicvoidshareMultipleImage(Viewview){
ArrayListuriList=newArrayList<>();
Stringpath=Environment.getExternalStorageDirectory()+File.separator;
uriList.add(Uri.fromFile(newFile(path+"australia_1.jpg")));
uriList.add(Uri.fromFile(newFile(path+"australia_2.jpg")));
uriList.add(Uri.fromFile(newFile(path+"australia_3.jpg")));
IntentshareIntent=newIntent();
shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,uriList);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent,"分享到"));
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。