4

In my app I have implemented a webview to show an webpage conataing some useful information. Now Initially I checked whether Netwotk is available or not. If availbale it will connect to webpage. If not, it will show an alertdialog, telling that no internet connecttion on your device. After that it will redirect to setting option of device. I can swich on wifi from this option. But the problem is after turning on the wifi, when I go back to job page, it is not updated automatically. I have to go to my option menu page, then click on button and then it is updated. How can I update the page just after turning on the internet as like as google chrome. Here is my code for this

My Edited Code

    public class JobPage extends AppCompatActivity {

    private WebView webView;

    public static final String WIFI = "Wi-Fi";
    public static final String ANY = "Any";
    private static final String URL = "https://app.com";

    private static boolean wifiConnected = false;
    private static boolean mobileConnected = false;
    public static boolean refreshDisplay = true;

    public static String sPref = null;

    // The BroadcastReceiver that tracks network connectivity changes.
    private NetworkReceiver receiver = new NetworkReceiver();


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

        webView=(WebView)findViewById(R.id.webView);
       // Registers BroadcastReceiver to track network connection changes.
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        receiver = new NetworkReceiver();
        this.registerReceiver(receiver, filter);

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        // Unregisters BroadcastReceiver when app is destroyed.
        if (receiver != null) {
            this.unregisterReceiver(receiver);
        }
    }
    // Refreshes the display if the network connection and the
    // pref settings allow it.


    // Checks the network connection and sets the wifiConnected and mobileConnected
    // variables accordingly.
    @Override
    public void onStart () {
        super.onStart();

        // Gets the user's network preference settings
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

        // Retrieves a string value for the preferences. The second parameter
        // is the default value to use if a preference value is not found.
        sPref = sharedPrefs.getString("listPref", "Wi-Fi");

        updateConnectedFlags();

        if(refreshDisplay){
            loadPage();
        }
    }
    public void updateConnectedFlags() {
        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
        if (activeInfo != null && activeInfo.isConnected()) {
            wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
            mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
        } else {
            wifiConnected = false;
            mobileConnected = false;
        }
    }
    public void loadPage() {
        if (((sPref.equals(ANY)) && (wifiConnected || mobileConnected))
                || ((sPref.equals(WIFI)) && (wifiConnected))) {
            webView.loadUrl(URL);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.setWebViewClient(new WebViewClient());
            refreshDisplay=true;

        } else {
            errorDialog();
        }
    }

    public void errorDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder
                .setMessage("No internet connection on your device. Would you like to enable it?")
                .setTitle("No Internet Connection")
                .setCancelable(false)
                .setPositiveButton("Enable Internet",
                        new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog, int id)
                            {
                                Intent dialogIntent = new Intent(android.provider.Settings.ACTION_SETTINGS);
                                dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                getApplicationContext().startActivity(dialogIntent);
                            }
                        });
        builder.setNegativeButton(" Cancel ", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int id)
            {
                dialog.cancel();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

}

My NetworkReceiver Class

    public class NetworkReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager conn = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = conn.getActiveNetworkInfo();

        // Checks the user prefs and the network connection. Based on the result, decides whether
        // to refresh the display or keep the current display.
        // If the userpref is Wi-Fi only, checks to see if the device has a Wi-Fi connection.
        if (WIFI.equals(sPref) && networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            // If device has its Wi-Fi connection, sets refreshDisplay
            // to true. This causes the display to be refreshed when the user
            // returns to the app.

            Toast.makeText(context, "Wi-fi is connected", Toast.LENGTH_SHORT).show();
            JobPage.refreshDisplay = true;

            // If the setting is ANY network and there is a network connection
            // (which by process of elimination would be mobile), sets refreshDisplay to true.
        } else if (ANY.equals(sPref) && networkInfo != null) {
            JobPage.refreshDisplay = true;

            // Otherwise, the app can't download content--either because there is no network
            // connection (mobile or Wi-Fi), or because the pref setting is WIFI, and there
            // is no Wi-Fi connection.
            // Sets refreshDisplay to false.
        } else {
            JobPage.refreshDisplay = false;
            Toast.makeText(context, "Lost internet connection", Toast.LENGTH_SHORT).show();
        }
    }
}

3 Answers3

2

You need to add a BroadcastReceiver for handling CONNECTIVITY_CHANGE. This will allow your app to be notified when the network status has changed, such as no internet to connected.

public class NetworkChangeReceiver extends BroadcastReceiver {

   @Override
   public void onReceive(final Context context, final Intent intent) {
       boolean isOnline = isOnline( context );
       // Fire an event with the new status of the network.
       Bus bus = new Bus(ThreadEnforcer.MAIN);
       bus.post( new NetworkEvent( isOnline ) );
   }

    public boolean isOnline(Context context) {
         ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
         NetworkInfo netInfo = cm.getActiveNetworkInfo();
         //should check null because in airplane mode it will be null
         return (netInfo != null && netInfo.isConnected());
     }
}

And there in your manifest, you also need to add that receiver.

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.INTERNET" />
 <receiver
    android:name="NetworkChangeReceiver"
    android:label="NetworkChangeReceiver" >
    <intent-filter>
        <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
    </intent-filter>
</receiver>

Now, for actually sending the data, I'll use Otto, the event bus library.

Create a class to contain the information we'll be putting on the event bus.

public class NetworkEvent {

    private boolean isOnline;

    public NetworkEvent( boolean isOnline ) {
        this.isOnline = isOnline;
    }
}

And then finally in your JobPage activity, register ( and unregister on onDestroy ) the bus, and you can Subscribe to the event.

