1

I have been doing some research and seen some debate of whether to use Broadcast Receiver or Alarm Manager, Im not sure what to use but here is what I am trying to do and have done.

I have a method that will check if there is internet connection. And then updates the UI accordingly.

public void isNetworkAvailable() {
    ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();

    if (networkInfo != null && networkInfo.isConnected()) {
        mLayout.removeView(noInternetView);
        checkInternetViewOpen = false;
    } else {
        if (!checkInternetViewOpen) {
            checkInternetViewOpen = true;
            mLayout.addView(noInternetView, params);
        }
    }
}

And while I am in an activity that will be using the internet I want to run this once every few seconds to make sure the internet is still active. Like this

while (usingInternet) {
    //I need to make it wait
    isNetworkAvailable();

}

I also need to be not on the main thread for this, so I can make it wait, and then I will adjust the updating the UI parts on the main tread.

So how can I make this on a background thread? And what option should I use?

Thanks for the help in advance.

james brown
  • 250
  • 1
  • 4
  • 11

3 Answers3

1

As I understand you want to check Internet connection and if connected then you have to perform certain operations either in backgroung or on UI thread.

So I suggest you to write Broadcast reciever for connection changes and a Service class if connected start the Service.

In that service write A TimerTask that will run after some specific period. In TimerTask you write data on shared pref and when user opens Application you can update UI from shared data

Gaurav
  • 3,615
  • 2
  • 27
  • 50
  • You can follow this page for TimerTask http://examples.javacodegeeks.com/android/core/activity/android-timertask-example/ and this answer for Broadcast receiver http://stackoverflow.com/questions/15698790/broadcast-receiver-for-checking-internet-connection-in-android-app – Gaurav Jul 08 '15 at 05:09
  • 1
    Ive seen that BroadCast Receiver example but how do I call it? And is broadcast recieve on a background thread? – james brown Jul 08 '15 at 05:13
  • Broadcast recever get called automatically on Internet connection state change no need to call explicitly – Gaurav Jul 08 '15 at 05:14
  • So I just need to make the class and never call it? And is it on the background thread or UI thread? – james brown Jul 08 '15 at 05:18
  • Ya just call to TimerTask from broadCast receiver's onReceive() method – Gaurav Jul 08 '15 at 05:21
1

You can create a background thread to check for this task. Here are my sample code.

The only things left for you to do is to fulfill setNetworkAvaiableUI(), setNetworkNotAvaiableUI(), and set NETWORK_CHECK_INTERVAL.

private boolean isCheckNetworkThreadActive = false; // Flag to indicate if thread is active
private boolean isNetworkAvaiableUIActive = false; // Flag to indicate which view is showing
final private static int NETWORK_CHECK_INTERVAL = 5000; // Sleep interval between checking network

@Override
protected void onResume() {
    // Start network checking when activity resumes
    startCheckNetwork();
    super.onResume();
}

@Override
protected void onPause() {
    // Stop network checking when activity pauses
    stopCheckNetwork()
    super.onPause();
}

private void setNetworkAvaiableUI() {
    // If network avaible UI is not showing, we will change UI
    if (!isNetworkAvaiableUIActive) {
        isNetworkAvaiableUIActive = true;
        runOnUiThread(new Runnable() {
            public void run() {
                // Update UI here when network is available.
            }
        });
    }
}
private void setNetworkNotAvaiableUI() {
    // If network avaible UI is showing, we will change UI
    if (isNetworkAvaiableUIActive) {
        isNetworkAvaiableUIActive = false;
        runOnUiThread(new Runnable() {
            public void run() {
                // Update UI here when network is unavailable.
            }
        });
    }
}

