Inetrnet connection checking thread Android - android

In my main activity , there is a internet status TextView . In that TextView I want to show whether the internet connection is enabled or not. I have to refresh the status in every 10 sec.
I know that i have to do this in a separate thread but I tried a lot. I'm not getting perfect solution.
public class MainActivity extends Activity {
ImageView imageView;
TextView internetStausTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
internetStausTextView = (TextView) findViewById(R.id.tv1);
new InternetChecker();
}
public class InternetChecker implements Runnable {
Thread t;
boolean internetStatus;
ConnectivityManager conMgr;
public InternetChecker() {
t = new Thread(this);
t.start();
conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
}
public void run() {
while (true) {
if (conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
|| conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING) {
internetStatus = true;
} else if (conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED
|| conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {
internetStatus = false;
}
runOnUiThread(new Runnable() {
public void run() {
if (internetStatus)
internetStausTextView.setText("connected");
else
internetStausTextView.setText("Not connected.");
}
});
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
}
}
}
Here is my code ....
But it is affecting performance of the app.
Can any one help me to take out the sub class InternetChecker to a separate file.

Try this :
EDITED :
First Create one Handler and Thread running flag:
Handler mHandler = new Handler();
boolean isRunning = true;
Then, use this thread from your onCreate() method :
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (isRunning) {
try {
Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// Write your code here to update the UI.
displayData();
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
Then, declare this method which called by your handler at every 10 seconds :
private void displayData() {
ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf=cn.getActiveNetworkInfo();
if(nf != null && nf.isConnected()==true )
{
Toast.makeText(this, "Network Available", Toast.LENGTH_SHORT).show();
myTextView.setText("Network Available");
}
else
{
Toast.makeText(this, "Network Not Available", Toast.LENGTH_SHORT).show();
myTextView.setText("Network Not Available");
}
}
To stop thread call this :
isRunning = false;
That's It.
Thanks.

DONOT use service.
User TimerTask and Timer to check and update internet connection regularly. Updating the UI from a Timer is the best example for your need.
Happy coding :)

First you need to create a Timer task to check network connectivty
_tv = (TextView) findViewById( R.id.TextViewTime );
UpdateNetworkInfo();
Timer _t = new Timer();
String conn;
_t.scheduleAtFixedRate( new TimerTask() {
#Override
public void run() {
ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf=cn.getActiveNetworkInfo();
if(nf != null && nf.isConnected()==true )
{
conn = " Avaialable";
}
else
{
conn = " Not Available";
}
}
}, 1000, 1000 );
Then update network info in the UI thread.
protected void UpdateNetworkInfo()
{
runOnUiThread(new Runnable()
{
public void run()
{
_tv.setText( "Network" + conn );
}
});
}
Dont forget to add appropriate permissions to the manifest file.

public boolean isNetworkAvailable(){
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected()){
Toast.makeText(this, "Network is available", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Network is not available", Toast.LENGTH_LONG).show();
}
return true;
}

Related

How to Check Internet Connection using Asynctask

Hi I have been seeing tutorials and questions here in stack on how to check if the current user has a active connection to the internet. I am trying to do it myself but I have been having trouble on applying it in an AsyncTask.
I have tried it myself but I think I am doing something wrong, My knowledge in AsyncTasks are not that developed. What am I doing wrong?
Thanks in advance! :D
This is my MainActivity:
private Button checkIntrnetButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkIntrnetButton = (Button) findViewById(R.id.checkInternetButton);
checkIntrnetButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isOnline())
{
Toast.makeText(MainActivity.this,"YOU ARE ONLINE", Toast.LENGTH_SHORT).show();
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
}
else
{
Toast.makeText(MainActivity.this,"YOU ARE NOT ONLINE", Toast.LENGTH_SHORT).show();
}
}
});
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
if (isOnline()) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://clients3.google.com/generate_204").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
boolean url = (urlc.getResponseCode() == 200);
String str = String.valueOf(url);
return str;
} catch (IOException e) {
}
} else {
Toast.makeText(MainActivity.this, "NO CONNECTION", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
progressDialog.dismiss();
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this,
"ProgressDialog",
"CHECKING NETWORK CONNECTION");
}
}
You should check before running the asynctask and only once, you don't need to check again inside async.
if(isOnline()) {
new AsyncTaskRunner().execute();
} else {
Toast.makeText(MainActivity.this, "NO CONNECTION", Toast.LENGTH_SHORT).show();
}
Since I am using volley for all my inserting and retrieving of data, I have been researching and experimenting about with the volley onErrorResponse. And I have found out about "NetworkError, NoConnectionError, and TimeoutError" and it help me solve the problem.
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
Toast.makeText(alcoholType.this,"THERE IS A PROBLEM WITH YOUR INTERNET CONNECTION", Toast.LENGTH_SHORT).show();
loading.dismiss();
}
else if (error instanceof NoConnectionError) {
Toast.makeText(alcoholType.this,"PLEASE SWITCH ON WIFI OR DATA", Toast.LENGTH_SHORT).show();
loading.dismiss();
}
else if (error instanceof TimeoutError) {
Toast.makeText(alcoholType.this,"Connection TimeOut! Please check your internet connection.", Toast.LENGTH_SHORT).show();
loading.dismiss();
}
}
Thanks again for everyone that helped! :D

