简体   繁体   中英

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.

Ps I am using Blogger API

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM