How to perform AsyncTask for checking internet connection - android

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();

Related

Show ProgressDialog fails

I know that there is a lot of questions about this, but I'm desperated...
I'm trying to show a Dialog while doing an AsyncTask, that must be easy but I'm no able to do it...
I had tried with .execute() and .get() and I had put a for to make the task take a long time, but nothing..
Here is my class:
public class OrdenNuevaActivity extends Activity {
#Override
protected void onCreate(Bundle bundle) {
Log.v("FLUJO", this.getClass().toString());
super.onCreate(bundle);
setContentView(R.layout.activity_orden_nueva);
aceptarOrdenNuevaButton = (Button) findViewById(R.id.aceptarOrdenNuevaButton);
aceptarOrdenNuevaButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoStringConSpinnerDentroDeLaClase tareaCambiarEstadoOrdenEnBDServer = new TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoStringConSpinnerDentroDeLaClase(idOrden, Estados.ACEPTADO,OrdenNuevaActivity.this);
try {
tareaCambiarEstadoOrdenEnBDServer.execute();
} catch (Exception e) {
e.printStackTrace();
}
Toast toast1 = Toast.makeText(getApplicationContext(), "Orden Aceptada", Toast.LENGTH_SHORT);
toast1.show();
NotificationManager notifManager= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notifManager.cancelAll();
UtilsVictor.addPuebloAlAceptarOrden(context,terminoOrdenAceptadaDetalleTV.getText().toString());
finish();
} else {
AlertDialog alertDialog = new AlertDialog.Builder(OrdenNuevaActivity.this).create();
alertDialog.setTitle("ERROR!");
alertDialog.setMessage("NO hay cobertura, vuelva a intentarlo mas tarde");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setIcon(R.drawable.common_signin_btn_icon_normal_light);
alertDialog.show();
}
}
});
}
public class TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoStringConSpinnerDentroDeLaClase extends AsyncTask<String,Integer,Boolean>{
private static final String TAG = "AppMovil";
private Integer mOrdenId;
private String mEstadoString;
boolean resul = true;
boolean tareaRealizada = false;
boolean catchPasado = false;
private Context mContext;
private ProgressDialog mPD;
public TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoStringConSpinnerDentroDeLaClase(Integer idO ,String estadoO, Context cntx) {
mContext = cntx;
mOrdenId = idO;
mEstadoString = estadoO;
mPD = new ProgressDialog(mContext);
}
public boolean getResultado(){
return resul;
}
public boolean getTareaRealizada(){
return tareaRealizada;
}
public boolean getCatchPasado(){
return catchPasado;
}
#Override
protected void onPreExecute() {
mPD.setTitle("Please Wait..");
mPD.setMessage("Loading...");
mPD.setCancelable(false);
mPD.show();
}
#Override
protected Boolean doInBackground(String... params) {
for(int i=0; i<999999;i++){
Log.v("A", "A");
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("id", mOrdenId);
jsonObject.put("estado", mEstadoString);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(URIS.URI_TareaCambiarEstadoOrdenEnBDServerPorIdOrdenYEstadoString);
post.setHeader("content-type", "application/json");
try {
StringEntity stringEntity = new StringEntity(jsonObject.toString());
post.setEntity(stringEntity);
HttpResponse response = httpClient.execute(post);
int responseCode = response.getStatusLine().getStatusCode();
if(responseCode >200 & responseCode < 400) {
Log.v(TAG, "Orden Enviada OK a nuestro Server");
tareaRealizada = true;
resul = true;
} else {
Log.v(TAG, "FALLO al Enviar Orden a nuestro Server");
resul = false;
tareaRealizada = true;
}
} catch (Exception e) {
catchPasado = true;
resul = false;
e.printStackTrace();
}
return resul;
}
#Override
protected void onCancelled() {
if(mPD.isShowing()){
mPD.dismiss();
}
}
#Override
protected void onPostExecute(Boolean result) {
if(mPD.isShowing()){
mPD.dismiss();
}
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
}
}
Where is the mistake?

Check Internet Connection from an AsyncTask

This is not a duplicate
I want to check real-time internet connection from my activity using AsyncTaskand Handler to display or hide TexView if a connection is available or not. But it doesn't work.
My code throws NetworkOnMainThreadException even using AsyncTask
I'm using this code:
class CheckNetWorkConnection extends AsyncTask<String, Void,Boolean>{
MyActivity activity;
public checkNetWorkConnection(MyActivity activity) {
this.activity= activity;
}
#Override
protected Boolean doInBackground(String... strings) {
boolean networkAvalaible;
try {
URL myUrl = new URL("https://www.stackoverflow.com");
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
networkAvalaible = true;
} catch (Exception e) {
//I'm catching NetworkInMainThreadException here
e.printStackTrace();
networkAvalaible = false;
}
}
});
// doInBackground always retun false
return networkAvalaible;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
// Using handler to repeat Task
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (aBoolean){
activity.noConnection.setVisibility(View.GONE);
}else {
activity.noConnection.setVisibility(View.VISIBLE);
}
}
},3000);
super.onPostExecute(aBoolean);
}
}
to use it, you call
new CheckNetWorkConnection().execute();
you will want your async task to run indefinitely until an internet connection is lost. your current code will only check one time.
you need to change your codes to be polling for it to work.
#Override
protected Boolean doInBackground(String... strings) {
boolean networkAvalaible = false;
do {
try {
URL myUrl = new URL("https://www.stackoverflow.com");
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
networkAvalaible = true;
sleep(5000); //check connection every 5 seconds.
// you can call publish progress here to tell your process that
// connection is available
} catch (Exception e) {
//I'm catching NetworkInMainThreadException here
e.printStackTrace();
networkAvalaible = false;
}
} while (networkAvalaible);
//you only exit and asyncTask when connection is lost.
return networkAvalaible;
}
AsyncTask is not the right way to do it though... take a look at the following article below.
https://www.grokkingandroid.com/android-getting-notified-of-connectivity-changes/
Put this Class into your util Package to chack internet connection anywhere into your project.
ConnectionDetector.java
package util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* Created by Pranav on 29/08/16.
*/
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
}
Here is a code snippet if MainActivity.java to check internet connection and if internet connection is on then call asynctask otherwise give toast message.
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import java.net.URL;
import java.net.URLConnection;
import util.ConnectionDetector;
/**
* Created by Pranav on 29/08/16.
*/
public class CaseDetaiksActivity extends Activity {
public static Context context;
ConnectionDetector mConnectionDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
mConnectionDetector = new ConnectionDetector(context);
setContentView(R.layout.activity_mail);
if (mConnectionDetector.isConnectingToInternet()) {
MyAyncTask MyTask = new MyAyncTask();
MyTask.execute();
} else {
Toast.makeText(context, getString(R.string.please_check_internet), Toast.LENGTH_SHORT).show();
}
}
public static class MyAyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
// You can track you progress update here
}
#Override
protected Void doInBackground(Void... params) {
try {
URL myUrl = new URL("https://www.stackoverflow.com");
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
} catch (Exception e) {
//I'm catching NetworkInMainThreadException here
e.printStackTrace();
}
return null;
}
}
}
Hope this helps you
a .Create a broadcast receiver class
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
if(checkInternet(context)){
Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show();
}
}
public boolean checkInternet(Context context) {
ServiceManager serviceManager = new ServiceManager(context);
if (serviceManager.isNetworkAvailable()) {
return true;
} else {
return false;
}
}
}
b. Create a Service manager class
public class ServiceManager {
Context context;
public ServiceManager(Context base) {
context = base;
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
}
Register permissions in the Android Manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Declare Broadcast Receiver in the Android Manifest
<receiver android:name=".receivers.NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
In your activity :
a. register your broadcast receiver in onResume()
registerReceiver(new NetworkChangeReceiver() , new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
b. unregister your broadcast receiver in onPause();
unregisterReceiver(new NetworkChangeReceiver());

Context issue with AsyncTask

When clicking a button then I want to show an alertDialog showing an animationDrawable and performing an asyncTask. I found that when I set the context of the dialog to getApplicationContext() then the app crashed , and when I set the context to the parent class activity then the dialog is dismissed very well when I call the dismiss method in the activity class ; but when I want to dismiss it in the onPostExecute of the AsyncTask then the dialog is not dismissed ! Here are codes :
public class SyncActivity extends Activity {
...
private MessageDialogView dlg = null; // an AlertDialog showing a message
private Patienter dwait = null; // an AlertDialog containing an imageview showing an animation-list
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.synchro);
...
dlg = new MessageDialogView(SyncActivity.this, getLayoutInflater());
dwait = new Patienter(SyncActivity.this, getLayoutInflater());
...
}
public void synchroniser(View view) { // called when a button is clicked
dwait.show();
new RequestTask().execute("http://192.168.1.8/impots/data/syncro/webVersAndroid/parcelles.txt");
}
private class RequestTask extends AsyncTask<String, Void, Void> {
private String err = "";
private boolean error = false;
private String[] enregs;
#Override
protected Void doInBackground(String... s_url) {
enregs = new String[s_url.length];
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo != null) {
if (networkInfo.isAvailable() && networkInfo.isConnected()) {
System.setProperty("http.keepAlive", "false");
HttpURLConnection con = null;
BufferedReader reader = null;
for (int u=0; u<s_url.length; u++) {
String tmp;
String lines = "";
try {
URL url = new URL(s_url[u]);
if (url != null) {
con = (HttpURLConnection) url.openConnection();
if (con != null && con.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = con.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
boolean firstLine = true;
while ((tmp = reader.readLine()) != null) {
if (firstLine) {
firstLine = false;
lines += tmp;
}
else
lines += "\r\n" + tmp;
}
enregs[u] = lines;
}
}
} catch (MalformedURLException e) {
error = true;
err = getResources().getString(R.string.errBadUrl);
} catch (IOException e) {
error = true;
err = getResources().getString(R.string.errAccessError);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
if (con != null)
con.disconnect();
}
}
}
else {
error = true;
err = getResources().getString(R.string.errNotConnected);
}
} else {
error = true;
err = getResources().getString(R.string.errNoNetwork);
}
if (!error)
populateDB();
return null;
}
#Override
protected void onPostExecute(Void result) {
dwait.dismiss();
if (error) {
displayError(err);
}
}
private void displayError(String msg) {
dlg.setTitre(getString(R.string.titreErrMsgBox));
dlg.setMsg(msg);
dlg.show();
}
...
}
}
}
Code of the dialog :
public class Patienter extends AlertDialog {
private View contenu;
AnimationDrawable frameAnimation = null;
public Patienter(Context context, LayoutInflater inflater) {
super(context);
contenu = inflater.inflate(R.layout.patienter, null);
setCancelable(false);
setCanceledOnTouchOutside(false);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(contenu);
ImageView img = (ImageView)contenu.findViewById(R.id.imgWait);
img.setBackgroundResource(R.drawable.wait);
frameAnimation = (AnimationDrawable) img.getBackground();
frameAnimation.start();
}
}
So how to work with the context ?
Set your Context in Constructor of AsyncTask & pass the context from where AsyncTask called.
Show your Dialogue in onPreExecute() of AsyncTask
Cancel your Dialogue on onPostExecute().
private class RunInBackground extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
private Context contextInsideDialogue;
public RunInBackground(Context activity) {
try {
this.contextInsideDialogue = activity;
dialog = new ProgressDialog(activity,
android.R.style.Theme_DeviceDefault_Light_Panel);
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.getWindow().setGravity(Gravity.BOTTOM);
} catch (Exception e) {
}
}
#Override
protected void onPreExecute() {
try {
dialog.setMessage("Please wait. . ");
dialog.show();
} catch (Exception e) {
}
}
#Override
protected void onPostExecute(Void result) {
try {
if (dialog.isShowing()) {
dialog.dismiss();
}
} catch (Exception e) {
}
}
}
& Invoke it as
RunInBackground task = new RunInBackground (MyActivity.this);
task.execute();

