kotlin_08:wlan直连/wifi_p2p的页面跳转以及实时获取连接状态
生活随笔
收集整理的這篇文章主要介紹了
kotlin_08:wlan直连/wifi_p2p的页面跳转以及实时获取连接状态
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言之前一段時間一直加班,淦。五一,有點時間,簡單的陳述一下,wlan直連頁面的跳轉和狀態獲取以及監聽。
1. 先看效果
2. 布局文件
2.1 wifi_p2p_actvity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity"><Buttonandroid:id="@+id/btn"android:layout_width="match_parent"android:layout_height="wrap_content"app:layout_constraintLeft_toLeftOf="parent"app:layout_constraintRight_toRightOf="parent"app:layout_constraintBottom_toBottomOf="parent"android:text="點擊手動獲取wlan直連連接狀態"/><TextViewandroid:layout_width="match_parent"android:layout_height="50dp"android:hint="請點擊上方按鈕獲取最新狀態值"android:gravity="center"android:id="@+id/txt"/><TextViewandroid:layout_width="match_parent"android:layout_height="50dp"android:text="@string/hyper_link_tip_direct"android:gravity="center"android:id="@+id/hyper_link_tip_direct"/></LinearLayout>2.2 strings.xml
<resources><string name="app_name">系統跳轉</string><string name="hyper_link_tip_direct">請點擊:wlan直連 實現跳轉</string><string name="hyper_link_wlan_direct">wlan直連</string> </resources>3. WiFiP2pActivity.kt
3.1 跳轉到wlan直連頁面方式
// wlan direct頁面private fun startWlanDirectActivity() {val intent = Intent()intent.addCategory(Intent.CATEGORY_DEFAULT)intent.action = "android.intent.action.MAIN"val cn = ComponentName("com.android.settings","com.android.settings.Settings\$WifiP2pSettingsActivity" // 華為 nova6 wlanDirect頁面(親測))intent.component = cnstartActivity(intent)}3.2 定位服務權限檢查
如果想獲取或者監聽wlan直連的設備信息和狀態,就必須讓你寫的activity擁有位置定位信息的權限,否則監聽或者獲取不到設備信息。
private fun checkLocationPermission(){// 需要動態檢查定位服務的權限是否開啟if (ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),PERMISSION_LOCATION_CODE)return}} /*** 請求權限結果*/override fun onRequestPermissionsResult(requestCode: Int,permissions: Array<out String>,grantResults: IntArray) {super.onRequestPermissionsResult(requestCode, permissions, grantResults)if (requestCode == PERMISSION_LOCATION_CODE) {if (grantResults.isNotEmpty() && grantResults[0] != PackageManager.PERMISSION_GRANTED) {Toast.makeText(context,"請授予該應用定位服務權限,否則無法獲取wifi p2p 連接狀態",Toast.LENGTH_SHORT).show()}}}3.3 廣播監聽
想要實時監聽wlan直連的連接狀態的話,自然少不了廣播,而wlan直連的廣播監聽以后很多,這里只監聽設備連接和斷開。
//1. 定義一個WiFiDirectBroadcastReceiver 廣播private inner class WiFiDirectBroadcastReceiver : BroadcastReceiver() {override fun onReceive(p0: Context?, intent: Intent?) {when (intent?.action) {WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION -> {Log.e(TAG, "intent = ${intent.extras.toString()}")val networkInfo =intent.getParcelableExtra<NetworkInfo>(WifiP2pManager.EXTRA_NETWORK_INFO)val wifiP2pDevice =intent.getParcelableExtra<WifiP2pDevice>(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE)connectState = if (networkInfo?.isConnected == true) {Log.d(TAG, "Connect to wifi p2p. ${wifiP2pDevice?.deviceName}")true} else {Log.d(TAG, "DisConnect to wifi p2p.")false}updatePage()}}}} //2.在onCreate()中注冊private fun registerReceiver() {if (broadcastReceiver != null) returnbroadcastReceiver = WiFiDirectBroadcastReceiver()val intentFilter = IntentFilter()intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION)context?.registerReceiver(broadcastReceiver, intentFilter)} //3. 在onDestroy()中反注冊private fun unregisterReceiver() {if (broadcastReceiver == null) returncontext?.unregisterReceiver(broadcastReceiver)broadcastReceiver = null}3.4 判斷wlan直連是否有設備的API
僅僅通過監聽只能解決動態變化的場景,如果wlan直連一直是連接的狀態,此時想獲取到信息的話,只能通過調用api來判斷了。在android官網上關于wlan Direct 的api都是有介紹的,此處不在贅述。
4 頁面跳轉和刷新
4.1 在onCtreate()中添加頁面跳轉邏輯
findViewById<Button>(R.id.btn).setOnClickListener {startSearch()}// wlan直連setHyperLinkTips(findViewById<TextView>(R.id.hyper_link_tip_direct),getString(R.string.hyper_link_tip_direct),getString(R.string.hyper_link_wlan_direct),"android.settings.WIFI_P2P_SETTINGS",this)/*** 設置超鏈接* @tipsView: 超鏈接設置的TextView* @content:文本所有的內容* @hyperText:超鏈接文字* @action:intent跳轉的action* @context:Context* Tips:超鏈接文字hyperText要在content中包含*/private fun setHyperLinkTips(tipsView: TextView?,content: String,hyperText: String,action: String,context: Context) {val spannableString = SpannableStringBuilder(content)val span = object : ClickableSpan() {override fun onClick(p0: View) {Log.i(TAG, "Go to $hyperText page.")try {startWlanDirectActivity()} catch (e: Exception) {Log.i(TAG, "Go to $hyperText page fail.")}}}val startIndex = content.indexOf(hyperText)if (startIndex == -1) {return}val endIndex = startIndex + hyperText.lengthspannableString.setSpan(span, startIndex, endIndex, Spannable.SPAN_INCLUSIVE_INCLUSIVE)tipsView?.movementMethod = LinkMovementMethod.getInstance()tipsView?.text = spannableStringtipsView?.highlightColor = Color.parseColor("#36969696");}4.2 頁面刷新
private fun updatePage(deviceName: String? = null) {Log.i(TAG, "updatePage...isConnected = ${isConnected()}")findViewById<TextView>(R.id.txt).text = "device: $deviceName state: ${isConnected()}"}總結: 廣播動態監聽 + api 靜態調用 = 無死角獲取wlan直連連接的設備信息和狀態。
(如有錯誤,歡迎批評指正,請大佬輕噴)
總結
以上是生活随笔為你收集整理的kotlin_08:wlan直连/wifi_p2p的页面跳转以及实时获取连接状态的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 栈回溯技术arm_v5t_le版
- 下一篇: nextcloud php 部署,Cen