2012-04-22 244 views
-1

我想我應該開始說我對eclipse和java完全陌生。我正在嘗試使用eclipse創建一個啓動我的網頁的android應用程序。我有一個我的代碼很好用的例子,但它非常複製並粘貼到我在網上找到的示例中,所以請原諒我的草率代碼。我想知道如何檢查互聯網或無線連接是否可用..如果沒有連接顯示警報(無互聯網連接)..我發現了一些類似的問題,但是,我只是不知道在哪裏放置碼?有人可以告訴我嗎?檢查互聯網連接

package com.mysite.news; 

    import com.mysite.news.R; 
    import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.graphics.Bitmap; 
import android.net.Uri; 
import android.os.Bundle; 
import android.view.KeyEvent; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.Window; 

import android.webkit.WebChromeClient; 
import android.webkit.WebSettings; 
import android.webkit.WebView; 
import android.webkit.WebViewClient; 
import android.widget.Toast; 




public class WebActivity extends Activity { 

    private WebView wv; 

    private String LASTURL = ""; 

    Menu myMenu = null; 

    private static final String PREFS_NAME = "MyPrefs"; 



    private Boolean imgOn; 

    /** 
    * Called when the activity is first created. 
    */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     this.getWindow().requestFeature(Window.FEATURE_PROGRESS); 
     setContentView(R.layout.web_view); 

     wv = (WebView) findViewById(R.id.web_view); 

     WebSettings webSettings = wv.getSettings(); 
     webSettings.setSavePassword(true); 
     webSettings.setSaveFormData(true); 
     webSettings.setJavaScriptEnabled(true); 
     webSettings.setUseWideViewPort(true); 
     webSettings.setLoadWithOverviewMode(true); 
     webSettings.setSupportZoom(false); 


     SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 
     imgOn = settings.getBoolean("IMGMODE", false); 
     webSettings.setLoadsImagesAutomatically(imgOn); 

     final Activity activity = this; 


     // start ProgressDialog with "Page loading..." 
     final ProgressDialog dialog = new ProgressDialog(activity); 
     dialog.setMessage("Page loading..."); 
     dialog.setIndeterminate(true); 
     dialog.setCancelable(true); 
     dialog.show(); 

     wv.setWebChromeClient(new WebChromeClient() { 
      public void onProgressChanged(WebView view, int progress) { 
       // set address bar and progress 
//    activity.setTitle(" " + LASTURL); 
//    activity.setProgress(progress * 100); 

       if(progress == 100) { 
        // stop ProgressDialog after loading 
        dialog.dismiss(); 

//     activity.setTitle(" " + LASTURL); 
       } 
      } 
     }); 

     wv.setWebViewClient(new WebViewClient() { 
      public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { 
       Toast.makeText(getApplicationContext(), "Error: " + description + " " + failingUrl, Toast.LENGTH_LONG).show(); 
      } 

      @Override 
      public boolean shouldOverrideUrlLoading(WebView view, String url) { 
       if(url.indexOf("mysite") <= 0) { 
        // the link is not for a page on my site, so launch another Activity that handles URLs 
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 
        startActivity(intent); 
        return true; 
       } 
       return false; 
      } 

      public void onPageStarted(WebView view, String url, Bitmap favicon) { 
       LASTURL = url; 
       view.getSettings().setLoadsImagesAutomatically(true); 
       view.getSettings().setBuiltInZoomControls(true); 
      } 

      public void onPageFinished(WebView view, String url) { 
       view.loadUrl("javascript:(function() { " + 
             "hide('sidebar');" + 
             //"var parent = document.getElementsByClassName('page-navigation')[0];"+ 
             //"var panel = document.getElementsByClassName('panel-tools')[0];"+ 
             //"var div = document.createElement('div');"+ 
             //"div.innerHTML = panel.innerHTML;"+ 
             //"parent.appendChild(div);"+ 
             //"panel.innerHTML = '';"+ 
             //"div.style['margin-left'] = '31px';"+ 
             "var panel = document.getElementById('search');" + 
             "panel.style['width'] = '55px';" + 

             //"var imgs=document.getElementsByTagName('IMG');for(var i=0;i<imgs.length;i++){if (imgs[i].height=60) {imgs[i].src='';imgs[i].width=0;} }"+ 
             //"var urls=document.getElementsByTagName('li');for(var i=0;i<urls.length;i++){if (urls[i].style='margin: -14px 0pt 0pt;'){urls[i].style['display'] = 'none';}}"+ 
             //"hideByClass('panel-tools');"+ 
             "function hide(id){if (document.getElementById(id)){document.getElementById(id).style['display'] = 'none';}}" + 
             //"function hideByClass(c){var e=document.getElementsByClassName(c);for(var i=0;i<e.length;i++){e[i].style['display'] = 'none';}}"+ 
             "})()"); 
       if(imgOn) { 
        view.getSettings().setLoadsImagesAutomatically(true); 
        view.getSettings().setSupportZoom(false); 

       } 
      } 
     }); 
     wv.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); 
     wv.setScrollbarFadingEnabled(false); 
     wv.loadUrl("http://www.mysite.com"); 
    } 

    @Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
     if((keyCode == KeyEvent.KEYCODE_BACK) && wv.canGoBack()) { 
      wv.goBack(); 
      return true; 
     } 
     return super.onKeyDown(keyCode, event); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     super.onCreateOptionsMenu(menu); 

     this.myMenu = menu; 
     MenuItem item = menu.add(0, 1, 0, "MAIN PAGE"); 
     item.setIcon(R.drawable.home); 
     MenuItem item2 = menu.add(0, 2, 0, "BACK"); 
     item2.setIcon(R.drawable.arrowleft); 
     MenuItem item3 = menu.add(0, 3, 0, "Reload"); 
     item3.setIcon(R.drawable.s); 
     MenuItem item4 = menu.add(0, 4, 0, "CLEAR CACHE"); 
     item4.setIcon(R.drawable.trash); 
     MenuItem item5 = menu.add(0, 5, 0, "Rate"); 
     item5.setIcon(R.drawable.vote); 
     MenuItem item6 = menu.add(0, 6, 0, "Exit"); 
     item6.setIcon(R.drawable.close); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     switch(item.getItemId()) { 
      case 1: 
       wv.loadUrl("http://mysite.com"); 
       break; 
      case 2: 
       if(wv.canGoBack()) { 
        wv.goBack(); 
       } 
       break; 
      case 3: 
       wv.loadUrl(LASTURL); 
       break; 
      case 4: 
       wv.clearCache(true); 
       break; 
      case 5: 
       Intent marketIntent2 = new Intent(Intent.ACTION_VIEW, Uri.parse(
         "https://play.google.com/store/apps/details?id=" + getPackageName())); 
        startActivity(marketIntent2); 
       break; 
      case 6: 
       finish(); 
       break; 

     } 

     return true; 
    } 

    private void saveSettings(Boolean val) { 
     SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 
     SharedPreferences.Editor editor = settings.edit(); 
     editor.putBoolean("IMGMODE", val); 
     editor.commit(); 
    } 
} 
+0

