2015-09-02 88 views
-1

我想在Android中製作應用程序,每5秒掃描一次所有網絡。爲了重複使用所有網絡,我使用了handler.postDelayed。應該執行task()wi()函數。 task()似乎有效,但wi()沒有。任何想法爲什麼?handler.postDelayed不執行

public class MainActivity extends Activity { 

    TextView tv , tv2; 
    int i = 0 ; 
    Timer t; 
    Thread time; 
    Handler handler; 
    WifiManager wifi; 
    WifiScanReceiver wifiReciever; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     tv = (TextView) findViewById(R.id.textView1); 
     tv2 = (TextView) findViewById(R.id.textView2); 
     handler = new Handler(); 
     handler.postDelayed(new Runnable() { public void run() { task();}}, 5000); 
    } 
    public void task(){ 
     i++; 
     tv.setText("Values "+i); 
     wi(); 
    } 
    public void wi(){ 
     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(); 
     } 
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 
     if (id == R.id.action_settings) { 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 
    private class WifiScanReceiver extends BroadcastReceiver{ 
     public void onReceive(Context c, Intent intent) { 

      WifiInfo ws = wifi.getConnectionInfo(); 
      tv2.setText(ws.toString()); 
      } 
     } 
} 

輸出: 值1

回答

0

我不完全確定的問題是什麼,但如果你想使處理器運行不斷,你應該嘗試這樣的事:

final Handler handler = new Handler(); 
Runnable runnable = new Runnable() { 

    @Override 
    public void run() { 
      task(); 
      handler.postDelayed(this, 5000); 
     } 
    } 
}; 
handler.postDelayed(runnable, 5000); 

編輯:

您可能需要將這些標記添加到這個清單文件:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> 
+0

我在每5秒後去任務中調用wi()函數,但wi()不顯示任何東西 –

+0

@UsmanMustafa您是否包含正確的權限?看看[這個答案](http://stackoverflow.com/a/7808715/5260943),並檢查編輯我的回答 –

+0

是的,我已經在清單文件中添加這些權限,當我不使用處理程序,它完美的作品,但打電話給無線()在任務中不起作用 –