简体   繁体   中英

Automatically refresh Activity when Internet is there

I have an ActivityNonetwork.java Activity. The purpose of that file is that when there is no network/internet, the ActivityNonetwork activity is shown.

I tried it, I turned off the internet and this page was shown (Successful!!!), but when I again turn on the internet, the page does not refresh and the same page is being shown even after I turn the internet on.

My ActivityNonetwork.java code:

package com.Notely.SplashScreenandAccounts;

import androidx.activity.OnBackPressedCallback;
import androidx.activity.OnBackPressedDispatcherOwner;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.Notely.Notes.ActivityDashboard;

public class ActivityNonetwork extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_nonetwork);

    final Button exit = findViewById(R.id.exit);
    final Button retry = findViewById(R.id.retry);

    exit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            exitApp();
        }
    });
    retry.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            retryApp();
        }
    });

    if (checkNetwork() == true) {
        finish();
        overridePendingTransition(0, 0);
        startActivity(getIntent());
        overridePendingTransition(0, 0);

        Intent activitySplash = new Intent(this, ActivitySplash.class);
        startActivity(activitySplash);
    }
}

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

public void exitApp() {
    Intent exitApp = new Intent(Intent.ACTION_MAIN);
    exitApp.addCategory( Intent.CATEGORY_HOME );
    exitApp.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(exitApp);
}

public void retryApp() {
    Intent retryApp = new Intent(this, ActivitySplash.class);
    startActivity(retryApp);
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    Intent exitApp = new Intent(Intent.ACTION_MAIN);
    exitApp.addCategory( Intent.CATEGORY_HOME );
    exitApp.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(exitApp);
}
}

Is there any way in which we can refresh the page when the internet comes?

you just check network connection when activity created, you have to initialize observer for network changes

read this article and manage your network connection

You can achieve this using broadcast receiver in your project

Create a class as below -

public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {
   PrefManager.getInstance(context).setPreviousNetworkStatus
   (NetworkUtil.getConnectivityStatusString(context));
 }
}

Then create below class -

class NetworkUtil {

private static int TYPE_WIFI = 1;
private static int TYPE_MOBILE = 2;
private static int TYPE_NOT_CONNECTED = 0;


private static int getConnectivityStatus(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (null != activeNetwork) {
        if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
            return TYPE_WIFI;

        if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
            return TYPE_MOBILE;
    }
    return TYPE_NOT_CONNECTED;
}

static String getConnectivityStatusString(Context context) {
    int conn = NetworkUtil.getConnectivityStatus(context);
    String status = null;
    if (conn == NetworkUtil.TYPE_WIFI) {
        status = context.getString(R.string.wifi_enabled);
    } else if (conn == NetworkUtil.TYPE_MOBILE) {
        status = context.getString(R.string.mobile_data_enable);
    } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
        status = context.getString(R.string.not_connected_to_internet);
    }
    return status;
 }
}

Create a PrefsManager class - This is not mandatory to create a separate class for this funcionality. You can add this code to your MainActivity.

public class PrefManager {

public static final String PREVIOUS_NETWORK_STATE = "previous_network_state";

private static SharedPreferences sharedPreferences;
private static PrefManager prefManager;

private PrefManager(Context context) {
    sharedPreferences = context.getSharedPreferences(PREFERENCE_NAME, 
    Context.MODE_PRIVATE);
}

public static PrefManager getInstance(Context context) {
    if (prefManager == null) {
        prefManager = new PrefManager(context);
    }
    return prefManager;
}

public SharedPreferences getSharedPreferences() {
    return sharedPreferences;
}

public void setPreviousNetworkStatus(String status) {
    sharedPreferences.edit().putString(PREVIOUS_NETWORK_STATE, status).apply();
}

public String getPreviousNetworkStatus() {
    return sharedPreferences.getString(PREVIOUS_NETWORK_STATE, "");
}
}

In MainActivity

 private NetworkChangeReceiver networkChangeReceiver = NetworkChangeReceiver()

In onCreate method register receiver

 registerReceiver(
        networkChangeReceiver,
        IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")
    )

Override below method

@Override void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String 
key) {
    if (key == PrefManager.PREVIOUS_NETWORK_STATE) {
        onNetworkChanged()
    }
 }

Then create this method -

private void onNetworkChanged() {
    // your code here 

    finish();
    overridePendingTransition(0, 0);
    startActivity(getIntent());
    overridePendingTransition(0, 0);

    Intent activitySplash = new Intent(this, ActivitySplash.class);
    startActivity(activitySplash);
}

unregister receiver in onDestroy method

 unregisterReceiver(networkChangeReceiver)

I hope this will work for you.

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