所以下半場(你想放置的代碼)在哪裏。你只是想在活動啓動時進行測試。也許只是在另一個活動中,如果你有互聯網連接開始這個活動或以其他方式顯示其他內容。這是一個很好的問題分離。 – Blundell 2012-04-22 19:18:21

+0

在執行wv.loadurl()之前,您必須檢查是否有Internet連接。如果有互聯網連接 - >繼續,如果沒有 - >顯示消息 – 2012-04-22 19:23:43

回答

0

這裏有一個輔助類我使用的網絡連接:

public class NetworkUtils 
{ 

    public static boolean isOnline(Service service) 
    { 
     ConnectivityManager cm = (ConnectivityManager) service.getSystemService(Context.CONNECTIVITY_SERVICE); 

     NetworkInfo netInfo = cm.getActiveNetworkInfo(); 

     if (netInfo != null && netInfo.isConnected()) 
     { 
      return true; 
     } 

     return false; 
    } 

} 

而且不要忘記將權限添加到AndroidManifest.xml中:

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

我想我只想測試它在活動啓動..我在這裏找到了一些東西[鏈接](http://stackoverflow.com/questions/4238921/android-detect-whether-there-is-an-internet-connection-available#_ = _)這可能會起作用,但就像我說過的,我真的不知道該把它放在哪裏...... @Blundell – 2012-04-22 19:29:24

+0

我在想這樣的事情...'私人布爾checkInternetConnection(){ ConnectivityManager conMgr =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); // ARE WE連接到網絡 如果(conMgr.getActiveNetworkInfo()!= NULL && conMgr.getActiveNetworkInfo()。isAvailable() && conMgr.getActiveNetworkInfo()。isConnected()){ 返回true; (TAG,「互聯網連接不存在」);其他{ }其他{ Log.v return false; } }'我可以把它放在上面的代碼中嗎?如果是這樣的話? – 2012-04-22 20:31:38

+0

使用我發佈的幫助類。然後,無論何時您需要檢查是否存在連接,只需調用'if(!NetworkUtils.isOnline(service)){return;根據需要。即在調用'wv.loadurl()'之前檢查網絡是否可用。顯然,參數'service'需要來自調用類。 – 2012-04-22 20:44:06

0
private boolean checkNetwork() { 
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo networkInfo = cm.getActiveNetworkInfo(); 
    if (networkInfo != null && networkInfo.isConnected()) { 
     return true; 
    } else { 
     Toast.makeText(getApplicationContext(), 
       "Sorry, Network Unavailable! :(", Toast.LENGTH_LONG).show(); 
    } 
    return false; 
} 

這段代碼幫了我,希望它也能幫助你。您的使用情況可能如下所示。

if (!checkNetwork()) { 
    //TODO Network Not Available 
} else { 
    //TODO Network Available  
} 

你可能想要把Toast notificationfunction()