2013-12-12 3 views
0

Я хочу проверить подключение к Интернету, после этого заполнить список. но мои коды для проверки подключения к Интернету не работают. я отключу свое сетевое подключение для тестирования, но mycodes (проверка соединения не работает). , пожалуйста, помогите мне, что не так.Проверка подключения к Интернету не работает в android

connectionDetector:

public class ConnectionDetector { 
    private Context _context; 

    public ConnectionDetector(Context context){ 
     this._context = context; 
    } 

    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; 
    } 
} 

моя активность:

protected void onCreate(Bundle bundle) { 
     super.onCreate(bundle); 
     setContentView(R.layout.updateapp); 
     oslist = new ArrayList<HashMap<String, String>>(); 
     Btngetdata = (Button)findViewById(R.id.getdata); 
     Btngetdata.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       //check Internet Connection 
       Boolean isInternetPresent = false; 
       ConnectionDetector cd; 
       cd = new ConnectionDetector(getApplicationContext()); 
       isInternetPresent = cd.isConnectingToInternet(); 

       if (isInternetPresent) { 
       new JSONParse().execute(); } 

       else { 
        // Internet connection is not present 
        // Ask user to connect to Internet 
        showAlertDialog(UpdateFromSite.this, "No Internet Connection", 
          "You don't have internet connection.", false); 
       } 

      } 
     }); 
    } 

    public void showAlertDialog(Context context, String title, String message, Boolean status) { 
     AlertDialog alertDialog = new AlertDialog.Builder(context).create(); 
     alertDialog.setTitle(title); 
     alertDialog.setMessage(message); 
     alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail); 
     alertDialog.setButton("OK", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
      } 
     }); 
     alertDialog.show(); 
    } 

    private class JSONParse extends AsyncTask<String, String, JSONObject> { 
     private ProgressDialog pDialog; 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 

      name = (TextView)findViewById(R.id.nameNewItem); 
      description = (TextView)findViewById(R.id.descriptionNewItem); 
      price = (TextView)findViewById(R.id.priceNewItem); 
      pDialog = new ProgressDialog(UpdateFromSite.this); 
      pDialog.setMessage("Getting Data ..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
     } 
     @Override 
     protected JSONObject doInBackground(String... args) { 
      JSONParser jParser = new JSONParser(); 
      // Getting JSON from URL 
      JSONObject json = jParser.getJSONFromUrl(url); 
      return json; 
     } 
     @Override 
     protected void onPostExecute(JSONObject json) { 
      pDialog.dismiss(); 
      try { 
       // Getting JSON Array from URL 
       android = json.getJSONArray(TAG_OS); 
       for(int i = 0; i < android.length(); i++){ 
        JSONObject c = android.getJSONObject(i); 

        // Storing JSON item in a Variable 
        String name = c.getString(TAG_NAME); 
        String description = c.getString(TAG_DESCRIPTION); 
        String price = c.getString(TAG_PRICE); 

        // Adding value HashMap key => value 
        HashMap<String, String> map = new HashMap<String, String>(); 
        map.put(TAG_NAME, name); 
        map.put(TAG_DESCRIPTION, description); 
        map.put(TAG_PRICE, price); 
        oslist.add(map); 
        list=(ListView)findViewById(R.id.listupdate); 
        ListAdapter adapter = new SimpleAdapter(UpdateFromSite.this, oslist, 
          R.layout.updateapprow, 
          new String[] { TAG_NAME,TAG_DESCRIPTION, TAG_PRICE }, new int[] { 
          R.id.nameNewItem,R.id.descriptionNewItem, R.id.priceNewItem}); 
        list.setAdapter(adapter);} 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

manifest.xml:

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

Ваш велосипед по всем типам сетей, один из которых может возвращать true, вы должны проверить тип в этом случае. –

ответ

0
public static void getNetworkState(Context context,OnConnectListener onConnectListener) { 
    final ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo(); 
    if (activeNetwork != null && activeNetwork.isConnected()) { 
     //notify user you are online 
     onConnectListener.onConnect(); 
    } else { 
     //notify user you are not online 
     onConnectListener.onDisConnect(); 
    } 
} 
0

Используйте этот код, чтобы проверить подключение к Интернету

Просто позвоните checkInternetConnection (getBaseContext())

/** Check network availability */ 
public static boolean checkInternetConnection(Context context) { 
    ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo i = conMgr.getActiveNetworkInfo(); 
    if (i == null) 
     return false; 
    if (!i.isConnected()) 
     return false; 
    if (!i.isAvailable()) 
     return false; 
    return true; 
} 


} 

Этот код проверяется!

0

Попробуйте один

public static boolean isNetworkConnection(Context context) 
    { 
     final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo(); 
     if(activeNetworkInfo!= null && activeNetworkInfo.isAvailable() && activeNetworkInfo.isConnected()) 
      return true; 
     else 
      return false; 
    } 
0

Попробуйте это.

if(isNetworkConnected()){ 
    // your task 
} else { 
    Toast.makeText(getBaseContext(), "No internet connection available.",Toast.LENGTH_SHORT).show(); 
} 

И isNetworkConnected() выглядит следующим образом:

private boolean isNetworkConnected() { 
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo ni = cm.getActiveNetworkInfo(); 
    if (ni == null) { 
     // There are no active networks. 
     return false; 
    } else 
    return true; 
} 
0

один я использую и работает:

public class DetectConnection { 

    private Context _context; 

    public DetectConnection(Context context){ 
     this._context = context; 
    } 

    public boolean isConnectedToInternet(){ 
     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; 
    } 
} 

в деятельности:

DetectConnection dc = new DetectConnection(getApplicationContext()); 
     if(dc.isConnectedToInternet()==true) 
     { 
     new AsyncGet().execute(); 
     } 
     else 
     { 
      Toast.makeText(getSherlockActivity(), "No Active Connection", Toast.LENGTH_SHORT).show(); 
     } 
1

Используйте следующие метод проверки сетевой активности:

public static boolean isNetworkAvailable(Context context) { 
    ConnectivityManager connectivityManager = (ConnectivityManager) context 
      .getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo activeNetworkInfo = connectivityManager 
      .getActiveNetworkInfo(); 
    return activeNetworkInfo != null && activeNetworkInfo.isConnected(); 
} 
0

Попробуйте это ..

public class ConnectionDetector { 
    private Context _context; 

    public ConnectionDetector(Context context){ 
     this._context = context; 
    } 

    public boolean isConnectingToInternet(){ 
     if(_context != null) 
     { 
      ConnectivityManager connec = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE); 
      try { 
       android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI); 

       android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 

       if (wifi.isConnected()||mobile.isConnected()) 
        return true; 
       else if (wifi.isConnected() && mobile.isConnected()) 
        return true; 
       else 
        return false; 

      } catch (NullPointerException e) { 
       Log.d("ConStatus", "No Active Connection"); 
       return false; 
      } 
     } 
     else 
     { 
      return false; 
     } 
    } 
0

Попробуйте этот код.

public static boolean isConnectingToInternet(Context context) { 
     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; 

    } 
Смежные вопросы