Samadhan Medge
Samadhan Medge

Reputation: 2049

Reload an Activity on Internet occurence in android

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.

Upvotes: 1

Views: 3946

Answers (5)

Alobaidi
Alobaidi

Reputation: 29

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

Upvotes: 0

Samadhan Medge
Samadhan Medge

Reputation: 2049

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

Upvotes: 1

Shivang Trivedi
Shivang Trivedi

Reputation: 2182

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

Upvotes: 2

Biraj Zalavadia
Biraj Zalavadia

Reputation: 28484

you can all call function recursively like

public void loadDataFromServer(){

  if(isNetworkAvailabel()){
    //call web service
  }else{
    loadDataFromServer();
  }
}

Upvotes: 0

nedaRM
nedaRM

Reputation: 1827

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.

Upvotes: 0

Related Questions