Tuesday, December 17, 2013

Code Snippet - SD Cards & Network check

In many occassions, we may find a need to check for online condition and download files to our sd card.

PFB the code to check for network availability,

public boolean isNetworkAvailable() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;

}

PFB the code for SD Card mount check,

private boolean isSDCardMounted() {
String sdCardStatus = android.os.Environment.getExternalStorageState();
return sdCardStatus.equals(android.os.Environment.MEDIA_MOUNTED);
}

PFB the code that returns available space in SD Card,

public int getFreeExtMemory()
{
    StatFs statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
    int free  =  ((statFs.getAvailableBlocks() * statFs.getBlockSize()) / 1024);
    Log.i("AppInstallChecker", "Available Space : " + free + " KB, Required Space : "+APPSIZE_KB+" KB");
    return free;
}

Note : The methods getAvailableBlocks() & getBlockSize() from the above method/snippet is deprecated after api 18, so put a check if needed.

References :

No comments:

Post a Comment