所以Android不允许网络操作在主线程上运行,这很公平。我在另一个线程上运行此代码时遇到了一些麻烦。你能看看我的代码,看看这是否可行/正确吗?谢谢您,感谢您提供的任何帮助。
public class StartActivity extends Activity implements Runnable {
public static final int timeout = 3000;
private boolean boolConStatus = false;
public static final String TAG = "StartActivity";
public static final String url = "serverIP";
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
Log.d(TAG, "onCreated with Bundle: " + bundle);
setContentView(R.layout.activity_start);
}
public void run() {
boolean boolConStatus;
boolConStatus = this.isConnected();
toaster();
}
public boolean getConStatus() {
return boolConStatus;
}
public void toaster() {
boolConStatus = this.isConnected();
if (boolConStatus == true) {
Toast.makeText(getApplicationContext(),
"Connected to Server", Toast.LENGTH_LONG);
} else {
Toast.makeText(getApplicationContext(),
"All has failed", Toast.LENGTH_LONG);
}
}
public boolean isConnected() {
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected()) {
URL server = new URL(url);
HttpURLConnection huc = (HttpURLConnection) server.openConnection();
huc.setRequestProperty("Connection", "close");
huc.setConnectTimeout(timeout);
huc.connect();
if (huc.getResponseCode() == 200) {
return true;
} else {
Log.d("NOT CONNECTED TO SERVER", "NOT CONNECTED TO SERVER");
return false;
}
} else {
Log.d("NO INTERNET CONNECTION", "NO INTERNET CONNECTION");
return false;
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage(), e);
e.printStackTrace();
}
return false;
}
}