我想在点击按钮时检查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秒后继续检查?
答案 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
);
}