Example usage for android.net NetworkInfo isConnected

List of usage examples for android.net NetworkInfo isConnected

Introduction

In this page you can find the example usage for android.net NetworkInfo isConnected.

Prototype

@Deprecated
public boolean isConnected() 

Source Link

Document

Indicates whether network connectivity exists and it is possible to establish connections and pass data.

Usage

From source file:com.moez.QKSMS.mmssms.Transaction.java

private void sendMMSWiFi(final byte[] bytesToSend) {
    // enable mms connection to mobile data
    mConnMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo.State state = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS).getState();

    if ((0 == state.compareTo(NetworkInfo.State.CONNECTED)
            || 0 == state.compareTo(NetworkInfo.State.CONNECTING))) {
        sendData(bytesToSend);/*ww  w. jav  a2  s  . c om*/
    } else {
        int resultInt = mConnMgr.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, "enableMMS");

        if (resultInt == 0) {
            try {
                Utils.ensureRouteToHost(context, settings.getMmsc(), settings.getProxy());
                sendData(bytesToSend);
            } catch (Exception e) {
                Log.e(TAG, "exception thrown", e);
                sendData(bytesToSend);
            }
        } else {
            // if mms feature is not already running (most likely isn't...) then register a receiver and wait for it to be active
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            final BroadcastReceiver receiver = new BroadcastReceiver() {

                @Override
                public void onReceive(Context context1, Intent intent) {
                    String action = intent.getAction();

                    if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                        return;
                    }

                    NetworkInfo mNetworkInfo = mConnMgr.getActiveNetworkInfo();
                    if ((mNetworkInfo == null)
                            || (mNetworkInfo.getType() != ConnectivityManager.TYPE_MOBILE_MMS)) {
                        return;
                    }

                    if (!mNetworkInfo.isConnected()) {
                        return;
                    } else {
                        alreadySending = true;

                        try {
                            Utils.ensureRouteToHost(context, settings.getMmsc(), settings.getProxy());
                            sendData(bytesToSend);
                        } catch (Exception e) {
                            Log.e(TAG, "exception thrown", e);
                            sendData(bytesToSend);
                        }

                        context.unregisterReceiver(this);
                    }

                }

            };

            context.registerReceiver(receiver, filter);

            try {
                Looper.prepare();
            } catch (Exception e) {
                // Already on UI thread probably
            }

            // try sending after 3 seconds anyways if for some reason the receiver doesn't work
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (!alreadySending) {
                        try {
                            context.unregisterReceiver(receiver);
                        } catch (Exception e) {

                        }

                        try {
                            Utils.ensureRouteToHost(context, settings.getMmsc(), settings.getProxy());
                            sendData(bytesToSend);
                        } catch (Exception e) {
                            Log.e(TAG, "exception thrown", e);
                            sendData(bytesToSend);
                        }
                    }
                }
            }, 7000);
        }
    }
}

From source file:com.BeatYourRecord.SubmitActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    boolean haveConnectedWifi = false;
    boolean haveConnectedMobile = false;
    ConnectivityManager cm = (ConnectivityManager) 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;
    }//from  w  ww .j a v  a 2s . c  o  m
    if (haveConnectedWifi == false) {
        showDialog(11);
    }
    super.onCreate(savedInstanceState);

    // SharedPreferences pref = SubmitActivity.this.getSharedPreferences("TourPref", 0); // 0 - for private mode
    //Editor editor = pref.edit();
    //auth = pref.getString("BYR_session", null);
    /*SharedPreferences pref6 = SubmitActivity.this.getSharedPreferences("TourPref", 0); // 0 - for private mode
      Editor editor7 = pref6.edit();
      //this.setContentView(R.layout.submit);
        String logoutme = pref6.getString("log", null);
        //log.v("log",logoutme);
     */
    SharedPreferences pref1 = SubmitActivity.this.getSharedPreferences("TourPref", 0); // 0 - for private mode
    Editor editor1 = pref1.edit();
    tourid = pref1.getString("id", null);
    logout = pref1.getString("log", null);
    filepath = pref1.getString("filepath", null);
    //log.v("id",tourid);
    //log.v("log",logout);

    Log.v("reached here first", "reached here first");
    File f = new File("/data/data/com.BeatYourRecord/shared_prefs/Tester15.xml");
    if (f.exists() && logout.equals("yes") == false) {

        //log.v("yyy","yyy");
        SharedPreferences pref = SubmitActivity.this.getSharedPreferences("Tester15", 0); // 0 - for private mode
        Editor editor = pref.edit();
        this.setContentView(R.layout.submit);
        auth = pref.getString("BYR_session", null);

    } else {
        //log.v("yyy","yyy1");
        this.setContentView(R.layout.submit1);
        showDialog(10);
    }

    //   String checksession = pref.getString("BYR_session", null);
    //   //log.v("checksession", checksession);

    ////log.v("Authhere",auth);
    this.authorizer = new ClientLoginAuthorizer.ClientLoginAuthorizerFactory().getAuthorizer(this,
            ClientLoginAuthorizer.YOUTUBE_AUTH_TOKEN_TYPE);

    dbHelper = new DbHelper(this);
    dbHelper = dbHelper.open();

    Intent intent = this.getIntent();
    this.videoUri = intent.getData();
    SharedPreferences pref1223 = SubmitActivity.this.getSharedPreferences("TourPref", 0); // 0 - for private mode
    Editor editor1223 = pref1223.edit();
    filepath = pref1223.getString("filepath", null);
    // this.videoUri =

    //   Uri path = Uri.parse(filepath);
    //File f1 = new File(filepath);  
    //Uri imageUri = Uri.fromFile(f1);
    //this.videoUri = imageUri;
    //this.videoUri = path;

    Log.v("Reached here second", "Reached here secord");
    //this.videoUri= Uri.fromFile(new File("/sdcard/Movies/com.BeatYourRecord/BYR_tournName_dateTim_20130724181901222.mp4"));
    //log.v("haha","haha");

    MediaScannerConnectionClient mediaScannerClient = new MediaScannerConnectionClient() {
        private MediaScannerConnection msc = null;
        {
            msc = new MediaScannerConnection(getApplicationContext(), this);
            msc.connect();
        }

        public void onMediaScannerConnected() {
            msc.scanFile(filepath, null);
        }

        public void onScanCompleted(String path, Uri uri) {
            //This is where you get your content uri
            Log.d("test3", uri.toString());
            needed = uri;
            // videoUri=needed;

            msc.disconnect();
        }
    };

    String videoPath = "";

    try {
        videoPath = getFilePathFromUri(this.videoUri);
        filepath1 = videoPath;
        Log.v("videoPath", videoPath);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    File videoFile = new File(videoPath);

    this.ytdDomain = intent.getExtras().getString(DbHelper.YTD_DOMAIN);
    this.assignmentId = intent.getExtras().getString(DbHelper.ASSIGNMENT_ID);

    this.domainHeader = (TextView) this.findViewById(R.id.domainHeader);
    domainHeader.setText(SettingActivity.getYtdDomains(this).get(this.ytdDomain));

    this.preferences = this.getSharedPreferences(MainActivity.SHARED_PREF_NAME, Activity.MODE_PRIVATE);
    this.youTubeName = preferences.getString(DbHelper.YT_ACCOUNT, null);

    final Button submitButton = (Button) findViewById(R.id.submitButton);
    submitButton.setEnabled(false);

    submitButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            showDialog(DIALOG_LEGAL);
        }
    });
    addusertotournament();
    Button cancelButton = (Button) findViewById(R.id.cancelButton);
    cancelButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            //SharedPreferences pref1 = SubmitActivity.this.getSharedPreferences("TourPref", 0); // 0 - for private mode
            //Editor editor = pref1.edit();
            //editor.putString("filepath", permfilepath); 
            //editor.commit();
            Intent intent = new Intent(SubmitActivity.this, DetailsActivity.class);
            //    intent.putExtra(DbHelper.YTD_DOMAIN, "TODO-appname.appspot.com");

            //intent.setData(Uri.fromFile(file));   
            startActivity(intent);
            finish();
            // setResult(RESULT_CANCELED);
            //finish();
        }
    });

    Button forgotButton = (Button) findViewById(R.id.forgotButton);

    forgotButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            //SharedPreferences pref1 = SubmitActivity.this.getSharedPreferences("TourPref", 0); // 0 - for private mode
            //Editor editor = pref1.edit();
            //editor.putString("filepath", permfilepath); 
            //editor.commit();

            SharedPreferences pref155 = getApplicationContext().getSharedPreferences("TourPref", 0); // 0 - for private mode
            Editor editor155 = pref155.edit();

            editor155.putString("filepath", filepath1);
            editor155.commit();
            Log.v("fielpathss", filepath1);
            Intent intent = new Intent(SubmitActivity.this, DetailsActivity.class);
            //    intent.putExtra(DbHelper.YTD_DOMAIN, "TODO-appname.appspot.com");

            //intent.setData(Uri.fromFile(file));   
            startActivity(intent);
            //   finish();
            // setResult(RESULT_CANCELED);
            //finish();
        }
    });

    EditText titleEdit = (EditText) findViewById(R.id.submitTitle);
    titleEdit.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable arg0) {
            enableSubmitIfReady();
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });
    EditText descriptionEdit = (EditText) findViewById(R.id.submitDescription);
    descriptionEdit.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable arg0) {
            enableSubmitIfReady();
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    Cursor cursor = this.managedQuery(this.videoUri, null, null, null, null);

    if (cursor.getCount() == 0) {
        Log.d(LOG_TAG, "not a valid video uri");
        Toast.makeText(SubmitActivity.this, "not a valid video uri", Toast.LENGTH_LONG).show();
    } else {
        getVideoLocation();

        if (cursor.moveToFirst()) {

            long id = cursor.getLong(cursor.getColumnIndex(Video.VideoColumns._ID));
            this.dateTaken = new Date(cursor.getLong(cursor.getColumnIndex(Video.VideoColumns.DATE_TAKEN)));
            Log.v("here", "here12");
            SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm aaa");
            Configuration userConfig = new Configuration();
            Settings.System.getConfiguration(getContentResolver(), userConfig);
            /* Calendar cal = Calendar.getInstance(userConfig.locale);
             TimeZone tz = cal.getTimeZone();*/
            Log.v("here", "here13");

            // dateFormat.setTimeZone(tz);

            TextView dateTakenView = (TextView) findViewById(R.id.dateCaptured);
            dateTakenView.setText("Date captured: " + dateFormat.format(dateTaken));

            ImageView thumbnail = (ImageView) findViewById(R.id.thumbnail);
            ContentResolver crThumb = getContentResolver();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 1;
            Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(crThumb, id,
                    MediaStore.Video.Thumbnails.MICRO_KIND, options);
            thumbnail.setImageBitmap(curThumb);
        }
    }
}

From source file:net.freifunk.android.discover.Main.java

void updateMaps() {
    final String URL = "https://raw.githubusercontent.com/NiJen/AndroidFreifunkNord/master/MapUrls.json";

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    final ConnectivityManager connManager = (ConnectivityManager) getSystemService(
            this.getBaseContext().CONNECTIVITY_SERVICE);
    final NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    MapMaster mapMaster = MapMaster.getInstance();
    final DatabaseHelper databaseHelper = DatabaseHelper.getInstance(this.getApplicationContext());
    final RequestQueueHelper requestHelper = RequestQueueHelper.getInstance(this.getApplicationContext());

    final HashMap<String, NodeMap> mapList = databaseHelper.getAllNodeMaps();

    final boolean sync_wifi = sharedPrefs.getBoolean("sync_wifi", true);
    final int sync_frequency = Integer.parseInt(sharedPrefs.getString("sync_frequency", "0"));

    if (sync_wifi == true) {
        Log.d(TAG, "Performing online update ONLY via wifi, every " + sync_frequency + " minutes");
    } else {//w  w  w. j a  va  2s  .  c o  m
        Log.d(TAG, "Performing online update ALWAYS, every " + sync_frequency + " minutes");
    }

    updateTask = new TimerTask() {
        @Override
        public void run() {
            /* load from database */
            for (NodeMap map : mapList.values()) {
                map.loadNodes();
            }

            /* load from web */
            if (connManager.getActiveNetworkInfo() != null
                    && (sync_wifi == false || mWifi.isConnected() == true)) {
                Log.d(TAG, "Performing online update. Next update at " + scheduledExecutionTime());
                requestHelper.add(new JsonObjectRequest(URL, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            MapMaster mapMaster = MapMaster.getInstance();

                            Iterator mapkeys = jsonObject.keys();
                            while (mapkeys.hasNext()) {
                                String mapName = mapkeys.next().toString();
                                String mapUrl = jsonObject.getString(mapName);

                                NodeMap m = new NodeMap(mapName, mapUrl);
                                databaseHelper.addNodeMap(m);

                                // only update, if not already found in database
                                if (!mapList.containsKey(m.getMapName())) {
                                    m.loadNodes();
                                }
                            }
                        } catch (JSONException e) {
                            Log.e(TAG, e.toString());
                        } finally {
                            requestHelper.RequestDone();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e(TAG, volleyError.toString());
                        requestHelper.RequestDone();
                    }
                }));
            } else {
                Log.d(TAG, "Online update is skipped. Next try at " + scheduledExecutionTime());
            }
        }
    };

    Timer timer = new Timer();

    if (sync_frequency > 0) {
        timer.schedule(updateTask, 0, (sync_frequency * 60 * 1000));
    } else {
        timer.schedule(updateTask, 0);
    }

}

From source file:com.moez.QKSMS.mmssms.Transaction.java

private void sendMMS(final byte[] bytesToSend) {
    revokeWifi(true);//from   www . j  a v  a  2  s.c om

    // enable mms connection to mobile data
    mConnMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    int result = beginMmsConnectivity();

    if (LOCAL_LOGV)
        Log.v(TAG, "result of connectivity: " + result + " ");

    if (result != 0) {
        // if mms feature is not already running (most likely isn't...) then register a receiver and wait for it to be active
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        final BroadcastReceiver receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context1, Intent intent) {
                String action = intent.getAction();

                if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                    return;
                }

                @SuppressWarnings("deprecation")
                NetworkInfo mNetworkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

                if ((mNetworkInfo == null) || (mNetworkInfo.getType() != ConnectivityManager.TYPE_MOBILE)) {
                    return;
                }

                if (!mNetworkInfo.isConnected()) {
                    return;
                } else {
                    // ready to send the message now
                    if (LOCAL_LOGV)
                        Log.v(TAG, "sending through broadcast receiver");
                    alreadySending = true;
                    sendData(bytesToSend);

                    context.unregisterReceiver(this);
                }

            }

        };

        context.registerReceiver(receiver, filter);

        try {
            Looper.prepare();
        } catch (Exception e) {
            // Already on UI thread probably
        }

        // try sending after 3 seconds anyways if for some reason the receiver doesn't work
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!alreadySending) {
                    try {
                        if (LOCAL_LOGV)
                            Log.v(TAG, "sending through handler");
                        context.unregisterReceiver(receiver);
                    } catch (Exception e) {

                    }

                    sendData(bytesToSend);
                }
            }
        }, 7000);
    } else {
        // mms connection already active, so send the message
        if (LOCAL_LOGV)
            Log.v(TAG, "sending right away, already ready");
        sendData(bytesToSend);
    }
}

From source file:au.org.intersect.faims.android.ui.activity.ShowModuleActivity.java

private void setupWifiBroadcast() {
    broadcastReceiver = new WifiBroadcastReceiver(ShowModuleActivity.this);

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
    registerReceiver(broadcastReceiver, intentFilter);

    ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    // initialize wifi connection state
    if (mWifi != null && mWifi.isConnected()) {
        wifiConnected = true;/*ww  w . j  a v a 2 s .c o  m*/
    }
}

From source file:com.halseyburgund.rwframework.core.RWService.java

/**
 * Checks if data connectivity is available, honoring the flag 
 * mOnlyConnectOverWifi to accept only WiFi and not mobile data
 * connections.//  w w w  .j  av  a2s  .  c  o m
 * 
 * @return true if data connectivity is available
 */
public boolean isConnected() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    if ((ni != null) && (ni.isConnected())) {
        if ((mOnlyConnectOverWiFi) && (!(ni.getType() == ConnectivityManager.TYPE_WIFI))) {
            return false;
        }
        return true;
    }
    return false;
}

From source file:com.droid.app.fotobot.FotoBot.java

/**
 * isOnline - Check if there is a NetworkConnection
 *
 * @return boolean/* w  w w  .j  a  v  a2  s. c o m*/
 */
public boolean isOnline() {

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

    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    fbpause(h, 3);

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

}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

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

From source file:com.t2.dataouthandler.DataOutHandler.java

/**
 * @return true if network is available//from w  ww .jav a  2  s. c  om
 */
private boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    // if no network is available networkInfo will be null
    // otherwise check if we are connected
    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    }
    return false;
}

From source file:com.dwdesign.tweetings.util.Utils.java

public static boolean isOnWifi(final Context context) {
    if (context == null)
        return false;
    final ConnectivityManager conn = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo networkInfo = conn.getActiveNetworkInfo();

    return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI
            && networkInfo.isConnected();
}