始终扫描WiFi Android

时间:2016-07-09 13:56:50

标签: android wifi android-wifi scanning

有没有办法创建一个始终扫描wifi并永不停止检查的应用程序。如果是这样,它是否会快速杀死电池? 有人能给我看一个很好的参考,扫描wifi并在列表视图中列出它们吗? 我试过这个Android Wi-Fi Tutorial网站,但它对我不起作用。

这就是我的所作所为:

package com.example.amire.yadavar;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.List;

public class MainActivity extends Activity  {
    private ListView lv;
    private WifiManager wifi;
    private WifiScanReceiver wifiReciever;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv=(ListView)findViewById(R.id.listView);

        wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE);
        wifiReciever = new WifiScanReceiver();
        wifi.startScan();
    }

    protected void onPause() {
        unregisterReceiver(wifiReciever);
        super.onPause();
    }

    protected void onResume() {
        registerReceiver(wifiReciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        super.onResume();
    }


    private class WifiScanReceiver extends BroadcastReceiver{
        public void onReceive(Context c, Intent intent) {
            List<ScanResult> wifiScanList = wifi.getScanResults();
            String[] wifis = new String[wifiScanList.size()];

            for(int i = 0; i < wifiScanList.size(); i++){
                wifis[i] = ((wifiScanList.get(i)).toString());
            }
            lv.setAdapter(new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_list_item_1, wifis));
        }
    }
}

1 个答案:

答案 0 :(得分:0)

当AndroidSystem与您的广播接收器进行通信时,运行onRecieve接口,您应该在onRecieve中调用startActivity方法并启动WifiActivity并获取扫描结果并通过调用setAdapter将其传递给ListView。 这有效:)