So Android does not allow network operations to run on the main thread, fair enough. I am having some trouble with running this code on another thread. Can you please take a look at my code and see if this would work/is correct? Thank you I appreciate any help given.
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;
}
}
A Runnable itself is nothing without a Thread. Try adding this to your onCreate() or onResume():
and then probably have to read this https://developer.android.com/reference/java/lang/Thread.html so you know how things should be done…in your case, maybe the usage of AsyncTask is appropriated…but you must first understand how Threads work.