private void startCheckNetwork() {
    // Only one network checking thread can be run at the time.
    if (!isCheckNetworkThreadActive) {
        isCheckNetworkThreadActive = true;

        Thread checkNetworkThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (isCheckNetworkThreadActive) {
                    if (isNetworkAvailable()) {
                        // Set UI if notwork is available
                        setNetworkAvaiableUI();
                    } else {
                        // Set UI if notwork is not available
                        setNetworkNotAvaiableUI();
                    }

                    // Sleep after finish checking network
                    try {
                        Thread.sleep(NETWORK_CHECK_INTERVAL);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        checkNetworkThread.setName("Check Network Thread");
        checkNetworkThread.start();
    }
}

private void stopCheckNetwork() {
    // This will break while loop of network checking thread.
    isCheckNetworkThreadActive = false;
}

You can also make the code a lot shorter by using Timer and Handler, that are the options.

spicydog
  • 1,644
  • 1
  • 17
  • 32
  • I need to add `checkNetworkThread.interrupt();` when exiting correct as otherwise the while loop stops but the thread is not gone? – james brown Jul 08 '15 at 06:24
  • I cant find a good way to stop the thread when exiting as `Thread.stop` has been deprecated – james brown Jul 08 '15 at 06:34
  • You don't need to interrupt the thread because when stopCheckNetwork() run isCheckNetworkThreadActive becomes false and the while loop will stop and the thread will stop since there is nothing to run after while loop. Next time you want to check again, you will just set isCheckNetworkThreadActive to true and start the thread again. FYI, stopCheckNetwork() will be call when the activity pauses, you can move it to anywhere. – spicydog Jul 08 '15 at 06:40
  • If I exit the app and then re-enter, `onResume` is called --> `startCheckNetwork();` which then tries to start the thread again as `isCheckNetworkThreadActive = false` from the exit. However if I set `isCheckNetworkThreadActive = true` before I call `startCheckNetwork()` then the while loop doesnt start again? – james brown Jul 08 '15 at 06:58
  • You should **not** set isCheckNetworkThreadActive manually but use startCheckNetwork() and stopCheckNetwork() instead it will set it and start the thread for you. If it were in a class, isCheckNetworkThreadActive is private and cannot be accessed by users. – spicydog Jul 08 '15 at 07:21
  • I am not setting it manually, when I exit `stopCheckNetwork` sets `isCheckNetworkThreadActive = false` correct? and then when I come back in the app, `startCheckNetwork` is called and then the code breaks on `checkNetworkThread.start();` do you follow me?, becuase you cannot restart a thread – james brown Jul 08 '15 at 07:26
  • 1
    I see, in that case move entire Thread thing to the startCheckNetwork and paste it after isCheckNetworkThreadActive = true;. This will make thread to be create every time. Sorry for that since I have this similar snippet but I haven't tried create thread outside the method. I have edited the answer. – spicydog Jul 08 '15 at 07:38
0

Case 1: Check internet status throughout the app

Extend the Application class and add a broadcast receiver in it.

public class MyApplication extends Application {

public static boolean isConnected = false;
/**
 * To receive change in network state
 */
private BroadcastReceiver NetworkStatusReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {

        ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        isConnected = networkInfo != null && networkInfo.isConnectedOrConnecting();

        if (!isConnected) {
            Toast noInternetToast = Toast.makeText(getApplicationContext(),
                    R.string.no_internet_msg, Toast.LENGTH_LONG);
            noInternetToast.show();
        }
    }
};

@Override
public void onCreate() {
    super.onCreate();
    /** Register for CONNECTIVITY_ACTION broadcasts */
    registerReceiver(NetworkStatusReceiver, new IntentFilter(
            ConnectivityManager.CONNECTIVITY_ACTION));
}

@Override
public void onTerminate() {
    super.onTerminate();
    unregisterReceiver(NetworkStatusReceiver);
}
}

In app's AndroidManifest.xml

<application
    android:name=".MyApplication"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
</application>

At any place in your app, you may check internet like

if(MyApplication.isConnected){
   /** Do your network operation **/
}

Case 2: Within an activity or fragment

Just add the broadcast receiver in each activity or fragment that needs internet status.

Sathish
  • 346
  • 5
  • 9