public class JobPage extends AppCompatActivity {
    @Override
    protected void onCreated( Bundle savedInstanceState ) {
        ...
        Bus bus = new Bus(ThreadEnforcer.MAIN);
        bus.register(this);
        ...
    }


    ...
    @Subscribe
    public void onNetworkChange( NetworkEvent event ) {
         if( event.isOnline ) {
            // Do refresh.
         }
    }
}
Advice-Dog
  • 4,481
  • 6
  • 29
  • 53
  • OK but shall I create this new class for this. Or how can I implement in my given code with this –  Aug 16 '17 at 10:41
  • Yes, you would create a new class that extends `BroadcastReceiver` and put in your manifest that it will handle the `CONNECTIVITY_CHANGE` & `WIFI_STATE_CHANGED`. This will tell Android that that class will handle that action. Then you need to create a method to pass that information down to your `JobPage` Activity. I suggest looking into EventBus, or Otto. Both very easy to implement and use. – Advice-Dog Aug 16 '17 at 10:43
  • @ktina I've updated my answer and given a lot more information on how you would implement this system. There is a lot to improve on, such as having the `Bus` static and in your `Application` class but that should give you enough of an idea on how to start. – Advice-Dog Aug 16 '17 at 11:27
  • where is your Bus class? –  Aug 16 '17 at 11:30
  • The `Bus` class is from the library `Otto`. I linked to it, and you should read on how to integrate that. – Advice-Dog Aug 16 '17 at 11:33
  • dog, so fater that I do not need isNetworkConnectionAvailable method to check the internet connection? –  Aug 16 '17 at 11:37
  • I have changed my code by seeing the documentation of https://developer.android.com/training/basics/network-ops/managing.html#detect-changes.With this code the netwrk state change is showing. But the page is still not updated after connection to internet. –  Aug 16 '17 at 13:17
  • I see, it seems like it's very similar code. If you're getting updates on the network status, but still not updating the page, I don't know what the issue is. That seems like it should work. – Advice-Dog Aug 16 '17 at 21:45
0

By Using Thread Handler you can run the web view after every 5 second please check below code .

  public class JobPage extends AppCompatActivity {

    private WebView webView;

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

        if(isNetworkStatusAvialable (getApplicationContext())) {
            Toast.makeText(getApplicationContext(), "internet available", Toast.LENGTH_SHORT).show();
            webView=(WebView)findViewById(R.id.webView);
            webView.loadUrl("https:...webaddress");
            webView.getSettings().setJavaScriptEnabled(true);
            webView.setWebViewClient(new WebViewClient());

            CallWebView();
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder
                    .setMessage("No internet connection on your device. Would you like to enable it?")
                    .setTitle("No Internet Connection")
                    .setCancelable(false)
                    .setPositiveButton("Enable Internet",
                            new DialogInterface.OnClickListener()
                            {
                                public void onClick(DialogInterface dialog, int id)
                                {
                                    Intent dialogIntent = new Intent(android.provider.Settings.ACTION_SETTINGS);
                                    dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    getApplicationContext().startActivity(dialogIntent);
                                }
                            });
            builder.setNegativeButton(" Cancel ", new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface dialog, int id)
                {
                    dialog.cancel();
                }
            });

            AlertDialog alert = builder.create();
            alert.show();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

    }

    public static boolean isNetworkStatusAvialable (Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null)
        {
            NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
            if(netInfos != null)
                if(netInfos.isConnected())
                    return true;
        }
        return false;
    }

    public void CallWebView() {
        final Handler ha=new Handler();
        ha.postDelayed(new Runnable() {

            @Override
            public void run() {
                //call function
                webView.loadUrl("http://www.google.com");
                ha.postDelayed(this, 1000);
            }
        }, 1000);
    }
}
Yogesh Borhade
  • 625
  • 10
  • 22
  • Where can I write this code, how can I call this code, what do you mean by mWebvie? Sorr yI am ver ynew in android developing. It would be nice if you explain more –  Aug 16 '17 at 10:09
  • you are using webView i am using mWebView .. just create this method and call this methode into your onCreate – Yogesh Borhade Aug 16 '17 at 10:13
  • no it is not working. I wite this method inside if(isNetworkStatusAvialable (getApplicationContext())) { but I cannot get any response after connecting to internet –  Aug 16 '17 at 10:16
  • hope above code works for you.if not tell me the error – Yogesh Borhade Aug 16 '17 at 10:31
  • I wrote same code as yours. but the page i snot updated jsut after turning on internet. I have to go the option page , click and then it is updated –  Aug 16 '17 at 10:39
  • use BroadcastReceiver to check when internet connection is change from wifi to other . and then do the needful changes – Yogesh Borhade Aug 16 '17 at 10:57
  • check when connection is change then broadcast will notify you and when it will notify you at that time reload the web view.. check link for the same https://stackoverflow.com/questions/25678216/android-internet-connectivity-change-listener – Yogesh Borhade Aug 16 '17 at 11:03
  • I have updated my code. in this way I am notifying about network state change. But the page is still not updated after connecting to wifi –  Aug 16 '17 at 13:18
-1

Below code Will Call the methode after every 1 second so your webview will refresh after avery 1 second automatically

 public void CallWebView() {
        final Handler ha=new Handler();
        ha.postDelayed(new Runnable() {

            @Override
            public void run() {
                //call function
                 webView.loadUrl("http://www.google.com");
                ha.postDelayed(this, 1000);
            }
        }, 1000);
    }
Yogesh Borhade
  • 625
  • 10
  • 22