Active Internet Connection on connected network - android

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
}
}
}

Related

Perform network operation to check if user has internet connection with async task

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.

How Can check web service available in mono android?

i used this code to call web service from xamarin :
void OnWebserviceRetrievedInformation1 (object sender, EventArgs e)
{
MyService.MonoDataService ms = new MyService.MonoDataService ();
ms.Url = "http://10.0.2.2:11339/MonoDataService.asmx";
TextView tx=FindViewById<TextView> (Resource.Id.textView1);
tx.Text = ms.Hello ("Hadi");
}
but when web server is offline my apps is in loop !
how can check web service is available and then call ?
Try something like this :
public bool IsConnected()
{
try{
var cm = (ConnectivityManager)GetSystemService (Context.ConnectivityService);
var netInfo = cm.ActiveNetworkInfo;
if (netInfo != null && netInfo.IsConnected)
{
//Network is available but check if we can get access from the network.
var url = new URL("http://www.Google.com/");
var urlc = (HttpURLConnection) url.OpenConnection();
urlc.SetRequestProperty("Connection", "close");
urlc.ConnectTimeout = 2000; // Timeout 2 seconds.
urlc.Connect();
if (urlc.ResponseCode == 200) //Successful response.
return true;
else {
Log.Debug ("No Internet", "No internet connection.");
return false;
}
}
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine (ex.Message);
}
return false;
}
Check Using this method:
public boolean isConnected()
{
try{
ConnectivityManager cm = (ConnectivityManager) getSystemService
(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
//Network is available but check if we can get access from the network.
URL url = new URL("http://10.0.2.2:11339/MonoDataService.asmx"");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(2000); // Timeout 2 seconds.
urlc.connect();
if (urlc.getResponseCode() == 200) //Successful response.
{
return true;
}
else
{
Log.d("NO INTERNET", "NO INTERNET");
return false;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return false;
}

force close my application when wifi "on" but internet not exist

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 (

How to make a ping in Android to Google

I'm trying to find the way to know when an user has Internet connection, since now I've got this method :
public boolean isNetworkOnline() {
boolean status=false;
try{
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getNetworkInfo(1);
if (netInfo != null && netInfo.getState()==NetworkInfo.State.CONNECTED) {
status= true;
}
}catch(Exception e){
e.printStackTrace();
return false;
}
return status;
}
This method returns true if user is CONNECTED but not if user has INTERNET CONNECTION, so I thought to if this method returns true, call another method to check if the user has connection to internet. For example someone can be connected to a router but without internet connection so I want to know when the user has internet connection or not.
I've read this answer and this other but all of them is returning me false when I've got Internet connection.... I thought that make a method that makes a ping to www.google.com it's a good approach to know if someone has internet connection so I tried to get this way but it didn't work for me...
Any idea or good approach (if it's better than my thoughts is better) to know when the user has internet connection?
The Simple Way To Check Internet Connectivity
public boolean isConnectingToInternet() {
if (networkConnectivity()) {
try {
Process p1 = Runtime.getRuntime().exec(
"ping -c 1 www.google.com");
int returnVal = p1.waitFor();
boolean reachable = (returnVal == 0);
if (reachable) {
System.out.println("Internet access");
return reachable;
} else {
return false;
}
} catch (Exception e) {
return false;
}
} else
return false;
}
private boolean networkConnectivity() {
ConnectivityManager cm = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
How To Call it
if (isConnectingToInternet()) {
// internet is connected and work properly...
}
else {
// something went wrong internet not working properly...
}
So simply copy and past the above two methods where you want to check the Internet connectivity. After that check the condition if (isConnectingToInternet()) { }
Can you try this method?
public boolean checkInternectConnection() {
try {
InetAddress inAddress= InetAddress.getByName("http://google.com");
if (inAddress.equals("")) {
return false;
} else {
return true;
}
} catch (Exception e) {
return false;
}
}
Please check this answer out and see if its helpful or not
You can try out this code
try {
URL url = new URL("http://"+params[0]);
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("User-Agent", "Android Application:"+Z.APP_VERSION);
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
Main.Log("getResponseCode == 200");
return new Boolean(true);
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
this is how i fixed this and i use it as a Utility method which can be called from any activity/fragment etc...:
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}//check if Wifi or Mobile data is enabled
private static class NetworkAsync extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... voids) {
try {
HttpURLConnection urlConnection = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlConnection.setRequestProperty("User-Agent", "Android");
urlConnection.setRequestProperty("Connection", "close");
urlConnection.setConnectTimeout(1500);
urlConnection.connect();
return (urlConnection.getResponseCode() == 204 &&
urlConnection.getContentLength() == 0);
} catch (IOException e) {
// Error checking internet connection
}
return false;
}
}//network calls shouldn't be called from main thread otherwise it will throw //NetworkOnMainThreadException
and now you simply need to call this method from anywhere you want:
public static boolean checkInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
try {
//used execute().get(); so that it gets awaited and returns the result
//after i receive a response
return new NetworkAsync().execute().get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return false;
}

Run progress Dialog in Asnyctask while process running

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.

Categories

Resources