這篇文章給大家介紹Android中怎么實現一個圖片分享工具類,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
權限
記得添加文件操作權限, 另外需要注意6.0版本以上的權限管理
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
具體細節見代碼
/**
* 系統分享圖片功能
* Created by wiky on 2018/1/13.
*/
object Util {
fun startShareImage(activity: Activity) {
//過濾出需要分享到對應的平臺:微信好友、朋友圈、QQ好友。 可自行修改
val targetApp = arrayOf("com.tencent.mm.ui.tools.ShareImgUI", "com.tencent.mm.ui.tools.ShareToTimeLineUI", "com.tencent.mobileqq.activity.JumpActivity")
/** * 分享圖片 */
val bitmap = getImageFromAssetsFile(activity, "img_share.jpg") //從assets目錄中取到對應的文件,文件名自行修改
val localImage = saveBitmap(bitmap!!, "share.jpg") //分享前,需要先將圖片存在本地(記得添加權限),文件名自行修改
val shareIntent = Intent(Intent.ACTION_SEND)
shareIntent.type = "image/*" //設置分享內容的類型:圖片
shareIntent.putExtra(Intent.EXTRA_STREAM, localImage)
try {
val resInfo = activity.packageManager.queryIntentActivities(shareIntent, 0)
if (!resInfo.isEmpty()) {
val targetedShareIntents = ArrayList<Intent>()
for (info in resInfo) {
val targeted = Intent(Intent.ACTION_SEND)
targeted.type = "image/*" //設置分享內容的類型
val activityInfo = info.activityInfo
//如果還需要分享至其它平臺,可以打印出具體信息,然后找到對應的Activity名稱,填入上面的數組中即可
// println("package = ${activityInfo.packageName}, activity = ${activityInfo.name}")
//進行過濾(只顯示需要分享的平臺)
if (targetApp.any { it == activityInfo.name }) {
val comp = ComponentName(activityInfo.packageName, activityInfo.name)
targeted.component = comp
targeted.putExtra(Intent.EXTRA_STREAM, localImage)
targetedShareIntents.add(targeted)
}
}
val chooserIntent = Intent.createChooser(targetedShareIntents.removeAt(0), "選擇要分享到的平臺")
if (chooserIntent != null) {
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toTypedArray<Parcelable>())
activity.startActivity(chooserIntent)
}
}
} catch (e: Exception) {
Log.e(StatConstants.LOG_TAG, "Unable to share image, logs : " + e.toString())
}
}
/** * 從Assets中讀取圖片 */
private fun getImageFromAssetsFile(context: Context, fileName: String): Bitmap? {
var image: Bitmap? = null
val am = context.resources.assets
try {
val inputStream = am.open(fileName)
image = BitmapFactory.decodeStream(inputStream)
inputStream.close()
} catch (e: IOException) {
e.printStackTrace()
}
return image
}
/** * 將圖片存到本地 */
private fun saveBitmap(bm: Bitmap, picName: String): Uri? {
try {
val dir = Environment.getExternalStorageDirectory().absolutePath + File.separator + picName
val f = File(dir)
if (!f.exists()) {
f.parentFile.mkdirs()
f.createNewFile()
}
val out = FileOutputStream(f)
bm.compress(Bitmap.CompressFormat.JPEG, 90, out)
out.flush()
out.close()
return Uri.fromFile(f)
} catch (e: FileNotFoundException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
return null
}
}關于Android中怎么實現一個圖片分享工具類就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。