2016-07-09 116 views
-1

有什麼辦法可以創建一個總是掃描wifi並永不停止檢查的應用程序。如果是這樣,它不會很快殺死電池嗎?
有人可以給我看一個很好的參考,掃描的WiFi和列表視圖中列出他們?
我試過這個Android Wi-Fi Tutorial網站,但它不適合我。總是掃描WiFi Android

這是我做的:

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)); 
     } 
    } 
} 
+0

我發現我的答案,這段代碼沒有工作,因爲我使用API​​ 23和AndroidManifest我不得不添加 代碼工作<使用權限android:name =「android.permission.ACCESS_FINE_LOCATION」/> –

回答

0

當AndroidSystem傳達您的廣播reciever次運行onRecieve接口,你應該調用startActivity方法onRecieve並開始WifiActivity並獲得掃描結果,並把它傳遞給ListView通過調用setAdapter。 This works :)