private boolean isNetworkAvailable() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); return isConnected; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_history); listView = (ListView) findViewById(android.R.id.list); Intent intent = getIntent(); String stringUrl = urlText; ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { new DownloadFilesTask().execute(stringUrl); } else { Log.v("info", "network ocnnection unaavailable"); // textView.setText("No network connection available."); } // Bundle extras = intent.getExtras(); // this.historyArray = new ArrayList<QuestionResponseModel>(); // if(null!=intent) { // this.historyArray = // (ArrayList<QuestionResponseModel>)intent.getSerializableExtra("historyArray"); // } // historyArray. // Log.v("testing", "thisishistoyarray"+historyArray.size()); // adapter = new HistoryAdapter(this, android.R.layout.simple_list_item_2, qrArray); // listView.setAdapter(adapter); }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main12); ConnectivityManager cManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE); NetworkInfo ninfo = cManager.getActiveNetworkInfo(); if (ninfo != null && ninfo.isConnected()) { } else { AlertDialog.Builder builder1 = new AlertDialog.Builder(this); builder1.setMessage("Sorry There is no internet please check your connection!"); builder1.setCancelable(true); builder1.setPositiveButton( "I Will!", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert11 = builder1.create(); alert11.show(); } itemlist = new ArrayList<RSSItem>(); new RetrieveRSSFeeds().execute(); }
/** * Used to check for a data connection. Will alert the user if connection is unavailable. * * @param _context Context * @return boolean to show if a data connection is available. */ public boolean checkInternet(final Context _context) { // Create the ConnectivityManager and check for active network ConnectivityManager cm = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { // Connection is good return true; } else { // No connection, alert the user and return a false. new AlertDialog.Builder(_context) .setTitle("No Internet") .setMessage( "Internet connectivity is unavailable, please enable your internet connection and try again.") .setPositiveButton( android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) {} }) .setIcon(android.R.drawable.ic_dialog_alert) .show(); return false; } }
private void refresh() { ConnectivityManager cM = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo infos = cM.getActiveNetworkInfo(); if (infos != null && infos.isAvailable() && infos.isConnected()) { for (int i = 0; i < tab.size(); i++) { new WeatherAccessDataAsync(this) .execute("DAYS", this.tab.get(i), "com.intent.action.ALLRECEIVE"); new WeatherAccessDataAsync(this) .execute("ACTU", this.tab.get(i), "com.intent.action.ALLRECEIVE"); new WeatherAccessDataAsync(this) .execute("DETAILS", this.tab.get(i), "com.intent.action.ALLRECEIVE"); } } else { Intent intent; for (int i = 0; i < this.tab.size(); i++) { intent = new Intent("com.intent.action.ALLRECEIVE"); intent.putExtra("town", this.tab.get(i)); intent.putExtra("type", "DAYS"); sendBroadcast(intent); intent.putExtra("type", "ACTU"); sendBroadcast(intent); intent.putExtra("type", "DETAILS"); sendBroadcast(intent); } Toast.makeText( this, "Si vous souhaitez actualiser les données, veuillez vous connecter a un reseau internet.", Toast.LENGTH_SHORT) .show(); } }
private void checkNetworkState(Context context) { Log.d(TAG, "************** CheckNetwork ************"); ConnectivityManager cmng = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo wifiNetInfo = cmng.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (wifiNetInfo.isConnected()) { Log.i(TAG, "wifi enable"); setWifiEnable(true); setNetWorkEnable(true); startSync(SyncMode.ALL); } else { setWifiEnable(false); NetworkInfo activeNetInfo = cmng.getActiveNetworkInfo(); if (activeNetInfo != null) { setNetWorkEnable(true); if (isWifiOnly()) { stopSynchronize(); Log.i(TAG, "has network not wifi, not startSync"); } else { Log.i(TAG, "has network not wifi, startSync"); startSync(SyncMode.ALL); } } else { setNetWorkEnable(false); stopSynchronize(); } } }
@Override public void onCreate() { Utils.logger("d", "service created", DEBUG_TAG); BugSenseHandler.initAndStartSession(this, YTD.BugsenseApiKey); BugSenseHandler.leaveBreadcrumb("AutoUpgradeApkService_onCreate"); registerReceiver(apkReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); try { currentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName; Utils.logger("d", "current version: " + currentVersion, DEBUG_TAG); } catch (NameNotFoundException e) { Log.e(DEBUG_TAG, "version not read: " + e.getMessage()); currentVersion = "100"; } ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected() && matchedVersion != "n.a.") { try { // init version and changelog matchedChangeLog = null; matchedVersion = null; asyncAutoUpdate = new AsyncUpdate(); webPage = "http://sourceforge.net/projects/ytdownloader/files/"; asyncAutoUpdate.execute(webPage); } catch (NullPointerException e) { Log.e(DEBUG_TAG, "unable to retrieve update data."); } } else { Log.e(DEBUG_TAG, getString(R.string.no_net)); } }
public synchronized ApnWrapper getCurrApn() { if (mSDKVersion >= VersionUtils.Android_SDK_4_2) { return null; } NetworkInfo nInfo = mCm.getActiveNetworkInfo(); if (nInfo == null || nInfo.getType() != ConnectivityManager.TYPE_MOBILE) return null; if (mApnWrapper != null) return mApnWrapper; if (mCursor == null) { ini(); } if (mCursor != null && mCursor.moveToFirst()) { ApnWrapper aw = new ApnWrapper(); aw.apn = mCursor.getString(mCursor.getColumnIndex("apn")); aw.name = mCursor.getString(mCursor.getColumnIndex("name")); String port = mCursor.getString(mCursor.getColumnIndex("port")); try { aw.port = Integer.parseInt(port); } catch (NumberFormatException e) { aw.port = Proxy.getDefaultPort(); // e.printStackTrace(); } aw.proxy = mCursor.getString(mCursor.getColumnIndex("proxy")); mApnWrapper = aw; return aw; } return null; }
/** @return true is device is in roaming */ public boolean isInRoaming() { NetworkInfo networkInfo = mCnxManager.getActiveNetworkInfo(); if (networkInfo != null) { return networkInfo.isRoaming(); } return false; }
public void uploadToServer() { Log.d(TAG, "Connecting to " + stringUrl); try { ConnectivityManager connMgr = (ConnectivityManager) mSoftKeyboard.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { Log.d(TAG, networkInfo.getTypeName()); Log.d(TAG, networkInfo.getSubtypeName()); Log.d(TAG, networkInfo.toString()); Log.d(TAG, "Apparently nw is available"); new SendStatsTask().execute(stringUrl); } else { Log.d(TAG, "No network connection available."); connMgr.setNetworkPreference(ConnectivityManager.TYPE_MOBILE); if (connMgr.getActiveNetworkInfo().isConnected()) { Log.d(TAG, "Using mobile data"); new SendStatsTask().execute(stringUrl); } Log.d(TAG, "No go for mobile data either"); } } catch (Exception e) { Log.d(TAG, e.getMessage()); } // if successful delete local data }
@Override public void run() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if ((networkInfo == null) || (!networkInfo.isConnected()) || (networkInfo.getType() != ConnectivityManager.TYPE_WIFI)) { bundle.putInt( Constants.SERVER_THREAD_STATUS, Constants.SERVER_THREAD_STATUS_WIFI_NOT_CONNECTED); msg.setData(bundle); MainActivity.this.serverThreadMessageHandler.sendMessage(msg); return; } WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress(); String ip = (ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "." + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff); try { serverSocket = new ServerSocket(Constants.SERVER_PORT); bundle.putInt(Constants.SERVER_THREAD_STATUS, Constants.SERVER_THREAD_STATUS_LISTENING); bundle.putString(Constants.IP_ADDRESS, ip); msg.setData(bundle); MainActivity.this.serverThreadMessageHandler.sendMessage(msg); } catch (Exception e) { bundle.putInt(Constants.SERVER_THREAD_STATUS, Constants.SERVER_THREAD_STATUS_INIT_FAILED); msg.setData(bundle); MainActivity.this.serverThreadMessageHandler.sendMessage(msg); return; } Socket clientSocket; while (true) { try { clientSocket = serverSocket.accept(); String hostAddress = clientSocket.getInetAddress().getHostAddress(); boolean inClients = false; for (Client client : clients) if (client.host.equals(hostAddress)) { inClients = true; break; } if (!inClients) { Client newClient = new Client(hostAddress); clients.add(newClient); newClient.connect(); } Server server = new Server(clientSocket, hostAddress); servers.add(server); server.start(); } catch (Exception e) { } } }
public static HttpURLConnection getConnection(String urlStr) throws IOException { URL url = new URL(urlStr); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); if (null == activeNetworkInfo) { Log.w(TAG, "No active network available!"); return null; } Proxy p = getProxy(); String extra = activeNetworkInfo.getExtraInfo(); // chinese mobile network if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE && p != null) { // cmwap, uniwap, 3gwap if (extra != null && (extra.startsWith("cmwap") || extra.startsWith("uniwap") || extra.startsWith("3gwap"))) { HttpURLConnection conn = (HttpURLConnection) new URL("http://" + p.address().toString() + url.getPath()).openConnection(); conn.setRequestProperty( "X-Online-Host", url.getHost() + ":" + (url.getPort() == -1 ? "80" : url.getPort())); return conn; } } if (null != p) { // through proxy return (HttpURLConnection) url.openConnection(p); } else { return (HttpURLConnection) url.openConnection(); } }
public static boolean isWIFI() { ConnectivityManager cm = (ConnectivityManager) MyApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); return netInfo.getType() == ConnectivityManager.TYPE_WIFI; }
/** * 网络是否手机网络连接 * * @param context * @return */ public static boolean isOnlyMobileType(Context context) { State wifiState = null; State mobileState = null; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = null; try { networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI); } catch (Exception e) { e.printStackTrace(); } if (networkInfo != null) { wifiState = networkInfo.getState(); } try { networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); } catch (Exception e) { e.printStackTrace(); } if (networkInfo != null) { mobileState = networkInfo.getState(); } LogS.d("zhang", "onReceive -- wifiState = " + wifiState + " -- mobileState = " + mobileState); if (wifiState != null && mobileState != null && State.CONNECTED != wifiState && State.CONNECTED == mobileState) { // 手机网络连接成功 LogS.d("zhang", "onReceive -- 手机网络连接成功"); return true; } return false; }
public static boolean isOnlineOnMobile(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return (activeNetwork != null && activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE); }
static String getNetworkType(TelephonyManager paramTelephonyManager) { try { if (Localytics.appContext .getPackageManager() .checkPermission( "android.permission.ACCESS_WIFI_STATE", Localytics.appContext.getPackageName()) == 0) { NetworkInfo localNetworkInfo = ((ConnectivityManager) Localytics.appContext.getSystemService("connectivity")) .getNetworkInfo(1); if (localNetworkInfo != null) { boolean bool = localNetworkInfo.isConnectedOrConnecting(); if (bool) { return "wifi"; } } } else { Localytics.Log.w( "Application does not have one more more of the following permissions: ACCESS_WIFI_STATE. Determining Wi-Fi connectivity is unavailable"); } } catch (SecurityException localSecurityException) { Localytics.Log.w( "Application does not have the permission ACCESS_NETWORK_STATE. Determining Wi-Fi connectivity is unavailable", localSecurityException); } return "android_network_type_" + paramTelephonyManager.getNetworkType(); }
@Override public void onReceive(final Context context, final Intent intent) { if (intent.getAction() != null && intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) schuduleAlarm(context, intent); if (intent.getAction() != null && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { Log.d("KeepAliveReceiver", "ConnectivityReceiver invoked..."); boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); if (!noConnectivity) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); // only when connected or while connecting... if (netInfo != null && netInfo.isConnectedOrConnecting()) { Log.d("KeepAliveReceiver", "We have internet, start update check and disable receiver!"); // Start service with wakelock by using WakefulIntentService Intent backgroundIntent = new Intent(context, BackgroundService.class); WakefulIntentService.sendWakefulWork(context, backgroundIntent); // disable receiver after we started the service disableReceiver(context); } } } }
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); Log.d("net", "getTypeName = " + ni.getTypeName()); int pre = cm.getNetworkPreference(); Log.d("net", "getNetworkPreference = " + pre); cm.setNetworkPreference(ConnectivityManager.TYPE_MOBILE); // cm.setNetworkPreference(ConnectivityManager.TYPE_WIFI); Log.d("net", "getNetworkPreference = " + pre); boolean valid = ConnectivityManager.isNetworkTypeValid(ConnectivityManager.TYPE_MOBILE); Log.d("net", "TYPE_MOBILE isNetworkTypeValid = " + valid); valid = ConnectivityManager.isNetworkTypeValid(ConnectivityManager.TYPE_WIMAX); Log.d("net", "TYPE_WIMAX isNetworkTypeValid = " + valid); }
public boolean isConnected() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) return true; else return false; }
/** * 取得URL * * @param context * @param getRequest * @return request URL */ public String getRequestUrl(Context context, HttpPost getRequest) { final StringBuilder urlBuilder = new StringBuilder(); ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkinfo = connManager.getActiveNetworkInfo(); String extraInfo = null; if (networkinfo != null) { extraInfo = networkinfo.getExtraInfo(); } if (extraInfo != null && (extraInfo.equals(CMWAP) || extraInfo.equals(CTWAP) || extraInfo.equals(UNIWAP) || extraInfo.equals(GWAP))) { urlBuilder.append(X_OFFLINE_HOST); isWapState = true; } else { urlBuilder.append(SCHEME); urlBuilder.append(getRequest.getURI().getHost()); int port = getRequest.getURI().getPort(); if (port != -1) { urlBuilder.append(PORT_TOKEN); urlBuilder.append(port); } } urlBuilder.append(getRequest.getURI().getPath()); final String query = getRequest.getURI().getQuery(); if (!TextUtils.isEmpty(query)) { urlBuilder.append("?"); urlBuilder.append(query); } return urlBuilder.toString(); }
// Check for network status public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { return true; } // Instantiate an AlertDialog.Builder with its constructor for the Add item button AlertDialog.Builder builder = new AlertDialog.Builder(this); // 2. Chain together various setter methods to set the dialog characteristics builder .setMessage(R.string.no_net_info) .setTitle(R.string.no_net) .setNegativeButton( R.string.close_add, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); // Create the AlertDialog AlertDialog dialog = builder.create(); dialog.show(); return false; }
@Before public void setup() { MockitoAnnotations.initMocks(this); when(connected.isConnected()).thenReturn(true); when(disconnected.isConnected()).thenReturn(false); network = new NetworkMonitor(Robolectric.application); }
private boolean checkUplink() { Log.v(TAG, "Dentro CheckupLink()"); if (!app.prefs.getBoolean("wan_start", false)) { // se la wan è disabilitata niente check Log.v(TAG, "Dentro CheckupLink(), WanStart False"); return true; } if (app.prefs.getBoolean("wan_nowait", false)) { Log.v(TAG, "Dentro CheckupLink(), Wan_NoWait True"); return true; } // NetworkInfo mobileInfo =connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); NetworkInfo wimaxInfo = connManager.getNetworkInfo(6); Log.v(TAG, "Dentro CheckupLink(), prima del return"); // Cerco se esiste una interfaccia UMTS NetworkInfo[] info = connManager.getAllNetworkInfo(); boolean umts = false; if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getType() == connManager.TYPE_MOBILE) { // log(true, "Hspa interface "+info[i].getSubtypeName()+" found"); if (info[i].getState() == NetworkInfo.State.CONNECTED) umts = true; } } } return (umts || ((wimaxInfo != null) && wimaxInfo.isConnected())); }
@Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.detect_start_localize_button: ConnectivityManager cm = (ConnectivityManager) this.getApplicationContext().getSystemService(CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); if (networkInfo == null || !networkInfo.isConnected()) { myHandler.post(new FailConnectInternet()); return; } if (((String) listTypeSpinner.getSelectedItem()).equals("GPS")) { LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Toast.makeText(getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT).show(); return; } } startLocalizeButton.setEnabled(false); startLocalizeButton.setFocusable(false); stopLocalizeButton.setEnabled(true); stopLocalizeButton.setFocusable(true); listTypeSpinner.setEnabled(false); listTypeSpinner.setFocusable(false); countInt = 0; if (((String) listTypeSpinner.getSelectedItem()).equals("WIFI")) { wifiDetector.setConvert(convertCheckbox.isChecked()); wifiDetector.startDetectLocation(); } else { gpsDetector.startDetectLocation(); } break; case R.id.detect_stop_localize_button: startLocalizeButton.setEnabled(true); startLocalizeButton.setFocusable(true); stopLocalizeButton.setEnabled(false); stopLocalizeButton.setFocusable(false); listTypeSpinner.setEnabled(true); listTypeSpinner.setFocusable(true); if (((String) listTypeSpinner.getSelectedItem()).equals("WIFI")) { wifiDetector.stopDectectLocation(); } else { gpsDetector.stopDectectLocation(); } break; default: break; } }
/** do not use frequently */ public boolean isConnectState() { ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) return true; return false; }
// Source: // http://stackoverflow.com/questions/4238921/detect-whether-there-is-an-internet-connection-available-on-android // User: Alexandre Jasmin // Changes: getActivity().getApplicationContext() to access getSystemService public static boolean isNetworkAvailable(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); }
@Override public void onReceive(Context context, Intent intent) { // make sure sd card is ready, if not don't try to send if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return; } String action = intent.getAction(); ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo currentNetworkInfo = manager.getActiveNetworkInfo(); if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { if (currentNetworkInfo != null && currentNetworkInfo.getState() == NetworkInfo.State.CONNECTED) { if (interfaceIsEnabled(context, currentNetworkInfo)) { uploadForms(context); } } } else if (action.equals("com.geoodk.collect.android.FormSaved")) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = connectivityManager.getActiveNetworkInfo(); if (ni == null || !ni.isConnected()) { // not connected, do nothing } else { if (interfaceIsEnabled(context, ni)) { uploadForms(context); } } } }
public boolean check_connect_status() { try { // Message ma=main_thread_handler.obtainMessage(1,"try!"); // main_thread_handler.sendMessage(ma); ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo network_info = cm.getActiveNetworkInfo(); if (network_info == null || network_info.isConnected() == false) { // Toast.makeText(this, "網路狀態:關閉", Toast.LENGTH_SHORT).show(); Message m = main_thread_handler.obtainMessage(4, "請開啟網路"); main_thread_handler.sendMessage(m); return false; } else { // Toast.makeText(this, "網路狀態:開啟", Toast.LENGTH_SHORT).show(); } if (connect_to_server("/project/mobilephone/check_connect.php", null).equals("1")) { // Toast.makeText(this, "可連接至主機", Toast.LENGTH_SHORT).show(); return true; } else { // Toast.makeText(this, "not connect", Toast.LENGTH_SHORT).show(); return false; } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { Message m = main_thread_handler.obtainMessage(4, "無法連接至主機"); main_thread_handler.sendMessage(m); e.printStackTrace(); } return false; }
public static boolean isInternetAvailable(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return (activeNetwork != null && activeNetwork.isConnectedOrConnecting()); }
private boolean isConnected(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return (activeNetwork == null ? false : activeNetwork.isConnectedOrConnecting()); }