Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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;
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top