我的Android项目中有一个实用程序类。但是,每当我调用其中一个辅助方法时,应用程序崩溃了。例如,当我这样称呼时:
public boolean IsNetworkAvailable(Context context){
ConnectivityManager connectivity = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
Toast.makeText(context, "None Available", Toast.LENGTH_SHORT).show();
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
for(NetworkInfo inf : info){
if(inf.getTypeName().contains("WIFI"))
if(inf.isConnected())
return true;
}
}
return false;
}
...来自MainActivity,如此:
SteinbeckCityUtils SteinbeckCityUtils = new SteinbeckCityUtils();
boolean networkAvailable = SteinbeckCityUtils.IsNetworkAvailable(MainActivity.this);
if (networkAvailable) {
Toast tostito = Toast.makeText(MainActivity.this, "Network is available", Toast.LENGTH_SHORT);
tostito.setGravity(Gravity.CENTER, 0, 0);
tostito.show();
}
即使我将IsNetworkAvailable()的中间改为此,也会失败:
if (null == connectivity) {
//Toast.makeText(context, "None Available", Toast.LENGTH_SHORT).show();
Log.i("czechNetwork", "no signs of life");
} else {
Log.i("czechNetwork", "some sign of life");
以下是更多上下文的更多代码:
package hhs.app;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.widget.Toast;
public class HHSUtils {
private Context _context;
public void ConnectionDetector(Context context) {
this._context = context;
}
// Found this here: http://www.androidsnippets.com/enable-and-disable-wifi
public void enableWiFi(boolean enable) {
WifiManager wifi = (WifiManager) _context.getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(enable);
}
// Found this here: http://www.androidsnippets.com/checking-for-wifi-access
public boolean IsNetworkAvailable(Context context){
ConnectivityManager connectivity = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
Toast.makeText(context, "None Available", Toast.LENGTH_SHORT).show();
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
for(NetworkInfo inf : info){
if(inf.getTypeName().contains("WIFI"))
if(inf.isConnected())
return true;
}
}
return false;
}
}
我尝试直接调用该方法而不实例化该类(使用HHS.IsNetworkAvailable()),但这样做,该方法甚至无法识别......
答案 0 :(得分:1)
您是否在AndroidManifest.xml中设置了权限?
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>