我在这里搜索了关于webview的“没有互联网消息”,我尝试了一些代码,但没有成功。我有一个片段WebView,我想检查设备是否有互联网或没有。如果是,则加载webview。如果不是,将加载另一个片段,并且这个新片段将使用无互联网消息对布局进行膨胀,并且此布局将具有刷新按钮(或下拉以刷新)。那么,我该如何实现网络检查和刷新?
主要活动
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(null == savedInstanceState) {
// set you initial fragment object
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content, InicioPagina.newInstance());
transaction.commit();
}
WebView Fragment
public class InicioPagina extends Fragment {
private ProgressBar prg;
SwipeRefreshLayout mySwipeRefreshLayout;
public WebView myWebView;
public static InicioPagina newInstance() {
InicioPagina fragment = new InicioPagina();
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.iniciopagina, container, false);
prg = (ProgressBar)rootView.findViewById(R.id.progressBar2);
mySwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipelayout);
myWebView = (WebView) rootView.findViewById(R.id.inicio_pagina);
myWebView.loadUrl("http://example.com.br/");
//*Ativar JavaScript
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//*Forçar links para abrir no WebView ao invés do navegador
myWebView.setWebViewClient(new WebViewClient());
myWebView.setVerticalScrollBarEnabled(false);
mySwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
myWebView.reload();
mySwipeRefreshLayout.setRefreshing(false);
}
});
myWebView.setOnKeyListener(new View.OnKeyListener()
{
@Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if(event.getAction() == KeyEvent.ACTION_DOWN)
{
WebView webView = (WebView) v;
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack())
{
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
return rootView;
}
public class WebViewClient extends android.webkit.WebViewClient{
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
prg.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
prg.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
}
content main xml
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/app_bar_main"
tools:context="br.com.example.example.MainActivity">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<FrameLayout
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
</RelativeLayout>
nointernet layout
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sem acesso a internet"
android:textAlignment="center"
android:textSize="30sp" />
答案 0 :(得分:1)
您可以通过访问网络状态来检查互联网可用性:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
你可以依靠这种方法检查互联网:
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
前:
if (!haveNetworkConnection()) {
//inflate your fragment, THERE IS NO INTERNET!!
}else {
//you can reload or what ever you want now.
}
答案 1 :(得分:1)
在我的情况下,我使用AlertDialogBox显示Internet错误,然后再次尝试按钮检查Internet连接
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
//Clearing the WebView
try {
webView.stopLoading();
} catch (Exception e) {
}
try {
webView.clearView();
} catch (Exception e) {
}
if (webView.canGoBack()) {
webView.goBack();
}
webView.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your internet connection and try again.");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
alertDialog.setCancelable(false);
alertDialog.show();
super.onReceivedError(webView, errorCode, description, failingUrl);
}