2017-06-14 249 views
0

IM使用一個片段內的WebView,我想補充的互聯網連接錯誤信息,並加載pregress吧,可有人請幫助 這裏是我的互聯網連接錯誤

import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.webkit.WebView; 
import android.webkit.WebViewClient; 

public class FoodFragment extends Fragment { 


@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    // Inflate the layout for this fragment 
    View view = inflater.inflate(R.layout.fragment_food, container, false); 

    WebView webView = (WebView) view.findViewById(R.id.webView); 
    webView.setWebViewClient(new WebViewClient()); 
    webView.getSettings().setJavaScriptEnabled(true); 
    webView.loadUrl("http://food.pacho.co.ke/"); 

    return view; 
} 


} 

回答

1

你可以這樣做是這樣的:

public boolean isNetworkAvailable() { 
    ConnectivityManager cm = (ConnectivityManager) 
      getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo networkInfo = cm.getActiveNetworkInfo(); 
    if (networkInfo != null && networkInfo.isConnected()) { 
     return true; 
    } 
    return false; 
} 

然後在你的代碼要檢查連接:

if(isNetworkAvailable()) 
{ 
    // do things when connection is available 
} 
else 
    { 
    final android.app.AlertDialog.Builder alertDialog = new 
    android.app.AlertDialog.Builder(project_details.this); 
    alertDialog.setMessage("You don't have internet connection").setNegativeButton("OK", new DialogInterface.OnClickListener() { 
      @Override 
     public void onClick(DialogInterface dialogInterface, int i) { 
       dialog.dismiss(); 
       } 
     }); 
    alertDialog.show(); 

}

而且我認爲你必須在清單中添加權限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

而且我不知道將這項工作時,你有網絡,但實際上沒有互聯網連接。