检查Wifi是否在课堂上连接的方法

时间:2016-06-15 20:06:42

标签: java android methods android-wifi wifimanager

我想在点击按钮时检查wifi是否已连接,并显示弹出消息,因此我为其编写了一个单独的类:

公共类Pop扩展了Activity {

@Override

protected void onCreate(Bundle savedInstanceSate) {

    super.onCreate(savedInstanceSate);

    setContentView(R.layout.popup);

    DisplayMetrics dm = new DisplayMetrics() ;
    getWindowManager().getDefaultDisplay().getMetrics(dm);

    int width = dm.widthPixels ;
    int height = dm.heightPixels ;

    getWindow().setLayout( (int)(width*.6),(int)(height*.4) ) ;

}

那么检查wifi是否连接的方法应该是什么,并且即使应用程序关闭,它也会在每5秒后继续检查?

2 个答案:

答案 0 :(得分:0)

您可以通过调用此方法检查您是否可以访问互联网:

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager =
            (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

    boolean isAvailable = false;
    if (networkInfo != null && networkInfo.isConnected()) {
        isAvailable = true;
    }
    return isAvailable;
}

请记住要求获得所需的权限:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

答案 1 :(得分:0)

试试这个

添加权限<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

MainActivity.java

中的

ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (mWifi.isConnected()) {
        Intent networkInfoServiceIntent = new Intent(MainActivity.this,NetworkInfoService.class);
        startService(networkInfoServiceIntent);
}

将服务名称创建为NetworkInfoService并在清单中注册

现在将NetworkInfoService实现为,

    /**
     * Function for check network connectivity after every 5 seconds
     */
    private void checkNetworkConnectivity() {
        // handler will run after 5 seconds
        new Handler().postDelayed(new Runnable() {
                                      @Override
                                      public void run() {
                                         ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                                         NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                                          if (mWifi.isConnected()){
                                              checkNetworkConnectivity();
                                          }else {
                                              // display alert (notification)
                                          }

                                      }
                                  },5000
        );
    }