Retriving data from the internet blocks main thread

I want to write an Android app which will retrieve the data from internet and save in a local file. This is what I have written:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Runnable r = new Runnable() {
#Override
public void run() {
updateData();
}
};
Handler h = new Handler();
h.post(r);
}
private Boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if(ni != null && ni.isConnectedOrConnecting()) {
return true;
}
else {
return false;
}
}
private void updateData() {
if(!isOnline()) {
Toast.makeText(this, "Unable to update data: Internet Connection Unavailable", Toast.LENGTH_SHORT).show();
}
else {
try {
HttpClient client = new DefaultHttpClient();
HttpGet req = new HttpGet("***SOME URL****");
HttpResponse res = client.execute(req);
InputStream is = res.getEntity().getContent();
InputStreamReader ir = new InputStreamReader(is);
StringBuilder sb = new StringBuilder();
Boolean end = false;
do {
int t = ir.read();
if(t==-1) {
end = true;
}
else {
sb.append((char)t);
}
}
while(!end);
String s = sb.toString();
File f = new File(getFilesDir(), "data.txt");
FileWriter fw = new FileWriter(f);
fw.write(s);
fw.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
I get the main thread blocked for about 2-3 seconds. And I'm not sure if this is the correct way to do this. So if you think this is an incorrect way to do, feel free to tell me.
Regards,
Sarun
From handler Constructor API:
associates this handler with the Looper for the current thread.
This means that the Handler you created is associated with the Looper of the UI thread, which means that the runnable is being executed on the UI thread (therefore you see the pause of the UI).
I suggest that you will use Android's AsyncTask or instantiate the Handler on a background thread.
Use AsyncTask, to get rid of this.
The code of AsyncTask is below:
class AsyncLogin extends AsyncTask<Void, Void, String> {
ProgressDialog dialog = new ProgressDialog(MyTopic.this);
protected String doInBackground(Void... params) {
return msg;
}
protected void onPostExecute(String result) {
try {
dialog.cancel();
}
} catch (Exception e) {
dialog.cancel();
}
}
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Fetching...Topic List!!!");
dialog.setCancelable(true);
dialog.show();
}
}
calling code:
AsyncLogin as = new AsyncLogin();
as.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