wifiManager.startScan () возвращает false - PullRequest
0 голосов
/ 27 февраля 2020

Не знаю, почему мой код копировал один в один из из android .developer.com не работает. Получая результат получения списка доступных Wi-Fi, я получил ошибку связи с функцией scanFailure (). Мой уровень API требует разрешений, которые я объявил, поэтому я отвечаю всем требованиям.

AddNewDeviceFragment

class AddNewDeviceFragment : Fragment() {

    private lateinit var wifiManager: WifiManager
    private var adapter: NewDeviceAdapter = NewDeviceAdapter(arrayListOf())
    private lateinit var model: NewDeviceViewModel
    private lateinit var rootView: View

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        rootView = inflater.inflate(R.layout.fragment_addnewdevice, container, false)

        return rootView
    }

    override fun onStart() {
        super.onStart()

        var newDevicesRecycledView = rootView.findViewById(R.id.newDevicesRecycledView) as RecyclerView
        newDevicesRecycledView.layoutManager = LinearLayoutManager(activity)
        newDevicesRecycledView.adapter = adapter

        //ViewModel
        model = ViewModelProviders.of(this).get(NewDeviceViewModel::class.java)

        //LiveData
        model.getNewDevices()
            .observe(viewLifecycleOwner, Observer<MutableList<NewDevice>> { newDevices ->
                adapter.addDevice(newDevices)
            })
        swipeRefreshLayout.setOnRefreshListener { startScan() }
    }

    fun startScan() {
        swipeRefreshLayout.isRefreshing = true

        wifiManager = context?.getSystemService(Context.WIFI_SERVICE) as WifiManager


        if (!wifiManager.isWifiEnabled) {
            Toast.makeText(activity, "Wifi is disable... We need to enable it", Toast.LENGTH_LONG).show()
            wifiManager.setWifiEnabled(true)
        }

        val wifiScanReceiver = object : BroadcastReceiver() {

            override fun onReceive(context: Context, intent: Intent) {
                val success = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false)
                if (success) {
                    scanSuccess()
                } else {
                    scanFailure()
                }
            }
        }

        val intentFilter = IntentFilter()
        intentFilter.addAction("android.net.wifi.SCAN_RESULTS")
        context?.registerReceiver(wifiScanReceiver, intentFilter)

        val success = wifiManager.startScan()
        if (!success) {
            // scan failure handling
            scanFailure()
        }
        swipeRefreshLayout.isRefreshing = false
    }

    private fun scanSuccess() {
        model.clearAllData()

        val results = wifiManager.scanResults
        for (result in results) {
            model.addNewDevice(NewDevice(result.SSID.toString()))
        }
    }

    private fun scanFailure() {
        Toast.makeText(activity,"Error while scanning WiFi",Toast.LENGTH_LONG).show()
    }
}

Манифест

<?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        package="com.example.lightmeup">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher"
            android:supportsRtl="true"
            android:theme="@style/AppTheme"
            tools:ignore="GoogleAppIndexingWarning">
        <activity android:name=".MainActivity"
        android:theme="@style/AppTheme.NoActionBar"
        android:screenOrientation="portrait">

        </activity>
        <activity
                android:name=".LoginActivity"
                android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>
...