安卓读取短信

目标

读取安卓系统短信.

实现方案

  1. 添加依赖
implementation 'com.qw:soulpermission:1.3.0'
  1. 主要代码
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //对按钮添加点击事件
        button.setOnClickListener {
            readContactsWithPermission()
        }
    }

    /**
     * 先申请读取短信权限,再进行读取。
     */
    private fun readContactsWithPermission() {
        SoulPermission.getInstance()
            .checkAndRequestPermission(
                Manifest.permission.READ_SMS,
                object : CheckRequestPermissionListener {
                    override fun onPermissionOk(permission: Permission) {
                        readSms()
                    }

                    override fun onPermissionDenied(permission: Permission) {
                        toast("请授予权限")
                    }
                })
    }

    /**
     * 读取短信并展示总数和其中一条短信内容。
     */
    private fun readSms() {
        val smsList: ArrayList<String> = getSmsInfo()
        if (smsList.isNotEmpty()) {
            toast("一共${smsList.size}条短信,其中一条:${smsList.first()}")
        }
    }

    /**
     * 读取短信
     */
    private fun getSmsInfo(): ArrayList<String> {
        val dataList = ArrayList<String>()
        val uri = Uri.parse("content://sms/inbox")
        contentResolver.query(
            uri, null, null, null, null
        )?.apply {
            while (moveToNext()) {
                val displayName = getString(getColumnIndex("body"))
                dataList.add(displayName)
            }
            close()
        }
        return dataList
    }

    private fun toast(text: String) =
        Toast.makeText(this, text, Toast.LENGTH_LONG).show()
}

源代码

https://gitee.com/cxyzy1/ContentProviderDemo

你可能感兴趣的:(安卓)