我需要帮助才能在我的 Android 应用程序中获取彩信图片和消息!但我只检索彩信上的最后一张图片。如果一个彩信聊天有 4 张图片,但我只得到 4 张中的最后一张图片,但不是全部,所以请帮我用代码来解决这个问题!
目前我正在使用下面的代码来检索图像
使用此 URI 读取消息:content://mms-sms/conversations/
private fun getMmsMessages(lastDate: Long? = null): MutableList<MmsMessage> {
println(" checkMMS006...")
val result = mutableListOf<MmsMessage>()
val cursor = getCursor(lastDate)
if (cursor != null) {
val contentResolver: ContentResolver = context.contentResolver
val projection1 = arrayOf("*")
val uri = Uri.parse("content://mms-sms/conversations/")
val query = contentResolver.query(uri, projection1, null, null, null)
var msg = ""
var phoneNumber: String? = ""
var contactName: String? = ""
var dateIndex: String? = ""
var messageType: String? = ""
var body: String? = ""
if (query!!.moveToFirst()) {
do {
val string = query.getString(query.getColumnIndex("ct_t"))
if ("application/vnd.wap.multipart.related" == string) {
msg = query.getString(query.getColumnIndex("_id"))
println(" MMS-Data...")
// it's MMS
var mmsImageUrl: String? = null
val selectionPart = "mid=$msg"
val uri1 = Uri.parse("content://mms/part")
val cPart: Cursor? = context.contentResolver.query(
uri1, null,
selectionPart, null, null
)
println(" checkMMs007...")
if (cPart != null) {
while (cPart.moveToNext()) {
val partId =
cPart.let { cPart.getString(it.getColumnIndex("_id")) }
val type =
cPart.let { cPart.getString(it.getColumnIndex("ct")) }
val data = cPart.let { cPart.getString(it.getColumnIndex("_data")) }
dateIndex =
cPart.getColumnIndex(Telephony.Mms.DATE).toLong().toDate()
.toAPIFormat()
val indexType = cPart.getColumnIndex(Telephony.Mms.MESSAGE_TYPE).toString()
messageType = if(indexType =="-1"){
"OUTGOING"
}else{
"INCOMING"
}
contactName = getAddressNumberOfRecipient(partId)
phoneNumber = if (getAddressNumber(partId) === null) {
"123456789"
} else {
getAddressNumber(partId).toString()
}
var myPhoneNumber = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
(context.getSystemService(AppCompatActivity.TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager).getPhoneNumber(
SubscriptionManager.DEFAULT_SUBSCRIPTION_ID
)
} else if ((context.getSystemService(AppCompatActivity.TELEPHONY_SERVICE) as TelephonyManager).line1Number != null) {
(context.getSystemService(AppCompatActivity.TELEPHONY_SERVICE) as TelephonyManager).line1Number.toString()
} else {
"NO SIM"
}
if (myPhoneNumber.isEmpty()) {
myPhoneNumber = "Private Number"
}
if (data != null) {
body = getMmsText(partId)
println(body)
} else {
body = cPart.let { cPart.getString(it.getColumnIndex("text")) }
println(body)
}
if ("image/jpeg" == type || "image/bmp" == type || "image/gif" == type || "image/jpg" == type || "image/png" == type) {
val bitmap: Bitmap? = partId?.let { getMmsImage(it) }
if (bitmap != null) {
mmsImageUrl = saveImage(bitmap)
println("MmsImageUrl: $mmsImageUrl")
result.add(
MmsMessage(
0,
myPhoneNumber,
phoneNumber,
"",
dateIndex,
messageType,
mmsImageUrl,
)
)
}
println(" checkMMS005-Images...")
println(bitmap)
println("---------------------")
}
println("MMS BODY DATA: ")
}
}
println(" testMMSDat005...")
} else {
println(" SMS-Data...")
// it's SMS
}
} while (query.moveToNext())
}
}
cursor?.close()
return result
}
private fun getCursor(lastDate: Long?): Cursor? {
val collection = Telephony.Mms.CONTENT_URI
val projection = null
val selection: String?
val selectionArgs: Array<String>?
val sortOrder = "${Telephony.Mms.DATE} DESC"
if (lastDate != null) {
selection = "${Telephony.Mms.DATE} > ?"
selectionArgs = arrayOf((lastDate).toString())
} else {
selection = null
selectionArgs = null
}
return if (PreferencesUtils.getSMSPermission(context).toString() == "true") {
context.contentResolver.query(
collection,
projection,
selection,
selectionArgs,
sortOrder
)
} else {
null
}
}
private fun getMmsText(id: String): String {
val partURI = Uri.parse("content://mms/part/$id")
var `is`: InputStream? = null
val sb = StringBuilder()
try {
`is` = context.contentResolver.openInputStream(partURI)
if (`is` != null) {
val isr = InputStreamReader(`is`, "UTF-8")
val reader = BufferedReader(isr)
var temp = reader.readLine()
while (temp != null) {
sb.append(temp)
temp = reader.readLine()
}
}
} catch (e: IOException) {
e.message
} finally {
if (`is` != null) {
try {
`is`.close()
} catch (e: IOException) {
e.message
}
}
}
return sb.toString()
}
private fun getMmsImage(_id: String): Bitmap? {
val partURI = Uri.parse("content://mms/part/$_id")
var `is`: InputStream? = null
var bitmap: Bitmap? = null
try {
`is` = context.contentResolver.openInputStream(partURI)
bitmap = BitmapFactory.decodeStream(`is`)
} catch (_: IOException) {
} finally {
if (`is` != null) {
try {
`is`.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
println(" MMsDataMap01...")
println(bitmap)
return bitmap
}
private fun saveImage(bitmap: Bitmap): String {
Log.i(FileUtil.TAG, "Saving image...")
val mmsImageUrl: String?
val fileName = String.format(
Locale.getDefault(), "auto_%s",
SimpleDateFormat("yyyyMMdd_HHmmssSSS", Locale.getDefault())
.format(Date(System.currentTimeMillis()))
)
Log.i(FileUtil.TAG, "File name: $fileName")
println(" checkReadImageMMS1...")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
println(" checkReadImageMMS2...")
mmsImageUrl = saveImage(fileName, bitmap)
} else {
println(" checkReadImageMMS3...")
mmsImageUrl = saveImageLegacy(fileName, bitmap)
}
println("mmsImageUri: $mmsImageUrl")
return mmsImageUrl
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
private fun saveImage(fileName: String, bitmap: Bitmap): String {
val dir: File = context.getDir(Environment.DIRECTORY_PICTURES, Context.MODE_PRIVATE)
val file = File(dir, "$fileName.jpeg")
val outputStream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream)
val writer = FileOutputStream(file)
writer.write(outputStream.toByteArray())
writer.close()
bitmap.recycle()
val imageUri = file.toUri()
Log.i(FileUtil.TAG, "MMS file Uri : " + file.path)
println(" MMS-Image-Data-13...: $imageUri")
println("Test>>>>>>>>>>>>>>>>")
println(imageUri)
println(imageUri.getRealPath(context))
return file.path
}
private fun saveImageLegacy(fileName: String, bitmap: Bitmap): String {
val dirPath =
context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.absolutePath + "/${FileUtil.AUTO_SCREENSHOTS_DIRECTORY}"
val path = File(dirPath)
if (!path.exists()) {
path.mkdir()
}
val pathName = "$dirPath/$fileName"
val file = File(pathName)
val outputStream = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream)
outputStream.flush()
outputStream.close()
bitmap.recycle()
Log.i(FileUtil.TAG, "Auto ScreenShot Uri : " + file.path)
println(" MMS-Image-Data...")
println(Uri.fromFile(file))
println(file.path)
return file.toUri().toString()
}