Created
June 13, 2025 08:48
-
-
Save walteranyika/ed7c05a65added9e315080193a99808a to your computer and use it in GitHub Desktop.
Read SMS from inbox
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| data class SmsMessage(val address: String, val body: String, val date: Long) | |
| val context = LocalContext.current | |
| var smsList by remember { mutableStateOf<List<SmsMessage>>(emptyList()) } | |
| val permissionLauncher = rememberLauncherForActivityResult( | |
| ActivityResultContracts.RequestPermission() | |
| ) { isGranted: Boolean -> | |
| if (isGranted) { | |
| fetchSms(context) { smsList = it } | |
| } | |
| } | |
| LaunchedEffect(Unit) { | |
| val permission = Manifest.permission.READ_SMS | |
| if (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) { | |
| fetchSms(context) { smsList = it } | |
| } else { | |
| permissionLauncher.launch(permission) | |
| } | |
| } | |
| fun fetchSms(context: android.content.Context, onSmsFetched: (List<SmsMessage>) -> Unit) { | |
| val uri = Telephony.Sms.CONTENT_URI | |
| val projection = arrayOf(Telephony.Sms.ADDRESS, Telephony.Sms.BODY, Telephony.Sms.DATE) | |
| val cursor = context.contentResolver.query(uri, projection, null, null, null) | |
| val messages = mutableListOf<SmsMessage>() | |
| if (cursor != null && cursor.moveToFirst()) { | |
| do { | |
| val address = cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Sms.ADDRESS)) | |
| val body = cursor.getString(cursor.getColumnIndexOrThrow(Telephony.Sms.BODY)) | |
| val date = cursor.getLong(cursor.getColumnIndexOrThrow(Telephony.Sms.DATE)) | |
| messages.add(SmsMessage(address, body, date)) | |
| } while (cursor.moveToNext()) | |
| cursor.close() | |
| } | |
| onSmsFetched(messages) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment