Pages

June 1, 2012

Example : Android Network connectivity check

    /**
     * Checks Internet connectivity
     * @return
     */
    public boolean isNetworkAvailable() {
           Context context = getApplicationContext();
           ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
           if (connectivity == null) {
              Log.e(tag,"network not available");
           } else {
              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;
        }
Permission:

Example : Android Menu/Selected snippet.

    final int MENU_ADD=0;
    final int MENU_DELETE=1;
    final int MENU_VIEW=2;
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        
        menu.add(0, MENU_ADD, 0, "Add").setIcon(R.drawable.ic_launcher);
        menu.add(0, MENU_DELETE, 0, "Delete");
        menu.add(0, MENU_VIEW, 0, "View");
        
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        
        switch (item.getItemId()) {
        case MENU_ADD:
            Log.v("menu","Add clicked");
            return true;
            
        case MENU_DELETE:
            Log.v("menu","View clicked");
            return true;
            
        case MENU_VIEW:
            Log.v("menu","View clicked");
            return true;
        default:
            break;
        }
        
        return true;
    }