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 }
/** * get connected network type by {@link ConnectivityManager} * * <p>such as WIFI, MOBILE, ETHERNET, BLUETOOTH, etc. * * @return {@link ConnectivityManager#TYPE_WIFI}, {@link ConnectivityManager#TYPE_MOBILE}, {@link * ConnectivityManager#TYPE_ETHERNET}... */ public static int getConnectedTypeINT(Context context) { NetworkInfo net = getConnectivityManager(context).getActiveNetworkInfo(); if (net != null) { Log.i(TAG, "NetworkInfo: " + net.toString()); return net.getType(); } return -1; }
@Override public void onReceive(final Context context, Intent intent) { // When the Network connection changes, check if we're connected Bundle extras = intent.getExtras(); NetworkInfo info = extras.getParcelable("networkInfo"); NetworkInfo.State state = info.getState(); Log.d("NetworkReceiver", info.toString() + " " + state.toString()); // If so, upload if (state == NetworkInfo.State.CONNECTED) { new RemoteDatabaseHelper(context).checkConnectionAndUpload(); } }
@Override public void onReceive(Context context, Intent intent) { if (intent != null && WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) { NetworkInfo networkInfo = (NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); Log.d("trans", "-------------------" + networkInfo.toString()); if (networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { Log.d("trans", "-------------------------wifi --------------------"); Intent i = new Intent(context, MonitoringService.class); i.setAction(MonitoringService.SEND_DATA); context.startService(i); } } }