기본 콘텐츠로 건너뛰기

안드로이드 앱 만들기 : MMS 의 정보 확인에 대한 이야기


원본출처: 티스토리 바로가기

이전 포스팅에서 SMS 또는 LMS을 읽어오는 부분에 대해서는 기술한 바 있습니다. 이여서 하는 이야기는 MMS을 확인해 보는 방법입니다. 이전 포스팅으로 MMS가 읽어져 오는 것으로 이해를 하고 있었습니다만... 실제로는 그것이 아니라는 특히 국내에서 출시된 개선된(?) 안드로이드를 사용하는 경우 그런 기능으로는 정보를 다 가지고 오지 못하는 부분이 있다는 것을 알게 되었습니다.

 

MMS 수신 이벤트 확인

국내향 안드로이드의 경우는 SMS와 달리 MMS의 경우는 수신을 했다고 해도 Event 를 감지할 수 없었습니다. 그래서 대안으로 처리한 것은 알림 수신을 이용하는 것입니다. (알림 수신에 대해서는 이전 포스팅을 참고해 주세요)

 

import android.annotation.SuppressLint import android.app.Notification import android.content.ContentResolver import android.content.Context import android.database.Cursor import android.net.Uri import android.os.Build import android.service.notification.NotificationListenerService import android.service.notification.StatusBarNotification import android.util.Log import androidx.annotation.RequiresApi ..... import java.io.BufferedReader import java.io.InputStreamReader import java.text.SimpleDateFormat import java.util.*   class MyNotificationListener : NotificationListenerService() {      val TAG = "MyNotificationListener"     val MMS_URI: Uri = Uri.parse("content://mms-sms/conversations/")     val mmsRcvNumbers = mutableListOf<MmsBean>()      override fun onNotificationRemoved(sbn: StatusBarNotification) {         super.onNotificationRemoved(sbn)         Log.e(             TAG, "onNotificationRemoved ~ " +                     " packageName: " + sbn.packageName +                     " id: " + sbn.id         )     }      /**      * MMS 발송자 전화 번호 알아 내기      */     @SuppressLint("Range")     private fun getAddressNumber(id: Int): String? {         val selectionAdd = "msg_id=${id}"         val uriStr = "content://mms/${id}/addr"         val uriAddress = Uri.parse(uriStr)         val cAdd = contentResolver.query(             uriAddress, null,             selectionAdd, null, null         )         var name: String? = ""         try {             if (cAdd!!.moveToFirst()) {                 do {                     val number = cAdd.getString(cAdd.getColumnIndex("address"))                     if (number != null) {                         try {                             number.replace("-", "").toLong()                             name = number                         } catch (nfe: NumberFormatException) {                             if (name == null) {                                 name = number                             }                         }                     }                 } while (cAdd.moveToNext())             }             if (cAdd != null) {                 cAdd.close()             }         } catch (e : Exception) {          }         return name     }      /**      * MMS 의 본문 내용 읽어 오기      */     private fun getMMsPart(mId: String?): String {         var rValue = ""         var selectionPart: String = "mid=" + mId;         var uriPart : Uri = Uri.parse("content://mms/part");         var cur : Cursor? = contentResolver.query(uriPart, null, selectionPart, null, null);         if (cur != null) {             if (cur.moveToFirst()) {                 do {                     rValue = getMmsBody(cur)                 } while (cur.moveToNext())             }         }         return rValue     }      /**      *  MMS Body read      */     private fun getMmsBody(partCursor: Cursor): String {         val partId = partCursor.getString(partCursor.getColumnIndexOrThrow("_id"))         val data = partCursor.getString(partCursor.getColumnIndexOrThrow("_data"))         return if (data != null) {             getMessageText(contentResolver, partId)         } else {             partCursor.getString(partCursor.getColumnIndexOrThrow("text"))         }      }      /**      * MMS body get Text      */     private fun getMessageText(contentResolver: ContentResolver, id: String): String {         val partUri = Uri.parse("content://mms/part/$id")         val stringBuilder = StringBuilder()         val inputStream = contentResolver.openInputStream(partUri)          if (inputStream != null) {             val inputStreamReader = InputStreamReader(inputStream, "UTF-8")             val bufferedReader = BufferedReader(inputStreamReader)             var temp = bufferedReader.readLine()             while (temp != null) {                 stringBuilder.append(temp)                 temp = bufferedReader.readLine()             }             inputStream.close()         }          return stringBuilder.toString()     }      @SuppressLint("Range")     @RequiresApi(Build.VERSION_CODES.S)     override fun onNotificationPosted(sbn: StatusBarNotification) {         super.onNotificationPosted(sbn)          val projection = arrayOf("_id", "ct_t")         val query: Cursor? = contentResolver.query(MMS_URI, projection, null, null, null)         mmsRcvNumbers.clear()         if (query != null) {             if (query.moveToFirst()) {                 do {                     var mId = query.getString(0)                     var fromAddr = getAddressNumber(mId.toInt())                     if (!"".equals(fromAddr)) {                         var mmsBean = MmsBean(mId.toInt(), fromAddr.toString())                         var mesg = getMMsPart(mId)                         mmsBean.mesg = mesg //                        Log.e(TAG, "mesg = ${mesg}")                         mmsRcvNumbers.add(mmsBean)                     }                     Log.e(TAG, "sms id=$mId [$fromAddr]")                 } while (query.moveToNext())             }         }         if (mmsRcvNumbers.size > 0) {             mmsRcvNumbers.sortByDescending { orderItem -> orderItem.mId }         }          var sdf = SimpleDateFormat("yyyy-MM-dd kk:mm:ss", Locale("ko", "KR"))         val extras = sbn.notification.extras          try {              var title = extras.getString(Notification.EXTRA_TITLE).toString()             var content = "" + extras.getCharSequence(Notification.EXTRA_TEXT)             if (extras.getCharSequence(Notification.EXTRA_SUB_TEXT) != null) {                 content += " " + extras.getCharSequence(Notification.EXTRA_SUB_TEXT)             }             var number = ""             if (mmsRcvNumbers.size > 0) {                 number = mmsRcvNumbers.get(0).rcvNumber                 content = mmsRcvNumbers.get(0).mesg             }              Log.e(                 TAG, "onNotificationPosted ~ " +                         "\n packageName: " + sbn.packageName +                         "\n id: " + sbn.id +                         "\n postTime: " + sdf.format(sbn.postTime) +                         "\n title: " + title +                         "\n number: " + number +                         "\n content : " + content             )                         } catch (e: Exception) {             Log.e(                 TAG, "error = ${e.localizedMessage}"             )         }     }  }

코드에서 보는 것과 같이 Notification Receiver을 활용해 contentResolver 을 이용 content://mms-sms/conversations의 정보를 읽어옵니다. 이 정보를 활용해서 mms의 정보를 열어 보는 방식으로 구현이 되었습니다.

 

이 부분을 조금 더 활용해 본다면, sms 수신 데이터의 정보도 읽어 올 수 있도록 구현이 될 것 같습니다. 

나중에 기회가 된다면 그 부분도 구현을 해 보도록 하겠습니다.

 

 

귤탐 당도선별 감귤 로열과, 3kg(S~M), 1박스 삼립 호빵 발효미종 단팥, 92g, 14개입 [엉클컴퍼니] 우리밀 찐빵/흑미찐빵/단호박찐빵/고구마찐빵 국산팥, 우리밀 고구마찐빵(20개입) 1300g 국산팥 우리밀 MORIT 여성용 방한장갑 터치스크린 다용도 고급겨울장갑 에이치머스 스마트폰 터치 방한 장갑
이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.

댓글

이 블로그의 인기 게시물

안드로이드 앱 만들기 : onBackPressed 가 deprecated 되었다니 ?

원본출처: 티스토리 바로가기 onBackPressed 가 deprecated 되었다? 이제 우리는 구글이 제안하는 안드로이드 13에 타기팅하는 앱을 제출 해야만 하는 시기에 도달하고 있습니다.  구글이 새로운 안드로이드 버전을 배포하기 시작하면서 오래된 안드로이드에 대한 게시를 제한 합니다.    그래서 이번에 API 33 인 안드로이드 13에 타겟팅 하는 앱을 작성해 보았습니다. 그러다 만난 몇 가지 사용 제한이 되는 것들에 대한 정리를 해 두고자 합니다.    onBackPressed는 사용자가 뒤로 가기 버튼을 클릭하는 경우 제어를 하기 위해서 사용했던 함수 입니다. MainActivity 에서 최종적으로 뒤로 가기를 클릭 하는 경우 앱을 종료시키는 기능도 사용이 되는 함수였는 데...   안드로이드 13에서는 더 이상 사용할 수 없는 (?)  - 사용은 가능 하나 소스 코드에 중간 줄이 생긴 모양을 보면서 코드를 지속적으로 봐야 합니다.    onBackPressed 어떻게 해소를 하면 될까요?   CallBack을 하나 만들어 봅니다. private val callback = object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { doCloseApps() } } 다른 건 없고 이런 모양으로 callback 함수를 하나 만들어 둡니다.  그러고 onCreate 에서 이 callback 이 호출 되도록 한 줄 넣어 주는 것으로 그 코딩은 마무리 됩니다.    @RequiresApi(Build.VERSION_CODES.TIRAMISU) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(sav...

개인정보처리방침 안내

 billcoreaTech('https://billcoreatech.blogspot.com/'이하 'https://billcoreatech.blogspot')은(는) 「개인정보 보호법」 제30조에 따라 정보주체의 개인정보를 보호하고 이와 관련한 고충을 신속하고 원활하게 처리할 수 있도록 하기 위하여 다음과 같이 개인정보 처리방침을 수립·공개합니다. ○ 이 개인정보처리방침은 2021년 8월 26부터 적용됩니다. 제1조(개인정보의 처리 목적) billcoreaTech('https://billcoreatech.blogspot.com/'이하 'https://billcoreatech.blogspot')은(는) 다음의 목적을 위하여 개인정보를 처리합니다. 처리하고 있는 개인정보는 다음의 목적 이외의 용도로는 이용되지 않으며 이용 목적이 변경되는 경우에는 「개인정보 보호법」 제18조에 따라 별도의 동의를 받는 등 필요한 조치를 이행할 예정입니다. 1. 서비스 제공 맞춤서비스 제공을 목적으로 개인정보를 처리합니다. 제2조(개인정보의 처리 및 보유 기간) ① billcoreaTech은(는) 법령에 따른 개인정보 보유·이용기간 또는 정보주체로부터 개인정보를 수집 시에 동의받은 개인정보 보유·이용기간 내에서 개인정보를 처리·보유합니다. ② 각각의 개인정보 처리 및 보유 기간은 다음과 같습니다. 1.<서비스 제공> <서비스 제공>와 관련한 개인정보는 수집.이용에 관한 동의일로부터<사용자의 설정시간>까지 위 이용목적을 위하여 보유.이용됩니다. 보유근거 : 앱의 기본기능 활용에 필요한 위치정보 제3조(개인정보의 제3자 제공) ① billcoreaTech은(는) 개인정보를 제1조(개인정보의 처리 목적)에서 명시한 범위 내에서만 처리하며, 정보주체의 동의, 법률의 특별한 규정 등 「개인정보 보호법」 제17조 및 제18조에 해당하는 경우에만 개인정보를 제3자에게 제공합니다. ② billcoreaTech...