Check Internet during SplashScreen

Well, after my SplashScreen screen. My app will check for an Internet connection. if there is internet available, it will call the WebView. Otherwise, it will call one Activity of error.
But how do I pair to check the internet DURING SplashScreen?
ACTIVITY SPLASH SCREEN:
public class Splash extends Activity{
private static int tempo_splash = 1000;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Para o layout preencher toda tela do cel (remover a barra de tit.)
new Timer().schedule(new TimerTask() {
public void run() {
finish();
Intent intent = new Intent();
intent.setClass(Splash.this, MainActivity.class); //Chamando a classe splash e a principal (main)
startActivity(intent);
}
}, 2000);
}
}
MY CLASS CheckINTERNET:
public class CheckInternet extends Activity{
boolean status = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.internet);
Button btnStatus = (Button) findViewById(R.id.check_btn);
btnStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status = checkInternetConnection();
if (status) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent mainIntent = new Intent(CheckInternet.this, MainActivity.class);
CheckInternet.this.startActivity(mainIntent);
CheckInternet.this.finish();
}
}, 5000);
}
else {
Toast.makeText(getApplicationContext(), "You don't have Internet connection. Try Again", Toast.LENGTH_LONG).show();
}
}
});
}
public boolean checkInternetConnection() {
ConnectivityManager connectivity = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] inf = connectivity.getAllNetworkInfo();
if (inf != null) {
for (int i = 0; i < inf.length; i++) {
return true;
}
}
}
return false;
}
}
try this code... maybe help you
public class SplashScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.splash_screen);
if(isWorkingInternetPersent()){
splash();
}
else{
showAlertDialog(SplashScreen.this, "Internet Connection",
"You don't have internet connection", false);
}
}
public void splash() {
Thread timerTread = new Thread() {
public void run() {
try {
sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent intent = new Intent(getApplicationContext(), New_Main_Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
};
timerTread.start();
}
public boolean isWorkingInternetPersent() {
ConnectivityManager connectivityManager = (ConnectivityManager) getBaseContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
// alertDialog.setIcon((status) ? R.mipmap.ic_launcher : R.mipmap.ic_launcher);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
System.exit(0);
}
});
// Showing Alert Message
alertDialog.show();
}
You should not really have an Intent just for checking connectivity. My suggestion is to create a "utility" class - call is MyConnectivityChecker and in there you add a static method (isConnected) with the following code:
public class MyConnectivityChecker {
public static boolean isConnected(Context context){
boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
connected = (wifi.isAvailable() && wifi.isConnectedOrConnecting() || (mobile.isAvailable() && mobile.isConnectedOrConnecting()));
return connected;
}
}
Then in your Splash Activity wherever you want to check connectivity, you call the isConnected method like this:
MyConnectivityChecker.isConnected(this)
For example you could do something like this:
if(MyConnectivityChecker.isConnected(this)){
//connectivity available
}
else{
//no connectivity
}
I hope this helps. Give it a try and let me know.
what you can do is check for internet connection inside of your timer of SplashScreen.
new Timer().schedule(new TimerTask() {
public void run() {
if(isOnline()){
Intent intent = new Intent(Splash.this,WebViewActivity.class);
startActivity(intent);
finish();
}else{
Intent intent = new Intent(Splash.this,ErrorActivity.class);
startActivity(intent);
finish();
}
}
}, 2000);
And for internet checking you can use this method.
public boolean isOnline() {
System.out.println("executeCommand");
Runtime localRuntime = Runtime.getRuntime();
try {
int i = localRuntime.exec("/system/bin/ping -c 1 8.8.8.8")
.waitFor();
System.out.println(" mExitValue " + i);
boolean bool = false;
if (i == 0) {
bool = true;
}
return bool;
} catch (InterruptedException localInterruptedException) {
localInterruptedException.printStackTrace();
System.out.println(" Exception:" + localInterruptedException);
return false;
} catch (IOException localIOException) {
localIOException.printStackTrace();
System.out.println(" Exception:" + localIOException);
}
return false;
}
NOTE: Add this method in your SplashScreen outside the onCreate() methode.
Happy Coding..
Create Following Utility Class as below :
public class Utility {
/**
* This function check <u>Mobile Data</u> or <u>WiFi</u> is switched on or not..<br />
* It will be return <b>true</b> when switched on and return <b>false</b> when switched off.<br />
* <br />
* Developed by <b>Suthar Rohit</b>
*
* #param context {#link Context} of activity
* #return true if <u>Mobile Data</u> or <u>WiFi</u> is switched on.
*/
public static boolean isOnline(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cm.getActiveNetworkInfo();
return nInfo != null && nInfo.isConnected();
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
and use as below in splash screen :
if(Utility.isOnline()) {
// INTERNET AVAILABLE
} else {
// INTERNET NOT AVAILABLE
}
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
public class SplashACtivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
NetworkInfo activeNetwork = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnectedOrConnecting()) {
// Load Webview
startActivity(new Intent(SplashACtivity.this, WebViewActivity.class));
} else {
// Show No internet
startActivity(new Intent(SplashACtivity.this, NoInternetACtivity.class));
}
}
}, 5000);
}
}

