I am trying to run the following code but I want to show a progress dialog while my process is being run:
public boolean isOnline() {
cm = (ConnectivityManager) mContext.getSystemService(mContext.CONNECTIVITY_SERVICE);
netInfo = cm.getActiveNetworkInfo();
progress_thread = new progress_thread();
progress_thread.execute();
isconnected = false;
if (netInfo != null && netInfo.isConnected()) {
try{
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) isconnected = true;
}catch (MalformedURLException e1) {
e1.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
progress_thread.cancel(true);
if (!isconnected) Toast.makeText(mContext,"Internet Connexion Error", Toast.LENGTH_LONG).show();
return isconnected;
private class progress_thread extends AsyncTask<Void, Integer, Boolean>{
protected void onPreExecute() {
dialog = new ProgressDialog(mContext);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Loading Tracker...");
dialog.setCancelable(false);
dialog.show();
}
protected Boolean doInBackground(Void... params) {
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
protected void onCancelled() {
if (dialog.isShowing()) dialog.dismiss();
}
protected void onPostExecute(Boolean result_ex) {
if (dialog.isShowing()) dialog.dismiss();
}
}
What I want to do is run the progress dialog while I'm checking if there is internet connection or not. But I am having the problem that the UI is not refreshed and the progress dialog is not shown like i would like.
The way you do it makes the UI thread occupied by checking for internet connection. This makes the window manager unable to process showing of your ProgressDialog.
You should move this check, along with showing progress dialog, to the AsyncTask, like so:
private void startOnlineCheck() {
ProgressThread progress_thread = new ProgressThread();
progress_thread.execute();
}
private class ProgressThread extends AsyncTask<Void, Void, Void>{
ProgressDialog dialog;
protected void onPreExecute() {
dialog = new ProgressDialog(Activity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Loading Tracker...");
dialog.setCancelable(false);
dialog.show();
}
protected Void doInBackground(Void... params) {
ConnectivityManager cm = (ConnectivityManager) Activity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try{
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
// CODE to run when we're online
return null;
}catch (MalformedURLException e1) {
e1.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
Toast.makeText(Activity.this, "Internet Connexion Error", Toast.LENGTH_LONG).show();
// CODE to run when there's no connection
return null;
}
protected void onPostExecute(Void result) {
if (dialog.isShowing()) dialog.dismiss();
}
}
You can also pass a Context in constructor to ProgressThread.
Remember that if ProgressThread is an inner class of Activity (which is often the case) you can call any method of that activity from any method of ProgressThread.
Related
My application activity is having a block of code which I want to check the connected network having active connection before accessing FireBase Auth Login.
I created a class for networkState add a block of code for checking networkActiveConnection
private void networkState() throws IOException {
final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
assert conMgr != null;
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnectedOrConnecting()) {
Toast.makeText(getApplicationContext(),"Network connected",Toast.LENGTH_SHORT).show();
//checking active internet service
HttpURLConnection urlc = (HttpURLConnection)(new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(10000);
urlc.connect();
if(urlc.getResponseCode() == 200){
Toast.makeText(getApplicationContext(), "Network has active internet", Toast.LENGTH_SHORT).show();
//user login
signInUser();
}else {
Toast.makeText(getApplicationContext(), "No active internet connection", Toast.LENGTH_SHORT).show();
}
//end of checking active internet service
} else {
Toast.makeText(getApplicationContext(),"Network not connected",Toast.LENGTH_SHORT).show();
}
}
Application keeps crashing. I cant move without the solution.Where I missed? Is there any other method to check the connected network having active connection?
Finally I found an answer.Its actually happening due to the version. Up to Android 3.0 and above all long process activities will work at only AsyncTask
I restructured the actual internet connection in the device by load checking of Google.com. I don't know what it will happen when google.com is down.
The following code may help.
#SuppressLint("StaticFieldLeak")
public class activeConnection extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return false;
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
protected void onPostExecute(Boolean result) {
if (!result) { // code if not connected
AlertDialog.Builder builder = new AlertDialog.Builder(Customers.this, R.style.MyDialogTheme);
builder.setTitle("ALERT");
builder.setMessage("Activate your Internet connection and Try again");
builder.setCancelable(false);
builder.setPositiveButton(
"Retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
new activeConnection().execute();
}
});
AlertDialog alert11 = builder.create();
alert11.show();
} else { // code if connected
}
}
}
I am getting below exception
android.os.NetworkOnMainThreadException
because I don't use an async task to make the particular network operation. I have searched for this, but it got me so confused. Could someone make it work with async task and the particular functions?
Below are two functions i use :
1) isNetworkAvailable()
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
2) hasInternetAccess(Boolean showMessage)
When i want to display a toast i call this function, setting the parameter to true.
public boolean hasInternetAccess(Boolean showMessage) {
if (isNetworkAvailable()) {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0);
} catch (IOException e) {
Log.w("connection", "Error checking internet connection", e);
}
} else {
if(showMessage) // If i want to show the toast, it's true
showAToast("No Internet Connection", Toast.LENGTH_SHORT); // Just another function to show a toast
}
return false;
}
This is how you can use an AsyncTask by creating an inner class which extends AsyncTask.
private class NetworkInAsync extends AsyncTask<String, Void, Boolean> {
private Context context;
private Activity activity;
NetworkInAsync(Activity activity) {
this.context = activity.getApplicationContext();
this.activity = activity;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(Boolean result) {
// Do something with the result here
}
#Override
protected Boolean doInBackground(String... params) {
if (isNetworkAvailable()) {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0);
} catch (IOException e) {
Log.w("connection", "Error checking internet connection", e);
}
} else {
if(showMessage) // If i want to show the toast, it's true
showAToast("No Internet Connection", Toast.LENGTH_SHORT); // Just another function to show a toast
}
return false;
}
}
You can execute the AsyncTask as follows
new NetworkInAsync(this).execute();
I would still recommend you go through the docs here to clarify yourself how AsyncTask works in Android.
The code should work when you call it from AsyncTask's doInBackground method
call test();
private void test() {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setConnectTimeout(1500);
urlc.connect();
}
You can check the network connection before making the call, but any how, you should catch the exception in TimeOut exception. So I dont think, that you have any much benifit to check the connectivity before making the call.
I wrote this code for checking INTERNET and it works but i have a problem that when wifi is on but internet does not exist!! in this situation my program force closed.
private class NetCheck extends AsyncTask<String,String,Boolean>
{
#Override
protected Boolean doInBackground(String... args){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(1000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
when internet connected or disconnected its work but when wifi on and internet not exist its not work an application force close!
#Override
protected void onPostExecute(Boolean th){
if(th == true){
getcountHA();
}
else{
ShowAlertDialog();
}
}
}
whats problem!!
its my logcat
Check with this method:
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com"); //You can replace it with your name
if (ipAddr.equals("")) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
}
Credits
my codes for check INTERNET are true and work great and the force close is because of another place. when INTERNET are not available the server give me some String codes like (
I am using isConnected() method to test Internet is working or not, However, When Mobile data is on but net is not working (happens when travelling) or Wifi is on but not connected to internet, the method returns true and my app crashes.
I did some finding and found that I need to ping Google also
so I tried using internetConnectionAvailable(1000). Even if Internet is working fine, this method sometimes return false. Can anybody help me with a better solution?
//Check device has Internet connection
public boolean isConnected() {
ConnectivityManager connMgr = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else {
//Custom Toast method
showToast("Unable to connect to Internet !");
return false;
}
}
//ping google and test internet connection
private boolean internetConnectionAvailable(int timeOut) {
InetAddress inetAddress = null;
try {
Future<InetAddress> future = Executors.newSingleThreadExecutor().submit(new Callable<InetAddress>() {
#Override
public InetAddress call() {
try {
return InetAddress.getByName("www.google.com");
} catch (UnknownHostException e) {
return null;
}
}
});
inetAddress = future.get(timeOut, TimeUnit.MILLISECONDS);
future.cancel(true);
} catch (InterruptedException e) {
} catch (ExecutionException e) {
} catch (TimeoutException e) {
}
Log.e("Google",String.valueOf(inetAddress));
return inetAddress!=null && !inetAddress.equals("");
}
Check whether the internet is connected/not... If yes androidTask() is called.
if (haveNetworkConnection()) {
new androidTask().execute();
} else {
Toast.makeText(context, "No Network Connection", Toast.LENGTH_SHORT).show();
}
Called method of haveNetworkConnection():
public boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
Method contains HTTP request:
class androidTask extends AsyncTask<Void, Void, String> {
String BASE_URL = http://abc.def.com/";
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(Void... params) {
HttpURLConnection con = null;
InputStream is = null;
hashMapPost.put("report", "users");
try {
con = (HttpURLConnection) (new URL(BASE_URL)).openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.connect();
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(hashMapPost));
writer.flush();
writer.close();
os.close();
buffer = new StringBuffer();
int responseCode = con.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null)
buffer.append(line).append("\r\n");
is.close();
}
con.disconnect();
return buffer.toString();
} catch (Throwable t) {
t.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (Throwable t) {
}
try {
if (con != null) {
con.disconnect();
}
} catch (Throwable t) {
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
I have developed a code to check if a url exists but it is not doing anything, could you please point out my mistake?
public void main(String s[]) {
String URLName = "http://www.google.com/";
Log_in uRLExists = new Log_in();
uRLExists.checkURLExists(URLName);
}
public void checkURLExists(String URLName) {
try {
HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
HttpURLConnection.setFollowRedirects(false);
con.setRequestMethod("HEAD");
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
Toast.makeText(getBaseContext(), "URL Exist", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "URL not Exists", Toast.LENGTH_SHORT).show();
}
}
catch(UnknownHostException unknownHostException){
}
catch (Exception e) {
e.printStackTrace();
}
}
On the Toasts, assuming this code is within an Activity, change getBaseContext() to getApplicationContext().
You can't do Network on MainThread. You are most likely getting android.os.NetworkOnMainThreadException. You should call checkURLExists() from a worker thread.
You could use AsyncTask class to do a network operation.
public class UrlChecker extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
String url = params[0];
// Check your URL here
return true;
}
#Override
protected void onPostExecute(Boolean exists) {
// Do something with your result
}
}
You did not call connect method.
After con.setRequestMethod("HEAD");
Add this: con.connect();
BTW, you should put the code in a new thread. Don't run it on the main thread, it will hang the App.
Try this:
new Thread(){
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
try {
URL url = new URL(customURL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("HEAD");
con.connect();
Log.i(TAG, "con.getResponseCode() IS : " + con.getResponseCode());
if(con.getResponseCode() == HttpURLConnection.HTTP_OK){
Log.i(TAG, "Sucess");
}
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG, "fail");
}
}
}.start();