kotlin 코드로 APN 설정

3121 단어
object ApnHelper {

    private val URI_APN = Uri.parse("content://telephony/carriers")
    private val URI_PREFER_APN = Uri.parse("content://telephony/carriers/preferapn")

    private val contentResolver = App.context.contentResolver

    /**
     *    APN
     */
    fun setApn(apn: String, simOperator: String): Boolean {
        logd("[ApnHelper] setApn: apn = $apn, simOperator = $simOperator")

        if (checkApn(apn, simOperator)) {
            logd("[ApnHelper] checkApn: Not need to set")
            return true
        }

        logd("[ApnHelper] checkApn: Need to set")
        val id =
            getExistApn(apn, simOperator)
                .also { logd("[ApnHelper] getExistApn: existing id = $it") }
                ?: addApn(apn, simOperator)
                    .also { logd("[ApnHelper] addApn: insert id = $it") }
        return selectApn(id) != 0
    }

    /**
     *    APN       
     */
    private fun checkApn(apn: String, simOperator: String?): Boolean {
        contentResolver.query(
            URI_PREFER_APN,
            null,
            "apn=? and numeric=?",
            arrayOf(apn, simOperator),
            null
        )?.use { cursor -> return cursor.moveToFirst() }
        return false
    }

    /**
     *              APN
     */
    private fun getExistApn(apn: String, simOperator: String): String? {
        contentResolver.query(
            URI_APN,
            arrayOf("_id"),
            "apn=? and numeric=?",
            arrayOf(apn, simOperator),
            null
        )?.use { cursor ->
            if (cursor.moveToFirst()) return cursor.getString(cursor.getColumnIndex("_id"))
        }
        return null
    }

    /**
     *       APN     
     */
    private fun addApn(apn: String, simOperator: String): String? {
        logd("[ApnHelper] addApn: apn = $apn, simOperator = $simOperator")

        val mcc = simOperator.substring(0..2)
        val mnc = simOperator.substring(3..4)
        logd("[ApnHelper] addApn: mcc = $mcc, mnc = $mnc")

        val values = ContentValues().apply {
            put("name", apn)
            put("apn", apn)
            put("numeric", simOperator)
            put("mcc", mcc)
            put("mnc", mnc)
            put(
                "type",
                "default,mms,supl,hipri,fota,cbs,dm,wap,net,cmmail,tethering,rcse,xcap,rcs,bip,vsim"
            )
        }
        return contentResolver.insert(URI_APN, values)?.lastPathSegment
    }

    /**
     *     APN
     */
    private fun selectApn(id: String?): Int {
        logd("[ApnHelper] selectApn: id = $id")
        if (id == null) return 0
        ContentValues().apply {
            put("apn_id", id) // TelephonyProvider.COLUMN_APN_ID = "apn_id";
            return contentResolver.update(URI_PREFER_APN, this, null, null)
                .also { logd("[ApnHelper] selectApn: updated rows = $it") }
        }
    }

}

좋은 웹페이지 즐겨찾기