handler.postDelayed不执行

时间:2015-09-02 12:07:33

标签: android android-wifi android-handler wifimanager

我想在Android中制作应用程序,每5秒扫描一次所有网络。为了能够反复使用所有网络,我使用handler.postDelayed。应执行task()wi()函数。 task()似乎有效但wi()没有。知道为什么吗?

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

1 个答案:

答案 0 :(得分: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" />