checking network connection android

Heres my code for checking the network connection of my app.I want my app run only when it is connected to a network and closes it if not. The code was running with no errors but the problem is the alertdialog show many times.
private void checkConnectivity(){
final Thread checkConnection = new Thread(new Runnable(){
#Override
public void run()
{
while (checkCon == true){
if(!isNetworkAvailable(MainActivity.this)) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new AlertDialog.Builder(MainActivity.this)
.setMessage("No network connection.")
.setCancelable(false)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int which) {
checkCon = false;
finish();
}
}).show();
}
});
} else {
checkCon = true;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
});
checkConnection.start();
}
Answer by harism, thanks
private void checkConnectivity(){
final Thread checkConnection = new Thread(new Runnable(){
#Override
public void run()
{
while (checkCon == true){
if(!isNetworkAvailable(MainActivity.this)) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new AlertDialog.Builder(MainActivity.this)
.setMessage("No network connection.")
.setCancelable(false)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int which) {
finish();
}
}).show();
checkCon = false;
}
});
} else {
checkCon = true;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
});
checkConnection.start();
}
Add a new method inside your current Activity or Fragment:
private boolean isNetworkAvailable(){
boolean available = false;
/** Getting the system's connectivity service */
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
/** Getting active network interface to get the network's status */
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if(networkInfo !=null && networkInfo.isAvailable())
available = true;
/** Returning the status of the network */
return available;
}
And here is how to use it. You can use it inside onCreate() method:
if (isNetworkAvailable() == true){ // if network is available
// do your thing here
...
}else{ // "else" means that the network is not available
// do your thing here
...
}

How to perform AsyncTask for checking internet connection

