【问题标题】:How to auto refresh webview after connecting to internet连接到互联网后如何自动刷新网页视图
【发布时间】:2017-08-16 10:01:13
【问题描述】:

在我的应用程序中,我实现了一个 webview 来显示包含一些有用信息的网页。现在,最初我检查了 Netwotk 是否可用。如果可用,它将连接到网页。如果没有,它将显示一个警报对话框,告诉您设备上没有互联网连接。之后它将重定向到设备的设置选项。我可以从此选项切换到 wifi。但问题是打开wifi后,当我回到工作页面时,它没有自动更新。我必须转到我的选项菜单页面,然后单击按钮,然后它会被更新。如何在打开互联网后像谷歌浏览器一样更新页面。这是我的代码

我的编辑代码

    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();
    }

}

我的 NetworkReceiver 类

    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();
        }
    }
}

【问题讨论】:

    标签: android webview android-webview auto-update android-internet


    【解决方案1】:

    您需要添加一个广播接收器来处理CONNECTIVITY_CHANGE。这将允许您的应用在网络状态发生变化时收到通知,例如没有连接互联网。

    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());
         }
    }
    

    在您的清单中,您还需要添加该接收器。

    <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>
    

    现在,为了实际发送数据,我将使用 Otto,即事件总线库。

    创建一个类来包含我们将放在事件总线上的信息。

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

    最后在您的 JobPage 活动中,注册(并在 onDestroy 上取消注册)总线,然后您可以Subscribe 参加活动。

    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.
             }
        }
    }
    

    【讨论】:

    • 好的,但是我应该为此创建这个新类。或者我如何在我给定的代码中实现这个
    • 是的,您将创建一个扩展 BroadcastReceiver 的新类,并将其放入您的清单中,它将处理 CONNECTIVITY_CHANGEWIFI_STATE_CHANGED。这将告诉 Android 该类将处理该操作。然后您需要创建一个方法将该信息传递给您的JobPage Activity。我建议研究 EventBus 或 Otto。两者都非常易于实施和使用。
    • @ktina 我已经更新了我的答案,并提供了更多关于如何实施这个系统的信息。有很多需要改进的地方,比如在你的 Application 类中有 Bus 静态和 Application 类,但这应该让你对如何开始有足够的了解。
    • 你的巴士班在哪里?
    • Bus 类来自库 Otto。我链接到它,你应该阅读如何整合它。
    【解决方案2】:

    通过使用线程处理程序,您可以每 5 秒运行一次 web 视图,请检查以下代码。

      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);
        }
    }
    

    【讨论】:

    • 这段代码在哪里可以写,这段代码怎么调用,mWebvie是什么意思?对不起,我是 android 开发的新手。多解释一下就好了
    • 你正在使用 webView 我正在使用 mWebView .. 只需创建此方法并将此方法调用到您的 onCreate 中
    • 不,它不工作。我在 if(isNetworkStatusAvialable (getApplicationContext())) { 中使用了这个方法,但连接到互联网后我无法得到任何响应
    • 希望上面的代码对你有用。如果不告诉我错误
    • 我写的代码和你的一样。但是打开互联网后我没有更新 jsut 的页面。我必须去选项页面,点击然后更新
    【解决方案3】:

    以下代码将在每 1 秒后调用一次方法,因此您的 web 视图将在每 1 秒后自动刷新

     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);
        }
    

    【讨论】:

    • 这不是一遍又一遍地刷新WebView吗?
    猜你喜欢
    • 1970-01-01
    • 2015-02-06
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多