2012-04-20 14 views
10

Nella mia applicazione i dati provengono da Internet e sto cercando di creare una funzione che controlli se è disponibile o meno una connessione Internet e se non lo è, dà un avviso messege che nessuna connessione internet disponibile. sto usando il seguente codice. ma non funzionaVisualizza un avviso quando la connessione Internet non è disponibile nell'applicazione Android

public void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main1); 
    if (isOnline()) 
    { 
    // my code 
    } 
    else 
    { 
    Hotgames4meActivity1.this.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS)); 
    try { 
     AlertDialog alertDialog = new AlertDialog.Builder(Hotgames4meActivity1.this).create(); 

     alertDialog.setTitle("Info"); 
     alertDialog.setMessage("Internet not available, Cross check your internet connectivity and try again"); 
     //alertDialog.setIcon(R.drawable.alerticon); 
     alertDialog.setButton("OK", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 
      finish(); 

     } 
     }); 

     alertDialog.show(); 
    } 
    catch(Exception e) 
    { 
     //Log.d(Constants.TAG, "Show Dialog: "+e.getMessage()); 
    } 
    } 
} 
+0

Che problema stai affrontando con questo metodo ??? – Sandeep

+0

usa il toast per mostrare il messaggio –

+0

@DeepSan: dove devo inserire questo codice, voglio controllare la connessione prima che l'attività principale venga creata. grazie per la risposta – ZooZoo

risposta

4
public void onCreate(Bundle obj) 
{ 
    super.onCreate(obj) 
    setContextView(layout); 

    if (isOnline()) 
     //do whatever you want to do 
    else 
     { 
     try { 
    AlertDialog alertDialog = new AlertDialog.Builder(con).create(); 

    alertDialog.setTitle("Info"); 
    alertDialog.setMessage("Internet not available, Cross check your internet connectivity and try again"); 
    alertDialog.setIcon(android.R.drawable.ic_dialog_alert); 
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 
     finish(); 

     } 
    }); 

    alertDialog.show(); 
    } 
    catch(Exception e) 
    { 
     Log.d(Constants.TAG, "Show Dialog: "+e.getMessage()); 
    } 
     } 
} 
+0

hi DeepSan. ho applicato sopra il codice. ma ancora, non sta mostrando alcun alret n app respingere :(.. il suo schifo. plz help – ZooZoo

+0

c'è qualche eccezione ??? o se possibile postare il codice, perché tutti i metodi in questo thread stanno funzionando bene, si prega di inviare il tuo codice ... – Sandeep

+0

grazie per il codice .. non funziona sull'emulatore ma funziona perfettamente sul dispositivo :) – ZooZoo

0

aggiuntivo permesso nel vostro manifest.xml

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

ho già aggiunto .. – ZooZoo

2

provare questo

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
     android.net.NetworkInfo wifi = cm 
       .getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
     android.net.NetworkInfo datac = cm 
       .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 
     if ((wifi != null & datac != null) 
       && (wifi.isConnected() | datac.isConnected())) { 
       //connection is avlilable 
       }else{ 
       //no connection 
        Toast toast = Toast.makeText(context, "No Internet Connection", 
       Toast.LENGTH_LONG); 
     toast.show(); 
       } 

e non dimenticare di aggiungere seguenti permssions

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

sto lavorando su dove mettere questo codice. m wrting code in oncreate ma non funziona lì. :( – ZooZoo

+0

E 'meglio metterlo in un metodo onResume() ma questo non può essere il problema – sampathpremarathna

+0

ma voglio cheak prima dell'attività creata. Se non c'è internet, l'attività principale non dovrebbe caricare n c'è un avviso msg. – ZooZoo

9
public boolean isOnline() { 
    ConnectivityManager conMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo netInfo = conMgr.getActiveNetworkInfo(); 

    if(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()){ 
     Toast.makeText(context, "No Internet connection!", Toast.LENGTH_LONG).show(); 
     return false; 
    } 
return true; 
} 

E si deve aggiungere premission per l'accesso stato della rete e di Internet:

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

grazie, ho apportato delle modifiche. puoi suggerire dove mettere questo metodo. Voglio controllare questo prima che l'attività principale venga avviata. – ZooZoo

+0

'if (isOnline() == false) { YourActivity.this.startActivity (new Intent (Settings.ACTION_WIRELESS_SETTINGS)); } ' – vtuhtan

1

Forse provare questo

handler.removeCallbacks(checkInternetConnection); 
       handler.postDelayed(checkInternetConnection, UPDATE_INTERVAL); 



    public Runnable checkInternetConnection = new Runnable() { 

      public void run() { 

       handler.postDelayed(checkInternetConnection, UPDATE_INTERVAL); 
       ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 

       if(conMgr.getActiveNetworkInfo()!=null 
       && conMgr.getActiveNetworkInfo().isAvailable() 
       && conMgr.getActiveNetworkInfo().isConnected()){ 
        alertOff(); 

       } 
       else{ 
        alertOn(); 
       } 

      } 
     }; 
0

Il metodo di cui sopra solo indica se il cellulare ha la possibilità di connettersi al Internet, tuttavia, non dice esattamente se la connettività esiste .. ad esempio, potresti essere in grado di connettersi a un wifi, ma essere in un bar in cui devi inserire le credenziali in un sito Web hot spot ... o, il tuo la rete domestica potrebbe funzionare, a d sei connesso ad esso, ma non puoi accedere ad internet. Utilizzare il codice seguente per verificare la connettività Internet. è preferibile utilizzarlo all'interno di un asynctask. il permesso

public boolean hasActiveInternetConnection() 
{ 
     try 
     { 
      HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection()); 
      urlc.setRequestProperty("User-Agent", "Test"); 
      urlc.setRequestProperty("Connection", "close"); 
      urlc.setConnectTimeout(4000); 
      urlc.setReadTimeout(4000); 
      urlc.connect(); 
      networkcode2 = urlc.getResponseCode(); 
      return (urlc.getResponseCode() == 200); 
     } catch (IOException e) 
     { 
      Log.i("warning", "Error checking internet connection", e); 
      return false; 
     } 

} 
0
public boolean isOnline() 
{ 


ConnectivityManager connectionManager; 

if(app_context!=null) 

connectionManager = (ConnectivityManager) app_context.getSystemService(Context.CONNECTIVITY_SERVICE); 

     else 
      return false; 

     try 
     { 
      if (connectionManager.getActiveNetworkInfo().isConnected()) 
      { 
       Log.e(THIS_FILE, "Communicator ....isConnected()"); 
       return true; 
      } 
      else 
      { 
       Log.e(THIS_FILE, "Communicator ....isNotConnected()"); 
       return false; 
      } 
     } 
     catch (NullPointerException e) 
     { 
      Log.e(THIS_FILE, "No Active Connection"); 
      return false; 
     } 
    } 

insieme a manifestare

<uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
0
private boolean isNetworkAvailable() { 
    ConnectivityManager connectivityManager 
      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); 
    return activeNetworkInfo != null && activeNetworkInfo.isConnected(); 
} 

