2015-04-22 15 views
8

Ho appena creato un'app per Android per il recupero dei dati da un sito web. Voglio verificare se il dispositivo ha una connessione Internet o no. Se il dispositivo ha una connessione Internet, esegui il mio codice e recuperi i dati e visualizzalo, altrimenti se il dispositivo non ha Internet, visualizza il messaggio di assenza di connessione Internet. Ho provato questo codice per controllare la connessione internet. Come posso chiamare il codice quando c'è una connessione Internet? Codiceapri l'app per Android quando la connessione internet è attiva, altrimenti non visualizza il messaggio di connessione internet

mio Java:

@Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_primary); 
     new FetchWebsiteData().execute();   
      } 
     }); 

    } 

    private class FetchWebsiteData extends AsyncTask<Void, Void, String[]> { 
     String websiteTitle, websiteDescription,websiteDescription1,websiteDescription2,websiteDescription3,listValue,listValue1; 
     ProgressDialog progress; 
     private Context context; 

     //check Internet connection. 
     private void checkInternetConnection(){ 

      ConnectivityManager check = (ConnectivityManager) this.context. 
        getSystemService(Context.CONNECTIVITY_SERVICE); 
      if (check != null) 
      { 
       NetworkInfo[] info = check.getAllNetworkInfo(); 
       if (info != null) 
        for (int i = 0; i <info.length; i++) 
         if (info[i].getState() == NetworkInfo.State.CONNECTED) 
         { 
          Toast.makeText(context, "Internet is connected", 
            Toast.LENGTH_SHORT).show(); 

         } 

      } 
      else{ 
       Toast.makeText(context, "not conencted to internet", 
         Toast.LENGTH_SHORT).show(); 
      } 
     } 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 

      //some code here 
     } 

     @Override 
     protected String[] doInBackground(Void... params) { 
      ArrayList<String> hrefs=new ArrayList<String>(); 
      try { 

       } 

      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      //get the array list values 
      for(String s:hrefs) 
      { 
       //some code 
      } 
      //parsing first URL 
      String [] resultArray=null; 
      try { 


      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      //parsing second URL 
      String [] resultArray1=null; 
      try { 



      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

      try{ 


      } catch (Exception e) { 
       e.printStackTrace(); 
      } 


      return null; 
     } 



     @Override 
     protected void onPostExecute(String[] result) { 

      ListView list=(ListView)findViewById(R.id.listShow); 
      ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1,result); 
      list.setAdapter(arrayAdapter); 
      mProgressDialog.dismiss(); 
     } 
    } 
} 

Come posso eseguire il codice quando la connessione è aperto e come visualizzare il messaggio quando applicazione non ha alcuna connessione a internet?

risposta

7

provare questo

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

una volta il metodo restituisce il valore che hanno per controllare

//detect internet and show the data 
    if(isNetworkStatusAvialable (getApplicationContext())) { 
     Toast.makeText(getApplicationContext(), "Internet detected", Toast.LENGTH_SHORT).show(); 
     new FetchWebsiteData().execute(); 
    } else { 
     Toast.makeText(getApplicationContext(), "Please check your Internet Connection", Toast.LENGTH_SHORT).show(); 

    } 
+0

ottimo lavoro.Grazie – prathik

4
public static boolean hasInternetAccess(Context context) { 

    if (isNetworkAvailable(context)) { 
     try { 
      HttpURLConnection urlc = (HttpURLConnection) 
       (new URL("http://clients3.google.com/generate_204") 
       .openConnection()); 
      urlc.setRequestProperty("User-Agent", "Android"); 
      urlc.setRequestProperty("Connection", "close"); 
      urlc.setConnectTimeout(1500); 
      urlc.connect(); 
      return (urlc.getResponseCode() == 204 && 
         urlc.getContentLength() == 0); 
     } catch (IOException e) { 
      Log.e(TAG, "Error checking internet connection", e); 
     } 
    } else { 
     Log.d(TAG, "No network available!"); 
    } 
    return false; 
} 
2

Creare una classe NetworkInformation.java

import android.content.Context; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 

public class NetworkInformation { 

    private static NetworkInfo networkInfo; 

    public static boolean isConnected(Context context) { 

      ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 

      try{ 
       networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

      // test for connection for WIFI 
      if (networkInfo != null 
        && networkInfo.isAvailable() 
        && networkInfo.isConnected()) { 
       return true; 
      } 

      networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 
      // test for connection for Mobile 
      if (networkInfo != null 
        && networkInfo.isAvailable() 
        && networkInfo.isConnected()) { 
       return true; 
      } 

      return false; 
     } 

} 

Ora verifica se la rete è disponibile o meno prima di chiamare un asynctask come questo:

if(NetworkInformation.isConnected(YourClassName.this)) 
     { 
      new FetchWebsiteData().execute();   
     }else{ 

      Toast.makeText(NewsAndEvents.this,R.string.no_connection,Toast.LENGTH_LONG).show(); 
     } 

Non dimenticate di includere i permessi di seguito in AndroidManifest.xml:

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

uso questo metodo per verificare la disponibilità della rete

public static boolean isNetworkAvailable(Context context) { 



    try{ 
    ConnectivityManager connectivityManager 
      = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); 
    boolean s= activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting(); 

     return s; 
    } 
    catch(Exception e){ 

     System.out.println("exception network"+e); 
     return false; 
    } 
} 

se restituisce vero si può andare avanti con la rete chiama altrimenti Toast un messaggio di non disponibilità della rete.

1

Utilizzare il codice riportato di seguito e creare una classe come NetworkAvailablity.java

public class NetworkAvailablity { 

    public static boolean checkNetworkStatus(Context context) { 
     boolean HaveConnectedWifi = false; 
     boolean HaveConnectedMobile = false; 

     ConnectivityManager cm = (ConnectivityManager) context 
       .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; 
    } 
} 

E nel vostro uso codice di queste righe seguenti, che verifica che la connessione internet è disponibile o non

 if (NetworkAvailablity.checkNetworkStatus(getActivity())) { 
      //code here 
     } 
     else 
     { 
     // give message here by Toast or create the alert dilog 
      Toast.makeText(context, "No network is available",Toast.LENGTH_LONG).show(); 
     } 
1
//Implement this code in MainActivity and check if isConnectingToInternet(), then allow Otherwise show the No Internet Connection message. 

public boolean isConnectingToInternet() { 
      ConnectivityManager connectivity = (ConnectivityManager) _context 
        .getSystemService(Context.CONNECTIVITY_SERVICE); 
      if (connectivity != null) { 
       NetworkInfo[] info = connectivity.getAllNetworkInfo(); 
       if (info != null) 
        for (int i = 0; i < info.length; i++) 
         if (info[i].getState() == NetworkInfo.State.CONNECTED) { 
          return true; 
         } 

      } 
      return false; 
     } 
1

per controllare se l'utente si connettono al wifi o qualsiasi punto di accesso è meglio controllare prima questo metodo per vedere se l'utente ha una connessione o no e se restituisce true è possibile verificare se ha una connessione reale o meno con il metodo successivo

public static boolean isOnline(Context context) { 
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
    return netInfo != null && netInfo.isConnectedOrConnecting(); 
} 

per verificare se l'utente ha una reale il traffico di inviare richiesta sulla rete

essere consapevoli che non si deve chiamare il metodo hasTraffic() nel thread principale (è possibile utilizzare AsyncTask)

public static boolean hasTraffic(){ 

    try { 

     URL url = new URL("http://www.google.com/"); 
     HttpURLConnection urlc = (HttpURLConnection)url.openConnection(); 
     urlc.setRequestProperty("User-Agent", "test"); 
     urlc.setRequestProperty("Connection", "close"); 
     urlc.setConnectTimeout(2000); // mTimeout is in seconds 
     urlc.connect(); 
     if (urlc.getResponseCode() == 200) { 
      Log.d("check Traffic ", "has traffic"); 
      return true; 
     } else { 
      return false; 
     } 
    } catch (Exception e) { 
     Log.i("warning", "Error checking internet connection", e); 
     return false; 
    } 

} 

per controllare la connessione internet

 new AsyncTask<Void, Void, Boolean>() { 
     @Override 
     protected void onPostExecute(Boolean flag) { 

      if(flag == true){ 
       // do whatever you want 
      }else{ 
       cantAccessToService(); 
      } 
     } 

     @Override 
     protected Boolean doInBackground(Void... voids) { 
      if(isOnline(SplashActivity.this) && hasTraffic()){ 
       return true ; 
      }else{ 
       return false ; 
      } 
     } 
    }.execute(); 
Problemi correlati