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.android.projectz.teamrocket.thebusapp.activities.SplashScreenActivity.java

/**
 * controlla se il dispositivo  connesso ad internet
 *
 * @return/*w ww .j  a  v a  2 s  .  com*/
 */
private boolean checkConnectionToInternet() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

From source file:com.teinproductions.tein.papyrosprogress.UpdateCheckReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    this.context = context;
    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);

    // Check Internet connection
    ConnectivityManager connManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
    if (networkInfo == null || !networkInfo.isConnected())
        return;//from w  w w . ja v  a2s  .co  m

    // Check if progress has to be checked
    boolean notifications = pref.getBoolean(Constants.NOTIFICATION_PREFERENCE, true);
    boolean appWidgets = AbstractProgressWidget.areAppWidgetsEnabled(context);
    if (notifications || appWidgets)
        checkProgress();

    // Check if blog has to be checked
    boolean extra = intent.getBooleanExtra(CHECK_BLOGS_EXTRA, true);
    if (extra && notifications)
        checkBlog();
}

From source file:com.polyvi.xface.extension.XNetworkConnectionExt.java

/**
 * ?./*from  ww  w .  ja  va 2s.c  o  m*/
 *
 * @param info   ??
 * @return       ? JSONObject
 */
private String getConnectionInfo(NetworkInfo info) {
    String type = TYPE_NONE;
    if (null != info) {
        // typenone
        if (!info.isConnected()) {
            type = TYPE_NONE;
        } else {
            type = getType(info);
        }
    }
    return type;
}

From source file:com.team1.soccerplayers.layout.PlayerInfoActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Check whether we're recreating a previously destroyed instance

    if (savedInstanceState != null) {
        // Restore value of members from saved state
        playerName = savedInstanceState.getString(STATE_PLAYER);

    } else {/*w  ww  .j  a  v  a2s.c  o  m*/

        // Probably initialize members with default values for a new instance
        setContentView(R.layout.activity_player_info);
        Intent intent = getIntent();
        playerName = intent.getStringExtra(DisplayFavoritePlayersActivity.EXTRA_MESSAGE);

    }
    if (playerName.contains(" ")) {
        firstName = playerName.split(" ");

    }

    if (playerName.contains(" ")) {
        APILink = "https://api.datamarket.azure.com/Bing/Search/v1/News?Query=%27" + firstName[0].trim() + "%20"
                + firstName[1].trim() + "%20%27&$format=json";
    } else {
        APILink = "https://api.datamarket.azure.com/Bing/Search/v1/News?Query=%27" + playerName
                + "%20%27&$format=json";
    }
    //Toast.makeText(PlayerInfoActivity.this, "resrult: " + playerName, Toast.LENGTH_SHORT).show();

    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        DownloadTask downloadTask = new DownloadTask();
        downloadTask.execute();
    } else {
        Toast.makeText(PlayerInfoActivity.this, "Unable to Connect to the server, Please try later.",
                Toast.LENGTH_SHORT).show();
    }

    infoListView = (ListView) findViewById(android.R.id.list);

    final TextView title1 = new TextView(this);
    final TextView summary1 = new TextView(this);
    infoListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            HashMap<String, String> map = (HashMap<String, String>) infoListView.getItemAtPosition(position);
            page = map.get("Url");
            int fadedTitleColor = getResources().getColor(R.color.marked_as_read_title_text);
            int fadedSummaryColor = getResources().getColor(R.color.marked_as_read_summary_text);

            profileView(view);
        }
    });

}

From source file:edu.mit.mobile.android.net.DownloadLoader.java

@Override
public Uri loadInBackground() {
    boolean alreadyHasDownload = false;

    if (!outdir.exists() && !outdir.mkdirs()) {
        mException = new IOException("could not mkdirs: " + outdir.getAbsolutePath());
        return null;
    }//  w  w w .  ja v a 2  s. c  o  m
    final String fname = mUrl.substring(mUrl.lastIndexOf('/'));
    final File outfile = new File(outdir, fname);

    alreadyHasDownload = outfile.exists() && outfile.length() > MINIMUM_REASONABLE_VIDEO_SIZE;

    final long lastModified = outfile.exists() ? outfile.lastModified() : 0;

    try {
        final NetworkInfo netInfo = mCm.getActiveNetworkInfo();
        if (netInfo == null || !netInfo.isConnected()) {
            // no connection, but there's already a file. Hopefully it works!
            if (alreadyHasDownload) {
                return Uri.fromFile(outfile);
            } else {
                mException = new IOException(getContext().getString(R.string.err_no_data_connection));
                return null;
            }
        }

        HttpURLConnection hc = (HttpURLConnection) new URL(mUrl).openConnection();

        hc.setInstanceFollowRedirects(true);

        if (lastModified != 0) {
            hc.setIfModifiedSince(lastModified);
        }

        int resp = hc.getResponseCode();

        if (resp >= 300 && resp < 400) {

            final String redirectUrl = hc.getURL().toExternalForm();

            if (BuildConfig.DEBUG) {
                Log.d(TAG, "following redirect to " + redirectUrl);
            }
            hc = (HttpURLConnection) new URL(redirectUrl).openConnection();

            if (lastModified != 0) {
                hc.setIfModifiedSince(lastModified);
            }
            resp = hc.getResponseCode();
        }

        if (resp != HttpStatus.SC_OK && resp != HttpStatus.SC_NOT_MODIFIED) {
            Log.e(TAG, "got a non-200 response from server");
            mException = new NetworkProtocolException("Received " + resp + " response from server");
            return null;
        }
        if (resp == HttpStatus.SC_NOT_MODIFIED) {
            if (Constants.DEBUG) {
                Log.d(TAG, "got NOT MODIFIED");
            }
            // verify the integrity of the file
            if (alreadyHasDownload) {
                if (Constants.DEBUG) {
                    Log.d(TAG, fname + " has not been modified since it was downloaded last");
                }
                return Uri.fromFile(outfile);
            } else {
                // re-request without the if-modified header. This shouldn't happen.
                hc = (HttpURLConnection) new URL(mUrl).openConnection();
                final int responseCode = hc.getResponseCode();
                if (responseCode != HttpStatus.SC_OK) {
                    Log.e(TAG, "got a non-200 response from server");
                    mException = new NetworkProtocolException(
                            "Received " + responseCode + " response from server");
                    return null;
                }
            }
        }

        final int contentLength = hc.getContentLength();

        if (contentLength == 0) {
            Log.e(TAG, "got an empty response from server");
            mException = new IOException("Received an empty response from server.");
            return null;

        } else if (contentLength < MINIMUM_REASONABLE_VIDEO_SIZE) { // this is probably not a
                                                                    // video
            Log.e(TAG, "got a very small response from server of length " + hc.getContentLength());
            mException = new IOException("Received an unusually-small response from server.");
            return null;
        }
        boolean downloadSucceeded = false;
        try {

            final BufferedInputStream bis = new BufferedInputStream(hc.getInputStream());
            final FileOutputStream fos = new FileOutputStream(outfile);
            if (Constants.DEBUG) {
                Log.d(TAG, "downloading...");
            }
            StreamUtils.inputStreamToOutputStream(bis, fos);

            fos.close();

            // store the server's last modified date in the filesystem
            outfile.setLastModified(hc.getLastModified());

            downloadSucceeded = true;
            if (Constants.DEBUG) {
                Log.d(TAG, "done! Saved to " + outfile);
            }
            return Uri.fromFile(outfile);

        } finally {
            hc.disconnect();
            // cleanup if this is the first attempt to download
            if (!alreadyHasDownload && !downloadSucceeded) {
                outfile.delete();
            }
        }
    } catch (final IOException e) {
        Log.e(TAG, "error downloading file", e);
        mException = e;
        return null;
    }
}

From source file:ca.shoaib.ping.PingListFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_ping_list, container, false);

    mListView = (ListView) rootView.findViewById(R.id.list_ping);

    pingListAdapter = new PingListAdapter(getActivity(), R.layout.ping_row, pingList);
    mListView.setAdapter(pingListAdapter);
    //mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override//from   w w  w .  j av a 2  s . c om
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            mPingListCallback.onPingSelected(pingList.get(position));
            mActivatedPosition = position;
            setActivatedPosition(position);
            //Log.d(TAG, "ArtistId: " + artistList.get(position).getArtistId());
        }
    });

    pb = (ProgressBar) rootView.findViewById(R.id.progress_bar);
    et = (EditText) rootView.findViewById(R.id.ping_destination);
    tv = (TextView) rootView.findViewById(R.id.ping_result);
    btn = (Button) rootView.findViewById(R.id.ping_start);

    btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            String stringUrl = et.getText().toString();

            ConnectivityManager connMgr = (ConnectivityManager) getActivity()
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

            if (networkInfo != null && networkInfo.isConnected()) {
                AsyncTask pingTask = new PingTask(getActivity(), pingList, pingListAdapter).execute(stringUrl);

            } else {
                tv.setTextSize(20);
                tv.setTextColor(Color.RED);
                tv.setText(R.string.no_internet);
            }

            InputMethodManager inputManager = (InputMethodManager) getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);

            inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                    InputMethodManager.RESULT_UNCHANGED_SHOWN);
        }
    });

    et.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            final int DRAWABLE_LEFT = 0;
            final int DRAWABLE_TOP = 1;
            final int DRAWABLE_RIGHT = 2;
            final int DRAWABLE_BOTTOM = 3;

            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (event.getRawX() >= (et.getRight()
                        - et.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
                    et.setText("");
                    et.selectAll();

                    return true;
                }
            }
            return false;
        }
    });
    return rootView;
}

From source file:com.android.settings.cyanogenmod.LtoService.java

private boolean shouldDownload() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();

    if (info == null || !info.isConnected()) {
        if (ALOGV)
            Log.v(TAG, "No network connection is available for LTO download");
    } else {/*from w  ww .j  a  va 2s.c  o  m*/
        boolean wifiOnly = prefs.getBoolean(LocationSettings.KEY_GPS_DOWNLOAD_DATA_WIFI_ONLY, true);
        if (wifiOnly && info.getType() != ConnectivityManager.TYPE_WIFI) {
            if (ALOGV) {
                Log.v(TAG, "Active network is of type " + info.getTypeName() + ", but Wifi only was selected");
            }
            return false;
        }
    }

    long now = System.currentTimeMillis();
    long lastDownload = getLastDownload();
    long due = lastDownload + LongTermOrbits.getDownloadInterval();

    if (ALOGV) {
        Log.v(TAG, "Now " + now + " due " + due + "(" + new Date(due) + ")");
    }

    if (lastDownload != 0 && now < due) {
        if (ALOGV)
            Log.v(TAG, "LTO download is not due yet");
        return false;
    }

    return true;
}

From source file:com.iiitd.networking.UDPMessenger.java

/**
 * Sends a broadcast message (TAG EPOCH_TIME message). Opens a new socket in case it's closed.
 * @param message the message to send (multicast). It can't be null or 0-characters long.
 * @return//w  w w.j  ava2 s .c  o m
 * @throws IllegalArgumentException
 */
public boolean sendMessage(String message) throws IllegalArgumentException {
    if (message == null || message.length() == 0)
        throw new IllegalArgumentException();

    // Check for WiFi connectivity
    ConnectivityManager connManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (mWifi == null || !mWifi.isConnected()) {
        Log.d(DEBUG_TAG,
                "Sorry! You need to be in a WiFi network in order to send UDP multicast packets. Aborting.");
        return false;
    }

    // Check for IP address
    WifiManager wim = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int ip = wim.getConnectionInfo().getIpAddress();

    // Create the send socket
    if (socket == null) {
        try {
            socket = new DatagramSocket();
        } catch (SocketException e) {
            Log.d(DEBUG_TAG, "There was a problem creating the sending socket. Aborting.");
            e.printStackTrace();
            return false;
        }
    }

    // Build the packet
    DatagramPacket packet;
    Message msg = new Message(TAG, message);
    byte data[] = msg.toString().getBytes();

    WifiInfo wifiInfo = wim.getConnectionInfo();
    int ipa = wifiInfo.getIpAddress();
    String ipAddress = Formatter.formatIpAddress(ipa);

    try {
        //         packet = new DatagramPacket(data, data.length, InetAddress.getByName(ipToString(ip, true)), MULTICAST_PORT);
        packet = new DatagramPacket(data, data.length, InetAddress.getByName(ipAddress), MULTICAST_PORT);
    } catch (UnknownHostException e) {
        Log.d(DEBUG_TAG, "It seems that " + ipToString(ip, true) + " is not a valid ip! Aborting.");
        e.printStackTrace();
        return false;
    }

    try {
        socket.send(packet);
    } catch (IOException e) {
        Log.d(DEBUG_TAG, "There was an error sending the UDP packet. Aborted.");
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:com.example.yudiandrean.socioblood.Twitter.TwitterActivity.java

public void getTwitter() {
    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

    if (networkInfo != null && networkInfo.isConnected()) {
        new DownloadTwitterTask().execute(ScreenName);
    } else {/*w ww . ja  va 2  s. c  o  m*/
        Log.v(LOG_TAG, "No network connection available.");
    }
}

From source file:github.daneren2005.dsub.util.Util.java

public static boolean isWifiConnected(Context context) {
    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();
    boolean connected = networkInfo != null && networkInfo.isConnected();
    return connected && (networkInfo.getType() == ConnectivityManager.TYPE_WIFI);
}