关键字
var:声明的变量,可读可写。
val:声明的变量,可读不可写,相当于 java中的 final
fun:声明方法。
unit:相当于 void
lateinit关键字的说明
详:https://blog.csdn.net/qq_25749749/article/details/109001465
kotlin中定义变量,都是需要初始化的。用 lateinit 修饰的变量,则可以延迟初始化。
注:lateinit 对应使用var来声明变量;lateinit 不可以修饰原始数据类型(byte,char,short ,int,long,float,double;
取代findViewById();插件的使用
kotlin-android-extensions 和 ViewBinding 的使用方式https://zhuanlan.zhihu.com/p/350300086
Kotlin动态权限申请管理
摘抄自:https://github.com/ChanghuiN/KPermissions
1.Permission类
class Permission(name: String, granted: Boolean, shouldShowRequestPermission: Boolean) {
lateinit var name: String
var granted: Boolean = false
var shouldShowRequestPermission: Boolean = false
}
// 访问摄像机权限
fun cameraPermission(): Array = arrayOf(
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
2.KPermission类
class KPermission private constructor() { //(var activity: Activity) {
constructor(activity: Activity) : this() {
this.activity = activity
}
@SuppressLint("NewApi")
constructor(fragment: Fragment) : this() {
this.fragment = fragment
}
private val TAG = "KPermission"
private val PERMISSIONS_REQUEST_CODE = 42
private var context: Context? = null
private var activity: Activity? = null
private var fragment: Fragment? = null
private var permissions: MutableMap = mutableMapOf()
private var unPermissions: MutableList = mutableListOf()
private lateinit var onRequestResultCallback: (Boolean) -> Unit
private lateinit var onRequestPermissionsCallback: (Permission) -> Unit
/**
* 权限请求
* @param perArr 权限数组
* @param onRequestResult 请求结果
* @param onRequestPermissions 每个权限请求结果,可省略
*/
@SuppressLint("NewApi")
fun requestPermission(
perArr: Array,
onRequestResult: (isAllow: Boolean) -> Unit,
onRequestPermissions: (permission: Permission) -> Unit = {}
) {
/* if activity android fragment is null, throw NullPointerException */
if (activity == null && fragment == null)
throw NullPointerException("activity and fragment is null")
context = activity?.let { activity } ?: fragment!!.context
/* To judge whether it's empty and SDK_VERSION */
if (perArr.isEmpty()) {
// || Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
onRequestResult(true)
return
}
onRequestResultCallback = onRequestResult
onRequestPermissionsCallback = onRequestPermissions
perArr.forEach { permissions.put(it, Permission(it, false, false)) }
/* check permission */
checkPermission()
/* shouldShowRequestPermissionRationale */
shouldShowRequestPermissionRationale()
/* requestPermissions */
if (unPermissions.size > 0)
activity?.let {
ActivityCompat.requestPermissions(
it,
unPermissions.toTypedArray(),
PERMISSIONS_REQUEST_CODE
)
} ?: let {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
fragment?.requestPermissions(
unPermissions.toTypedArray(),
PERMISSIONS_REQUEST_CODE
)
}
else
onRequestResultCallback(true)
}
/**
* 回调调用此函数
* @param requestCode 请求码
* @param pers 权限数组
* @param grantResults 请求权限结果
*/
fun onRequestPermissionsResult(
requestCode: Int,
pers: Array,
grantResults: IntArray
) {
if (requestCode == PERMISSIONS_REQUEST_CODE && grantResults.size > 0) {
var result = true
for (index in grantResults.indices) {
log(
"onRequestPermissionsResult---" + pers.get(index) + "---" + grantResults.get(
index
)
)
var permission = permissions.get(pers.get(index))
permission?.let {
permission.granted =
grantResults.get(index) == PackageManager.PERMISSION_GRANTED
onRequestPermissionsCallback(it)
if (!permission.granted) result = false
}
}
onRequestResultCallback(result)
}
}
private fun checkPermission() {
permissions.forEach {
if (ContextCompat.checkSelfPermission(
context!!,
it.key
) != PackageManager.PERMISSION_GRANTED
) {
unPermissions.add(it.key)
} else {
log("checkPermission---HavePermission---${it.key}")
it.value.granted = true
onRequestPermissionsCallback(it.value)
}
}
}
private fun shouldShowRequestPermissionRationale() {
activity?.let {
unPermissions.forEach {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity!!, it)) {
log("shouldShowRequestPermissionRationale---$it")
permissions.get(it)?.shouldShowRequestPermission = true
onRequestPermissionsCallback(permissions.get(it)!!)
}
}
} ?: unPermissions.forEach {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
fragment!!.shouldShowRequestPermissionRationale(it)
) {
log("shouldShowRequestPermissionRationale---$it")
permissions.get(it)?.shouldShowRequestPermission = true
onRequestPermissionsCallback(permissions.get(it)!!)
}
}
}
companion object {
/**
* 跳转到权限设置界面
*/
fun startPermissionSetting(context: Context) {
val intent = Intent()
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
intent.setData(Uri.fromParts("package", context.getPackageName(), null))
try {
context.startActivity(intent)
} catch (exception: Exception) {
throw exception
}
}
}
private fun log(msg: String) {
Log.i(TAG, msg)
}
}
3.MainActivity类
class MainActivity : AppCompatActivity() {
val TAG: String = this.javaClass.name
lateinit var kPermission: KPermission;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
kPermission = KPermission(this);
kPermission.requestPermission(cameraPermission(), {
// 总回调,所有权限都允许才回调
Log.i(TAG, "isAllow-22--$it")
}) {
// 单个权限允许回调,没允许一个,回调一次
Log.i(TAG, "permission-11--$it")
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
Log.i(TAG, "permission-33--")
kPermission.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}