1

Im my app I am writing one service which runs in the background and after every hour it updates the local db in devices as soon as new updates are received and i am sending the status bar notification to the user.

In my services i am making a rest api call but i need to check that if internet connection is down the service for making api calls should not run. I know how to make it in activity but don't know how to do it in the services.

SchedulingService.java

public class SchedulingService extends IntentService {
 DbHandler DbHandler;
 List<Shipment> _shipmentList = new ArrayList<>();

@Override
    protected void onHandleIntent(Intent intent) {
        checkNotificationStatus();
        // Waking up the Alarm Manager after some time
        TrackerAlarmReceiver.completeWakefulIntent(intent);
    }

 public void checkNotificationStatus() {
        List<String> notificationList = new ArrayList<String>();
        HashMap<User, String> notificationMap = new HashMap<User, String>();
        UserTracker userTracker;

        UserService apiService;
        DbHandler = new DbHandler(this);
        _userList = DbHandler.getAllActiveUsers();
        // Here i am making the API call
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(ApiMessage.API_URL)
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .setConverter(new GsonConverter(new Gson()))
                .build();

        apiService = restAdapter.create(UserService.class);

     sendNotification(message);
}
anand
  • 1,711
  • 2
  • 24
  • 59

4 Answers4

2

To Check the availability of the internet in the Android application, use the following approach by calling the isInternetAvailable() method:

/*
 * Checks if WiFi or 3G is enabled or not. server
 */
public static boolean isInternetAvailable(Context context) {
    return isWiFiAvailable(context) || isMobileDateAvailable(context);
}

/**
 * Checks if the WiFi is enabled on user's device
 */
public static boolean isWiFiAvailable(Context context) {
    // ConnectivityManager is used to check available wifi network.
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo network_info = connectivityManager.getActiveNetworkInfo();
    // Wifi network is available.
    return network_info != null
            && network_info.getType() == ConnectivityManager.TYPE_WIFI;
}

 /**
 * Checks if the mobile data is enabled on user's device
 */
public static boolean isMobileDateAvailable(Context context) {
    // ConnectivityManager is used to check available 3G network.
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    // 3G network is available.
    return networkInfo != null
            && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
}

Manifest.xml

    <!-- For checking the network state -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Recommendation This approach checks for the connectivity of the Wifi and the Mobile data using the OS. BUT is it not reliable because sometimes the user will be connected to one of those without having a permission to access the internet like what happened in most of the Cafes and Hotel until you login using username and password`

That's why I recommend you to create a simple HTML file into you server and PING it with checking the return content. If the content matches each other then you are having a reliable internet connection.

Sami Eltamawy
  • 9,874
  • 8
  • 48
  • 66
1

Detect network connection type on Android

to check that if internet connection

 private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager 
              = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();}

You will also need:

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

You can use the ConnectivityManager to check that you're actually connected to the Internet, and if so, what type of connection is in place.

Monitor for Changes in Connectivity

TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    switch (tm.getNetworkType()) {
    case TelephonyManager.NETWORK_TYPE_HSDPA:
        Log.d("Type", "3g");
        // for 3g HSDPA networktype will be return as
        // per testing(real) in device with 3g enable
        // data
        // and speed will also matters to decide 3g network type
        break;
    case TelephonyManager.NETWORK_TYPE_HSPAP:
        Log.d("Type", "4g");
        // No specification for the 4g but from wiki
        // i found(HSPAP used in 4g)
        // http://goo.gl/bhtVT
        break;
    case TelephonyManager.NETWORK_TYPE_GPRS:
        Log.d("Type", "GPRS");
        break;
    case TelephonyManager.NETWORK_TYPE_EDGE:
        Log.d("Type", "EDGE 2g");
        break;
    // case TelephonyManager.NETWORK_TYPE_CDMA:
    // break;
    // case TelephonyManager.NETWORK_TYPE_EVDO_A:
    // break;
    // case TelephonyManager.NETWORK_TYPE_EVDO_B:
    // break;
    // case TelephonyManager.NETWORK_TYPE_EVDO_0:
    // break;
    }
Community
  • 1
  • 1
MMM
  • 3,132
  • 3
  • 20
  • 32
0

You can check the internet connection using the following method:

/**
 * This method checks if the device has an active internet 
 * connection or not.
 * 
 * @param context
 *          - context of the class from where it is called
 * @return
 *      Returns true if there is internet connectivity
 */
public static Boolean checkInternet(Context context){
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()){
        return true;
    }
    else if (netInfo != null && (netInfo.getState() == NetworkInfo.State.DISCONNECTED || netInfo.getState() == NetworkInfo.State.DISCONNECTING || netInfo.getState() == NetworkInfo.State.SUSPENDED || netInfo.getState() == NetworkInfo.State.UNKNOWN)){
        return false;
    }
    else{
        return false;
    }
}

And for starting your process/services as soon as you get an active internet connection use a Braodcast receiver:

public class ConnectionReciever extends BroadcastReceiver{

Context context;
public String TAG = "ConnectionReciever";

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

    this.context = context;
    //read internet connectivity state
    if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {   
        NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra
                (ConnectivityManager.EXTRA_NETWORK_INFO);

        //connected to Internet
        if (currentNetworkInfo != null && currentNetworkInfo.isConnectedOrConnecting()) {
             // start sync process
        } 
        else if (currentNetworkInfo != null && (currentNetworkInfo.getState() ==
                NetworkInfo.State.DISCONNECTED || currentNetworkInfo.getState() == NetworkInfo.State.DISCONNECTING 
                || currentNetworkInfo.getState() == NetworkInfo.State.SUSPENDED || 
                currentNetworkInfo.getState() == NetworkInfo.State.UNKNOWN)) {

            // when Internet is disconnected
        }

    }
}

}

kamal2305
  • 671
  • 4
  • 11
0

Its been very easy by using this Library. For detail check here.

Demo Code:

public class MultiPostUploader extends Service implements InternetConnectivityListener {

        private Context mContext;
        private InternetAvailabilityChecker mInternetAvailabilityChecker;
        private boolean isConnected = true;

        public MultiPostUploader() {
        }

        @Override
        public void onCreate() {
            super.onCreate();
            mContext = this;
            InternetAvailabilityChecker.init(this);
            mInternetAvailabilityChecker = InternetAvailabilityChecker.getInstance();
            mInternetAvailabilityChecker.addInternetConnectivityListener(this);
        }

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            return super.onStartCommand(intent, flags, startId);
        }


        @Override
        public void onInternetConnectivityChanged(boolean isConnected) {
            // If true you have perform your action;
            this.isConnected = isConnected;
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            mInternetAvailabilityChecker
                    .removeInternetConnectivityChangeListener(this);
        }
    }
Sohail Zahid
  • 8,099
  • 2
  • 25
  • 41