2022年3月15日 星期二

Android 分享功能

 

網路圖片
https://stickershop.line-scdn.net/stickershop/v1/sticker/438329029/android/sticker.png

Intent intent = new Intent(Intent.ACTION_SEND);
if (imgPath == null || imgPath.equals("")) {
intent.setType("text/plain"); // 純文字
} else {
File f = new File(imgPath);
if (f != null && f.exists() && f.isFile()) {
intent.setType("image/jpg");
Uri u = Uri.fromFile(f);
intent.putExtra(Intent.EXTRA_STREAM, u);
}
}
intent.putExtra(Intent.EXTRA_SUBJECT, msgTitle);
intent.putExtra(Intent.EXTRA_TEXT, msgText);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().startActivity(Intent.createChooser(intent, activityTitle));




private void openShare(String msgText){
//建立一個AsyncTask執行緒進行圖片讀取動作,並帶入圖片連結網址路徑
new AsyncTask<String, Void, Bitmap>()
{
@Override
protected Bitmap doInBackground(String... params)
{
String url = params[0];
return getBitmapFromURL(url);
}

@Override
protected void onPostExecute(Bitmap result)
{
saveBitmapFile(result);
super.onPostExecute(result);

String imageUrl = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Android/data/" + getActivity().getPackageName() + "/tmp/share_image.jpg";
Intent intent=new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_SUBJECT, "BBBB");
intent.putExtra(Intent.EXTRA_TEXT, "AAAAAAA"); // 分享文字
File f = new File(imageUrl);
Uri u = FileProvider.getUriForFile(getActivity(), getActivity().getPackageName() + ".provider", f);
intent.putExtra(Intent.EXTRA_STREAM, u);
getActivity().startActivity(Intent.createChooser(intent, "分享到")); // 更改分享列表標題

}
}.execute("https://stickershop.line-scdn.net/stickershop/v1/sticker/438329029/android/sticker.png");
}

//讀取網路圖片,型態為Bitmap
private static Bitmap getBitmapFromURL(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
}
catch (IOException e) {
e.printStackTrace();
return null;
}
}

public String saveBitmapFile(Bitmap bitmap){
String dir = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Android/data/" + getActivity().getPackageName() + "/tmp";
File fileDir = new File(dir);
if (!fileDir.exists()){
fileDir.mkdirs();
}

String path = dir + "/share_image.jpg";
File file=new File(path);//将要保存图片的路径
if (!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
return path;
}

沒有留言:

張貼留言

Android Studio IDE 錯誤

 :app:compile xxxxx JavaWithJavac FAILED An exception has occurred in the compiler (1.8.0_312). Please file a bug against the Java compiler ...