1

how do i make this code run in background forever and always detect if there is internet access or not (not internet connection) and show a toast when there is no internet access?

here is what i want (See meow meo's answer), but it is for detecting internet

// check connectivity (Internet access)
    private boolean checkConnectivity() {
        System.out.println("executeCommand");
        Runtime runtime = Runtime.getRuntime();
        try {
            Process mIpAddrProcess = runtime
                    .exec("/system/bin/ping -c 1 8.8.8.8");
            int mExitValue = mIpAddrProcess.waitFor();
            System.out.println(" mExitValue " + mExitValue);
            if (mExitValue == 0) {
                img_c1.setImageResource(R.drawable.index2);
                return true;
            } else {
                img_c2.setImageResource(R.drawable.index2);
                return false;
            }
        } catch (InterruptedException ignore) {
            ignore.printStackTrace();
            System.out.println(" Exception:" + ignore);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(" Exception:" + e);
        }
        return false;
    }
Community
  • 1
  • 1
MaggotSauceYumYum
  • 402
  • 1
  • 5
  • 23

1 Answers1

2

First of all, its bad idea to run this code forever in background.

Instead use BroadCastReceiver to check network status, so it will only active at the time of network status change,

You have to register your BroadcastReceiver for Network Status Change event. So whenver any changes happen on device for network android broadcast event and your BroadcastReceiver will listen that event and display Toast based on that.

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

http://www.grokkingandroid.com/android-getting-notified-of-connectivity-changes/

user370305
  • 108,599
  • 23
  • 164
  • 151
  • i would like to use a broadcast receiver but that link is rather about detecting internet connection, could you tell me how to use my code for detecting internet access (sending pings) in this broadcast receiver http://stackoverflow.com/questions/3767591/check-intent-internet-connection – MaggotSauceYumYum Nov 07 '15 at 16:18
  • any clues? @user370305 – MaggotSauceYumYum Nov 08 '15 at 02:13
  • Why you want to ping to external server? Just for check internet connection? – user370305 Nov 08 '15 at 02:48
  • i want to turn wifi off and on if there is internet connection but no internet access, which i can't do if there is no internet connection or access because the wifi will be already off in that case. i hope that makes some sense – MaggotSauceYumYum Nov 08 '15 at 02:55