1

In my project I use JSON parsing, in my first activity I show ListView which get data from webservice, The problem is that when their is no internet connection it shows blank its Okey but want that if I stay on that activity and Internet is coming then my Activity get reload, what to do for that.

Samadhan Medge
  • 2,049
  • 2
  • 16
  • 24
  • You can use timer to check the internet connection and once it is found, re-execute the JSON parsing method and destroy the timer. – Jibran Khan Sep 02 '13 at 05:55
  • 1
    @JibranKhan: yes, but any proper option using BroadCast Resceiver anything else, timer is not too efficient. – Samadhan Medge Sep 02 '13 at 05:58
  • Have a look at this http://stackoverflow.com/questions/10733121/broadcastreceiver-when-wifi-or-3g-network-state-changed – Jibran Khan Sep 02 '13 at 06:00
  • And here is one more http://stackoverflow.com/questions/10350449/how-to-check-the-internet-connection-periodically-in-whole-application/10350511#10350511 – Jibran Khan Sep 02 '13 at 06:01

5 Answers5

2

Use BroadcastReceiver.

     private BroadcastReceiver networkReceiver = new BroadcastReceiver {
     @Override
     public void onReceive(Context context, Intent intent) {
          super.onReceive(context, intent);
          if(intent.getExtras()!=null) {
              NetworkInfo ni=(NetworkInfo)intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
         if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
             // we're connected
         }
 }
 // we're not connected 
  }
  }

register this in your onResume(), and unregister on onPause().

    @Override
    protected void onPause() {
       super.onPause();
       unregisterReceiver(networkReceiver);
    }

  @Override
  protected void onResume() {
      super.onResume();
      IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
      registerReceiver(networkReceiver, filter);
  }

  public boolean isNetworkConnected() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
  }

Jibran Khan
  • 3,236
  • 4
  • 37
  • 50
Shivang Trivedi
  • 2,182
  • 1
  • 20
  • 26
1

The following solution works for me
//MainActivity.java

public class MainActivity extends Activity 
{
    private ConnectionDetector detector;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        detector = new ConnectionDetector(MainActivity.this);

        // check Internet
        if (detector.isInternetAvailable()) 
        {
            Log.d("===========================", "Internet Present");
        } 
        else 
        {
            Log.d("===========================", "No Internet");
            this.registerReceiver(this.mConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
        }
    }

    @Override
    protected void onResume() 
    {
        super.onResume();
        Log.d("===========================", "onResume");
        IntentFilter intentFilter = new IntentFilter("com.agile.internetdemo.MainActivity");
        MainActivity.this.registerReceiver(mConnReceiver, intentFilter);

    }

    @Override
    public void onPause() 
    {
        super.onPause();
        Log.d("===========================", "onPause");
        MainActivity.this.unregisterReceiver(mConnReceiver);
    }

    private BroadcastReceiver mConnReceiver = new BroadcastReceiver() 
    {
        public void onReceive(Context context, Intent intent) 
        {
            boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
            String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
            boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

            NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

            if (currentNetworkInfo.isConnected()) 
            {
                Log.d("===========================", "Connected");
                finish();
                startActivity(getIntent());
                Toast.makeText(getApplicationContext(), "Connected",Toast.LENGTH_LONG).show();
            } 
            else
            {
                Log.d("===========================", "Not Connected");
                Toast.makeText(getApplicationContext(), "Not Connected",
                        Toast.LENGTH_LONG).show();
            }
        }
    };
}

//connectionDector.java

public class ConnectionDetector 
{
    private Context _context;

    public ConnectionDetector(Context context) 
    {
        this._context = context;
    }

    public boolean isInternetAvailable() 
    {
        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;
    }
}
Samadhan Medge
  • 2,049
  • 2
  • 16
  • 24
0

You can check for network connection like this:

public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

Also add the following permission to the Android Manifest

If you want to run this until you get connectivity you can use a TimerTask.

nedaRM
  • 1,837
  • 1
  • 14
  • 28
0

you can all call function recursively like

public void loadDataFromServer(){

  if(isNetworkAvailabel()){
    //call web service
  }else{
    loadDataFromServer();
  }
}
Biraj Zalavadia
  • 28,348
  • 10
  • 61
  • 77
0
import android.content.Context;
import android.net.ConnectivityManager;

public class DetectConnection {

public static boolean checkInternetConnection(Context context) {

      ConnectivityManager con_manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

      if (con_manager.getActiveNetworkInfo() != null
        && con_manager.getActiveNetworkInfo().isAvailable()
        && con_manager.getActiveNetworkInfo().isConnected()) {



       return true;
      } else {
       return false;
      }
     }
    }

And then

if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    if (DetectConnection.checkInternetConnection(MainActivity.this)) {
       //do something here "your reload Activity"
        } else {
        Toast.makeText(MainActivity.this,"NO Internet Connection",Toast.LENGTH_LONG).show();
        ProgressBar progressBar.setVisibility(View.GONE);
        }
Alobaidi
  • 29
  • 1
  • 3