Android系统⾃带分享功能【图⽚、⽂字、CSV和PDF⽂件】
前⾔:
调⽤系统⾃带的分享功能将⽂本,当前界⾯截图、CSV和PDF⽂件分享出去;
效果图【测试机型:⼩⽶10】:
添加依赖:
implementation 'com.itextpdf:itextg:5.5.10'
1、代码部分
①:⼯具类:FileShareUtils
public class FileShareUtils {
private static final String TAG = "FileShareUtils";
//⽂件输出流
private static OutputStream outputStream;
/**
* 维度。A4尺⼨为210×297毫⽶或8.27×11.69英⼨。
* 在PostScript中,其尺⼨四舍五⼊为595×842点。
*/
private static final int A4_WIDTH = 2520 / 2; // 210 * 6
private static final int A4_HEIGHT = 3564 / 2; // 297 * 6
/**
* 创建csv⽂件
*
* @param context 上下⽂
* @param datas  Lists of csv data
*/
public static void shareCsvFile(Context context, List<String> datas) {
//应⽤路径:/storage/emulated/0/Android/data/你的应⽤包名/files/test
File csvFile = ExternalFilesDir("HelloWord");
if (!ists()) {
// 如果你想在已经存在的⽂件夹(zainar)下建⽴新的⽂件夹(database),就可以⽤此⽅法。
// 此⽅法不能在不存在的⽂件夹下建⽴新的⽂件夹。假如想建⽴名字是"database"⽂件夹,那么它的⽗⽂件夹必须存在。
csvFile.mkdir();
}
String fileName = getFileName();
//时间戳.csv
File file = new File(csvFile, fileName + ".csv");
try {
//创建⼀个⽂件夹
} catch (IOException e) {
Log.e(TAG, "createCsvFile: " + e.getMessage());
}
//分享CSV
startIntent(context, getUriForFile(context, writeDataToFile(file, datas)), fileName, 0);
}
/**
* 写数据⾄⽂件夹中,创建file
*
* @param file    创建CSV⽂件对象
* @param dataList 分享的数组
* @return
*/
private static File writeDataToFile(final File file, List<String> dataList) {
//⽬录是否存在该⽂件
/
/⽬录是否存在该⽂件
if (ists()) {
try {
outputStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
Log.e(TAG, "writeDataToFile: " + e.getMessage());
}
//⽂件输出流
final OutputStream putStream = outputStream;
try { //写⼊Utf-8⽂件头
//在utf-8编码⽂件中BOM在⽂件头部,占⽤三个字节,⽤来标⽰该⽂件属于utf-8编码,
/
/现在已经有很多软件识别bom头,但是还有些不能识别bom头,⽐如PHP就不能识别bom头,
//这也是⽤记事本编辑utf-8编码后执⾏就会出错的原因了
putStream.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
} catch (IOException e) {
e.printStackTrace();
}
//减去1的标题栏
String[] headerArray = new String[dataList.size() - 1];
headerArray = Array(headerArray);
//1、普通形式
try {
for (int i = 0; i < headerArray.length; i++) {
putStream.write(headerArray[i].getBytes());
}
putStream.close();//关闭流
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "writeDataToFile: " + e.getMessage());
}
} else {
//⽆法创建CSV⽂件
Log.e(TAG, "创建CSV⽂件失败");
}
return file;
}
/**
* 创建Pdf
*/
public static void sharePdfFile(Context mContext) {
//1、关联布局
View view = LayoutInflater.from(mContext).inflate(R.layout.layout_pdf_view, null);
//设置宽⾼为A4纸⼤⼩
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(A4_WIDTH, A4_HEIGHT);
view.setLayoutParams(params);
//2、布局View转化为Bitmap
View.MeasureSpec.makeMeasureSpec(A4_HEIGHT, View.MeasureSpec.EXACTLY));
Bitmap bitmap = MeasuredWidth(), MeasuredHeight(), Bitmap.Config.ARGB_8888);        Canvas canvas = new Canvas(bitmap);
view.layout(0, 0, LayoutParams().width, LayoutParams().height);
view.draw(canvas);
//3、创建BitmapPDF
String fileName = getFileName();
File file = createBitmapPdf(mContext, fileName, bitmap);
//4、Intent意图-分享PDF
startIntent(mContext, getUriForFile(mContext, file), fileName, 1);
}
/**
* 创建PDF⽂件
* github/itext/itextpdf/tree/itextg
* iText是著名的开放源码的站点sourceforge⼀个项⽬,是⽤于⽣成PDF⽂档的⼀个java类库。
* iText是著名的开放源码的站点sourceforge⼀个项⽬,是⽤于⽣成PDF⽂档的⼀个java类库。    * 通过iText不仅可以⽣成PDF或rtf的⽂档,⽽且可以将XML、Html⽂件转化为PDF⽂件。
* iText 官⽹:itextpdf/
* iText 开发⽂档: developers.itextpdf/developers-home
*/
public static File createBitmapPdf(Context context, String fileName, Bitmap bitmap) {
if (null == bitmap) {
return null;
}
File dir = getFileUrl(context);
//是否存在该⽂件,不存在则创建
if (!ists()) {
dir.mkdir();
}
File file = new File(dir, fileName + ".pdf");
if (!ists()) {
try {
} catch (IOException e) {
e.printStackTrace();
}
}
//Page⼤⼩,左右上下边距【注意依赖库的包】
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
try {
document.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
/
/png、质量100
bitmappress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = ByteArray();
//Image注意导的包
Image image = Instance(byteArray);
//将图像缩放到⼀定的百分⽐。
image.scalePercent(50);
document.add(image);
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
/**
* 创建Bitmap图⽚
*/
getsavefilenamepublic static void sharePicFile(Activity context) {
String fileName = getFileName();
File path = getFileUrl(context);
saveBitmap(context, path, viewToBitmap(context), fileName);
File file = new File(path + "/" + fileName + ".png");
startIntent(context, getUriForFile(context, file), fileName, 2);
Log.e(TAG, "sharePicFile: " + String());
}
/**
* 当前界⾯转化为Bitmap
* 需要截取状态栏则将stateHeight设置为0
*/
private static Bitmap viewToBitmap(Activity activity) {
Bitmap bitmap;
View view = Window().getDecorView();
View view = Window().getDecorView();
//设置是否可以进⾏绘图缓存
view.setDrawingCacheEnabled(true);
//如果绘图缓存⽆法,强制构建绘图缓存
view.buildDrawingCache();
//返回这个缓存视图
bitmap = DrawingCache();
//获取状态栏⾼度(90)
Rect frame = new Rect();
//测量屏幕宽和⾼
int stateHeight = p;
Display display = WindowManager().getDefaultDisplay();
Point size = new Point();
int width = size.x;
int height = size.y;
Log.e(TAG, "stateHeight size:" + stateHeight);
Log.e(TAG, "width size:" + width);
Log.e(TAG, "height size:" + height);
// 根据坐标点和需要的宽和⾼创建bitmap
bitmap = ateBitmap(bitmap, 0, stateHeight, width, height - stateHeight);
return bitmap;
}
/**
* 保存图⽚
*
* @param context
* @param dir
* @param bitmap
* @param fileName
*/
@SuppressLint("SdCardPath")
public static void saveBitmap(Context context, File dir, Bitmap bitmap, String fileName) {
if (!ists()) {
dir.mkdir();
}
File file = new File(dir, fileName + ".png");
FileOutputStream out;
try {
out = new FileOutputStream(file);
if (bitmappress(Bitmap.CompressFormat.PNG, 100, out)) {
out.flush();//空⽅法体,此输出流并强制写出所有缓冲的输出字节
out.close();//关闭流
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "saveBitmap: " + e.getMessage());
}
//发送⼴播更新,扫描某个⽂件(⽂件绝对路径,必须是以 ExternalStorageDirectory() ⽅法的返回值开头)
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + AbsolutePath())));    }
/**
* 分享⽂本
*/
public static void shareText(Context context) {
Intent intent = new Intent(Intent.ACTION_SEND);
//指定包名:注意判断是否安装、QQ等;否则报错ActivityNotFoundException: No Activity found to handle Intent
//:  QQ:bileqq
//intent.setPackage("bileqq");//不指定包名则会显⽰所有可分享的应⽤
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "分享的内容");
context.startActivity(intent);
context.startActivity(intent);
}
/**
* 当前时间戳作为分享的⽂件名
*/
private static String getFileName() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").Instance().getTime());
}
/**
* 返回uri
*/
private static Uri getUriForFile(Context context, File file) {
//应⽤包名.fileProvider
String authority = PackageName().concat(".fileProvider");
Uri fileUri = UriForFile(context, authority, file);
Log.e(TAG, "onSuccess: ⽂件路径:" + authority);
Log.e(TAG, "onSuccess: ⽂件路径:" + String());
Log.e(TAG, "onSuccess: ⽂件路径:" + String());
return fileUri;
}
/
**
* 返回⽂件夹
*/
private static File getFileUrl(Context context) {
File root = FilesDir();
File dir = new File(root, "hello/");
if (!ists()) {
//创建失败
if (!dir.mkdir()) {
Log.e(TAG, "createBitmapPdf: 创建失败");
}
}
return dir;
}
/**
* 分享CSV⽂件
* true:csv false:pdf
*/
@SuppressLint("WrongConstant")
private static void startIntent(Context context, Uri fileUri, String fileName, int isType) {
Log.e(TAG, "startIntent: " + String());
Log.e(TAG, "startIntent: " + fileName);
Intent share = new Intent(Intent.ACTION_SEND);
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
share.putExtra(Intent.EXTRA_STREAM, fileUri);
share.putExtra(Intent.EXTRA_SUBJECT, fileName);
String title = "分享标题";
if (isType == 0) {
share.setType("application/vnd.ms-excel");
context.ateChooser(share, title));
} else if (isType == 1) {
share.setType("application/pdf");
//管理应⽤程序包
PackageManager packageManager = PackageManager();
//该组件或应⽤程序处于默认开启状态(其在清单指定)。
List<ResolveInfo> list = packageManager.queryIntentActivities(share, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);            if (null == list || list.size() == 0) {
Toast.makeText(context, "没有到可阅读PDF程序", Toast.LENGTH_SHORT).show();
} else {
context.ateChooser(share, title));

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。