if(!isNetworkAvailable()){ 
     //Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT).show(); 
     new AlertDialog.Builder(this) 
     .setIcon(android.R.drawable.ic_dialog_alert) 
     .setTitle("Closing the App") 
     .setMessage("No Internet Connection,check your settings") 
     .setPositiveButton("Close", new DialogInterface.OnClickListener() 
    { 
     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      finish();  
     } 

    }) 
    .show(); 
    } 
0

Questo è il lavoro nel mio codice, provate questo:

@Override 
protected void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    if (hasConnection(MainActivity.this)){ 
     //call methods 
     //getJsonData(); 
     } 
    else{ 
     showNetDisabledAlertToUser(MAinActivity.this); 
    } 
} 

public boolean hasConnection(Context context){ 
    ConnectivityManager cm=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);    
    NetworkInfowifiNetwork=cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
    if (wifiNetwork != null && wifiNetwork.isConnected()){ 
     return true; 
    }   
    NetworkInfo mobileNetwork=cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 
    if (mobileNetwork != null && mobileNetwork.isConnected()){ 
     return true; 
    } 
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); 
    if (activeNetwork != null && activeNetwork.isConnected()){ 
     return true; 
    } 
    return false; 
} 

public static void showNetDisabledAlertToUser(final Context context){ 
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context, AlertDialog.THEME_TRADITIONAL); 
    alertDialogBuilder.setMessage("Would you like to enable it?") 
      .setTitle("No Internet Connection") 
      .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); 
          context.startActivity(dialogIntent); 
         } 
        }); 

       alertDialogBuilder.setNegativeButton(" Cancel ", new DialogInterface.OnClickListener(){ 
       public void onClick(DialogInterface dialog, int id){ 
        dialog.cancel(); 
       } 
      }); 
    AlertDialog alert = alertDialogBuilder.create(); 
    alert.show(); 
} 
+0

Questo visualizza solo un avviso, ma la domanda richiede anche il controllo se un è disponibile la connessione Internet o non sapere quando visualizzare l'avviso. – Marilia

+0

grazie marilia ..... ho modificato la mia risposta si prega di controllare questo .... questo potrebbe essere utile per voi –

+0

il permesso di Internet è richiesto nel manifest –

0

scrivere questo codice nel metodo creare

4

È possibile utilizzare questi metodi ovunque

public void checkNetworkConnection(){ 
    AlertDialog.Builder builder =new AlertDialog.Builder(this); 
    builder.setTitle("No internet Connection"); 
    builder.setMessage("Please turn on internet connection to continue"); 
    builder.setNegativeButton("close", new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      dialog.dismiss(); 
     } 
    }); 
    AlertDialog alertDialog = builder.create(); 
    alertDialog.show(); 
} 

public boolean isNetworkConnectionAvailable(){ 
    ConnectivityManager cm = 
      (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); 

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); 
    boolean isConnected = activeNetwork != null && 
      activeNetwork.isConnected(); 
    if(isConnected) { 
     Log.d("Network", "Connected"); 
     return true; 
     } 
    else{ 
     checkNetworkConnection(); 
     Log.d("Network","Not Connected"); 
     return false; 
    } 
} 

quando è necessario controllare la connessione disponibile isNetworkConnectionAvailable call() method.if la rete non disponibili si aprirà la vostra finestra di dialogo. Se hai bisogno di controllare la rete in più schermi aggiungi questi metodi alla super classe ed eredita quella classe in un'altra classe e chiama questo metodo quando necessario

Problemi correlati