I have the following code, and what I'm trying to do is to programmatically check if there is an internet connection or not.
Since I'm getting a NetworkOnMainThreadException, and have been advised to use AsyncTask.
I want to perform network operation on hasActiveInternetConnection(Context context)and return true if connected to a network, else false .
How do I do this using AsyncTask?
public class NetworkUtil extends AsyncTask<String, Void, String>{
Context context;
public NetworkUtil(Context context){
this.context = context;
}
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
if (new CheckNetwork(context).isNetworkAvailable())
{
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
boolean url= (urlc.getResponseCode() == 200);
String str = String.valueOf(url);
return str;
} catch (IOException e) {
}
}
// your get/post related code..like HttpPost = new HttpPost(url);
else {
Toast.makeText(context, "no internet!", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
use this class for checking internet connectivity...
public class CheckNetwork {
private Context context;
public CheckNetwork(Context context) {
this.context = context;
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
then.....
use the this ASynTask for httppost.
public class NetworkUtil extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(YourActivity.this);
dialog.setMessage("Loading...");
dialog.setCancelable(false);
dialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
if (new CheckNetwork(YourActivity.this).isNetworkAvailable()) {
// your get/post related code..like HttpPost = new HttpPost(url);
} else {
// No Internet
// Toast.makeText(YourActivity.this, "no internet!", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
There is no way to get an Internet connexion state, you will always have the network connection state.
But I found a pretty nice answer here: you send a request to google.com !! :) you can also try to ping to google by unix commandes if you want !!
here the guy is using a thread , and waiting a little bit for the answer, then returning a boolean . you do your staff in the handler . this is his code :
public static void isNetworkAvailable(final Handler handler, final int timeout) {
// ask fo message '0' (not connected) or '1' (connected) on 'handler'
// the answer must be send before before within the 'timeout' (in milliseconds)
new Thread() {
private boolean responded = false;
#Override
public void run() {
// set 'responded' to TRUE if is able to connect with google mobile (responds fast)
new Thread() {
#Override
public void run() {
HttpGet requestForTest = new HttpGet("http://m.google.com");
try {
new DefaultHttpClient().execute(requestForTest); // can last...
responded = true;
}
catch (Exception e) {
}
}
}.start();
try {
int waited = 0;
while(!responded && (waited < timeout)) {
sleep(100);
if(!responded ) {
waited += 100;
}
}
}
catch(InterruptedException e) {} // do nothing
finally {
if (!responded) { handler.sendEmptyMessage(0); }
else { handler.sendEmptyMessage(1); }
}
}
}.start();
}
Then, I define the handler:
Handler h = new Handler() {
#Override
public void handleMessage(Message msg) {
if (msg.what != 1) { // code if not connected
} else { // code if connected
}
}
};
...and launch the test:
isNetworkAvailable(h,2000); // get the answser within 2000 ms
Your AsyncTask should look like this:
private class NetworkUtilTask extends AsyncTask<Void, Void, Boolean>{
Context context;
public NetworkUtilTask(Context context){
this.context = context;
}
protected Boolean doInBackground(Void... params) {
return hasActiveInternetConnection(this.context);
}
protected void onPostExecute(Boolean hasActiveConnection) {
Log.d(LOG_TAG,"Success=" + hasActiveConnection);
}
}
You would then execute it like the following:
NetworkUtilTask netTask = new NetworkUtilTask(context);
netTask.execute();

Create a dialogbox inside a thread while checking for an internet connection

I am trying to find out if my app is connected to the internet or not. I have a timeout set to 3 seconds. Sometimes the Internet Check will come back as "Not Connected" (even if I do have an internet connection) and sometimes it doesn't. Why does it take longer sometimes to check than others? Would I be able to have a dialogbox or something to popup while this is being checked?
public void isNetworkAvailable(final Handler handler)
{
new Thread()
{
private boolean responded = false;
#Override
public void run()
{
new Thread()
{
#Override
public void run()
{
HttpGet requestForTest = new HttpGet("http://m.google.com");
try
{
new DefaultHttpClient().execute(requestForTest);
responded = true;
}
catch (Exception e)
{
}
}
}.start();
try
{
int waited = 0;
while (!responded && (waited < 3000))
{
sleep(100);
if (!responded)
{
waited += 1000;
}
}
}
catch (InterruptedException e)
{
} // do nothing
finally
{
if (!responded)
{
handler.sendEmptyMessage(0);
}
else
{
handler.sendEmptyMessage(1);
}
}
}
}.start();
}
Handler h = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if (msg.what != 1)
{ // code if not connected
Log.i("Internet check", "Not connected");
}
else
{ // code if connected
Log.i("Internet check", "Connected");
}
}
};
Use the following code
if(!haveInternet()){
<Your Alert Dialog Here>
}
private boolean haveInternet() {
NetworkInfo info = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
return true;
}
return true;
}
are you consider use this http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html and/or register a BroadcastReceiver to notify it when connection is down/up, then you can handle it in any place of your application?
public class CustomApplication extends Application {
public static final String INTERNET_ACTION = "internet_action";
public static final String EXTRA_STATUS = "status";
#Override
public void onCreate() {
super.onCreate();
monitorNetworkAvailability();
}
private void monitorNetworkAvailability() {
//
// Improve the way to handle Thread
//
new Thread() {
private boolean responded = false;
#Override
public void run() {
while (true) {
new Thread() {
#Override
public void run() {
HttpGet requestForTest = new HttpGet("http://m.google.com");
try {
new DefaultHttpClient().execute(requestForTest);
responded = true;
} catch (Exception e) {
}
}
}.start();
try {
int waited = 0;
while (!responded && (waited < 3000)) {
sleep(100);
if (!responded) {
waited += 1000;
}
}
} catch (InterruptedException e) {
} // do nothing
finally {
Intent i = new Intent(INTERNET_ACTION);
i.putExtra(EXTRA_STATUS, responded);
sendBroadcast(i);
}
try {
Thread.sleep(1 * 60 * 1000);
} catch (InterruptedException e) {
}
}
}
}.start();
};
}
class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, i);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
IntentFilter i = new IntentFilter(CustomApplication.INTERNET_ACTION);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
boolean responded = intent.getBooleanExtra(CustomApplication.EXTRA_STATUS, false);
if (!responded) {
Toast.makeText(MyActivity.this, "No connection", Toast.LENGTH_SHORT).show();
}
}
};
}
public static Boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if(ni != null && ni.isConnected())
return true;
//Toast.makeText(context, context.getString(R.string.no_internet_connection), Toast.LENGTH_SHORT).show();
return false;
}
Requires permission:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
Edit:
As you correctly point out this is not a solid solution. In my case (which I indeed failed to mention) this is sufficient as a first check paired with LocationClient.isConnected().
Looking at your code I would think that it is worth taking a look at LocationClient, even if you are not planning to use location awareness of you app.
My reasoning for this is that you get rid of the need to repeatedly use resources to check if you have a valid connection. LocationClient uses the already in place communication with Google Play to tell you whether you are connected or not.
This solution of course only works if you assume that your users have a Google Account added to their device.
Here is a link to the official guidelines: http://developer.android.com/training/location/retrieve-current.html the onConnected and onDisconnected parts are found in the Define Location Services Callbacks section.
You are right. Your problem is that, the device checks for internet connection, and sometimes get a response from the router which says it cannot connect to internet, but that itself is a response, so your code might think that there is a response. Below is a sample method to test if you really can connect to the internet.
public static boolean hasActiveInternetConnection()
{
try
{
new Socket().connect(new InetSocketAddress("google.com", 80), 4000);
return true;
} catch (Exception e)
{
return false;
}
}
Then inside your activity you can call. (Make sure not to run this inside the MAIN/UI thread. Use an async or thread/handler/runnable strategy)
if(hasActiveInternetConnection())
{
//yey I have internet
}
else
{
//no internet connection
}
I was able to complete this by putting it inside an AsyncTask.
class online extends AsyncTask<String, String, String>
{
boolean responded = false;
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog2 = new ProgressDialog(Main.this);
pDialog2.setMessage("Checking internet, please wait...");
pDialog2.setIndeterminate(false);
pDialog2.setCancelable(false);
pDialog2.show();
}
protected String doInBackground(String... args)
{
HttpGet requestForTest = new HttpGet("http://m.google.com");
try
{
new DefaultHttpClient().execute(requestForTest); // can
responded = true;
}
catch (Exception e)
{
}
try
{
int waited = 0;
while (!responded && (waited < 5000))
{
mHandler.postDelayed(new Runnable()
{
public void run()
{
}
}, 100);
waited += 100;
}
}
finally
{
if (!responded)
{
h.sendEmptyMessage(0);
}
else
{
h.sendEmptyMessage(1);
}
}
return null;
}
protected void onPostExecute(String file_url)
{
pDialog2.dismiss();
}
}

Categories

Resources