Search code examples
androidandroid-wifi

periodic wifi scan and export result to a txt file


I want to make periodic wifi scan(maybe every 5 mins) and export result to a txt file, so it shows the AP SSID and MAC and Signal Strength received. I'm very new to Android development so I only know the basics. my progress for now is copying the same exact steps in this thislink.


Solution

  • Create an outputStream and file

    private final static String STORETEXT="storetext.txt";
    OutputStreamWriter out=
        new OutputStreamWriter(openFileOutput(STORETEXT, 0));
    

    You can scan the wifi signal repeatedly using a timer and async task like this

    WifiManager wManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);// wifi manager
    
    // timer task
        public void Asyncwifi() {
        whandler = new Handler();
        timer = new Timer();
        doAsynchronousTask = new TimerTask() {
    
        @Override
        public void run() {
        whandler.post(new Runnable() {
        public void run() {
        try {
             wifiScan wscan = new wifiScan();
             wscan.execute();
            }catch (Exception e) {}
              }
            });
            }
            };
            timer.schedule(doAsynchronousTask, 0, 5000); // Repeate in every 5 sec
        }
    
    
        // Async task - wifi scan
        public class wifiScan extends AsyncTask<Void, String, Void> {
    
    
            protected void onPreExecute() {
    
            }
    
            protected void onPostExecute(Void results) {
    
            }
    
            @Override
            protected Void doInBackground(Void... params) {
                registerReceiver(br, new IntentFilter(
                        WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
                wManager.startScan();
                return null;
            }
        }
    

    You got the result in your BroadcastReceiver

       BroadcastReceiver br = new BroadcastReceiver() {
         @Override
        public void onReceive(Context c, Intent intent) {
         wifiList = wManager.getScanResults();
                for (int i = 0; i < wifiList.size(); i++) {
                sr1 = wManager.getScanResults().get(i);
                System.out.println("BSSID: " + sr1.BSSID);
                System.out.println("RSSI: " + sr1.level);
    
                    String str = "BSSID: "+sr1.BSSID+" "+"Level: "+sr1.level;
    
    // Write this data to file
              out.write(str.toString());
    
                   }
    
    
    
            };
    
    out.close();