我刚开始学习Kotlin,我目前正在开发一个基于WebView的应用程序,如果应用程序打开后,我需要显示一个警告框。我怎么能在科特林做到这一点?
注意:我已经检查过许多堆栈溢出问题,但所有答案都是针对java而不是Kotlin的。另外,我只是个初学者,所以请用简单的方式写下答案,这样我才能理解。抱歉,英语不好
发布于 2020-05-20 11:30:13
private fun checkConnectivity() {
val manager = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork = manager.activeNetworkInfo
if (null == activeNetwork) {
val dialogBuilder = AlertDialog.Builder(this)
val intent = Intent(this, MainActivity::class.java)
// set message of alert dialog
dialogBuilder.setMessage("Make sure that WI-FI or mobile data is turned on, then try again")
// if the dialog is cancelable
.setCancelable(false)
// positive button text and action
.setPositiveButton("Retry", DialogInterface.OnClickListener { dialog, id ->
recreate()
})
// negative button text and action
.setNegativeButton("Cancel", DialogInterface.OnClickListener { dialog, id ->
finish()
})
// create dialog box
val alert = dialogBuilder.create()
// set title for alert dialog box
alert.setTitle("No Internet Connection")
alert.setIcon(R.mipmap.ic_launcher)
// show alert dialog
alert.show()
}
}还将此权限添加到报表中
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
这应该足以显示一个对话框,如果你的应用程序没有互联网连接。
发布于 2020-05-19 12:29:27
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
open class ConnectionCheck:BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (connectivityReceiverListener != null) {
connectivityReceiverListener!!.onNetworkConnectionChanged(
isConnectedOrConnecting(
context!!
)
)
}
}
private fun isConnectedOrConnecting(context: Context): Boolean {
val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo = connMgr.activeNetworkInfo
return networkInfo != null && networkInfo.isConnectedOrConnecting
}
interface ConnectivityReceiverListener {
fun onNetworkConnectionChanged(isConnected: Boolean)
}
companion object {
var connectivityReceiverListener: ConnectivityReceiverListener? = null
}
}这是互联网连接活动。在您想要检查internet连接的每一个活动中,该活动都应该扩展ConnectionCheck.ConnectivityReceiverListener。
不要忘记将<uses-permission android:name="android.permission.INTERNET"/>放在清单中。
https://stackoverflow.com/questions/61891063
复制相似问题