在android中定期更新Wifi状态信息

时间:2015-04-24 06:56:38

标签: android android-wifi runnable

我知道这个问题可能是另一个问题的复制品,但有人可以帮我弄清楚我哪里出错了,如果可能的话可能会纠正它吗?

public class MainActivity extends ActionBarActivity {

    TextView ford;
    public String TAG=MainActivity.class.getSimpleName();
    protected static final long TIME_DELAY = 1000;
    //the default update interval for your text, this is in your hand , just run this sample
    TextView mTextView;
    Handler handler=new Handler();
    Random trust = new Random();
    int count =0;

    @Override
    protected void onCreate(Bundle savedInstanceState){

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView=(TextView)findViewById(R.id.textview);}
        protected void onResume({

            super.onResume();handler.post(updateTextRunnable);}
            ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
            Runnable updateTextRunnable=new Runnable(){
            public void run() {

                if (networkInfo != null && networkInfo.isConnected()) {

                    mTextView.setText("connected!");
                } else {

                    mTextView.setText("No network connection available.");
                }
            }
        };
    }

1 个答案:

答案 0 :(得分:0)

有效的方法是创建一个broacast接收器,它将重新检查wifi状态。像这样注册接收器 -

 WifiMonitor wifiMonitor = new WifiMonitor();
    registerReceiver(wifiMonitor, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
    registerReceiver(wifiMonitor, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

    public class WifiMonitor extends BroadcastReceiver {

            @Override
            public void onReceive(Context context, Intent intent) {
    //do your work here
    }
}