Joy Dey
Joy Dey

Reputation: 593

How to use a custom No Internet Connection Available layout when user is offline?

I have been trying to use a custom Image that is to be shown to a user when he is offline and when the user clicks on the image, the activity should be reloaded.

P.s I am using Blogger API

Upvotes: 0

Views: 1692

Answers (2)

Himanshu
Himanshu

Reputation: 91

You can use Custom Dialog of full Screen to check for internet. So, you can write,

if(isNetworkAvailable()){
        //Your Logic for Internet Connection
 }else {
    val noInternetDialog = Dialog(this, android.R.style.Theme)
    noInternetDialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
    noInternetDialog.setContentView(R.layout.no_internet_layout)
    val window = noInternetDialog.window
    window.setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
    // What ever you have widget, can use them here.
    //for example
    val button_try_again = noInternetDialog.findViewById(R.id.buttonId)
    val image_to_display = noInternetDialog.findViewById(R.id.imageId)
    // listeners for image

    noInternetDialog.show
 }

isNetworkAvaibale() is,

fun isNetworkAvailable(): Boolean {

        val connectivityManager = ApplicationInit.getAppContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val activeNetworkInfo = connectivityManager.activeNetworkInfo
        return activeNetworkInfo != null && activeNetworkInfo.isConnected
    } 

PS : Do not forget to add Internet Permissions

Upvotes: 0

menasoft
menasoft

Reputation: 145

first add this permission to manifest

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

thin in your activty

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

and use like this

if(isNetworkAvailable()){
//internt connect
}else{
// no network 
//you can show image here by adding layout and set visibility gone and when no connection set visible
}

Upvotes: 1

Related Questions