0

Can you please help me on this?

How to create a activity which runs a url at oncreate method if Internet connection is available?

I want to check Internet connection is available or not every 5 seconds, if Internet connection gone it will alert as dilog box only one time.

If Internet connection comes then activty will resume where the session was closed

Here below my code is:

    public class MainActivity extends Activity {

private String URL="http://www.moneycontrol.com/";

private Handler mHandler = new Handler();

private boolean isRunning = true;

private TextView textlabel=null;    

public WebView webview=null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textlabel=(TextView)findViewById(R.id.textlabel);
        displayData();

    }

    private void Chekstate() {

    new Thread(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (isRunning) {
                try {
                    Thread.sleep(1000);
                    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(); 

    }


    @SuppressWarnings("deprecation")
    private void displayData() {
        ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo nf=cn.getActiveNetworkInfo();
        if(nf != null && nf.isConnected()==true )
        {
           textlabel.setText("Network Available");
           Webview();
        }
        else
        {
           textlabel.setText("Network Not Available");
           final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
           alertDialog.setTitle("Intenet Connecction");
           alertDialog.setMessage("Internet Connetion is not available now.");
           alertDialog.setButton(" OK ", new OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                alertDialog.dismiss();
            }
        });
           alertDialog.show();
        }       
    } 


      @Override
        protected void onResume() {
            super.onResume();

        }

        @Override
        protected void onPause() {
            super.onPause();

        }

    @SuppressLint("SetJavaScriptEnabled")
    private void Webview() {
        webview= (WebView) findViewById(R.id.webview);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setWebViewClient(new WebViewClient());
        webview.loadUrl(URL);
        webview.setInitialScale(1);
        webview.getSettings().setBuiltInZoomControls(true);
        webview.getSettings().setUseWideViewPort(true);

    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}
user5071535
  • 1,312
  • 8
  • 25
  • 42

1 Answers1

1

to check internet connectivity you can use the following.

Add the following permissions in manifest

 <uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

Use a handler

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

Alterntively you ca use the below. But it does not check connectivty every 5 seonds

public class CheckNetwork {
private static final String TAG = CheckNetwork.class.getSimpleName();
public static boolean isInternetAvailable(Context context)
{
NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

if (info == null)
{
     Log.d(TAG,"no internet connection");
     return false;
}
else
{
    if(info.isConnected())
    {
        Log.d(TAG," internet connection available...");
        return true;
    }
    else
    {
        Log.d(TAG," internet connection");
        return true;
    }
   }
 }
}

In your activity in onCreate()

if(CheckNetwork.isInternetAvailable(MainActivtiy.this))  //if connection available
{

}

http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html

You can use a BroadCast Reciever. When connectivity is lost the system broadcasts. But i suggest not to use broadcast reciever.

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • Thanks for the help I have already used this code.But I want to pause the activity when network gone and resume if network comes. –  Apr 03 '13 at 10:03
  • activity is paused when it in background. Suppose you display a dialog in the activity. Dialog is in foreground. Activity goes to background. Paused and resumed when you dismiss the dialog. Go through the link for better understanding http://developer.android.com/guide/components/tasks-and-back-stack.html – Raghunandan Apr 03 '13 at 10:10
  • you can override the methods. call back methods. What do you mean manually? – Raghunandan Apr 03 '13 at 10:32
  • I meant to say I run a url like google.com and search for "Raghunandan" then Internet connection gone now it will show the alert right after this when Internet connection comes it must be the privious page meance serch result of "Raghunandan". –  Apr 03 '13 at 10:36