Example usage for android.net NetworkInfo getType

List of usage examples for android.net NetworkInfo getType

Introduction

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

Prototype

@Deprecated
public int getType() 

Source Link

Document

Reports the type of network to which the info in this NetworkInfo pertains.

Usage

From source file:org.m2x.rssreader.service.FetcherService.java

@SuppressWarnings("deprecation")
@Override/*w w  w . j  av a 2  s . c o  m*/
public void onHandleIntent(Intent intent) {
    if (intent == null) {
        return;
    }

    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
    final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    // Connectivity issue, we quit
    if (networkInfo == null || networkInfo.getState() != NetworkInfo.State.CONNECTED) {
        broadcastNetworkProblem();
        return;
    }

    boolean isFromAutoRefresh = intent.getBooleanExtra(Constants.FROM_AUTO_REFRESH, false);
    boolean skipFetch = isFromAutoRefresh && PrefUtils.getBoolean(PrefUtils.AUTO_REFRESH_ONLY_ON_WIFI, false)
            && networkInfo.getType() != ConnectivityManager.TYPE_WIFI;
    // We need to skip the fetching process, so we quit
    if (skipFetch) {
        return;
    }

    if (ACTION_DOWNLOAD_IMAGES.equals(intent.getAction())) {
        downloadAllImages();
    } else { // == Constants.ACTION_REFRESH_FEEDS
        PrefUtils.putBoolean(PrefUtils.IS_REFRESHING, true);

        if (isFromAutoRefresh) {
            PrefUtils.putLong(PrefUtils.LAST_SCHEDULED_REFRESH, SystemClock.elapsedRealtime());
        }

        String feedId = intent.getStringExtra(Constants.FEED_ID);
        int newCount = (feedId == null ? refreshFeeds() : refreshFeed(feedId));

        if (newCount > 0) {
            if (PrefUtils.getBoolean(PrefUtils.PUSH_NOTIFICATION, true)) {
                Cursor cursor = getContentResolver().query(EntryColumns.CONTENT_URI, new String[] { COUNT },
                        EntryColumns.WHERE_UNREAD, null, null);

                cursor.moveToFirst();
                newCount = cursor.getInt(0); // The number has possibly changed
                cursor.close();

                if (newCount > 0) {
                    String text = getResources().getQuantityString(R.plurals.number_of_new_entries, newCount,
                            newCount);

                    Intent notificationIntent = new Intent(FetcherService.this, MainActivity.class);
                    PendingIntent contentIntent = PendingIntent.getActivity(FetcherService.this, 0,
                            notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

                    NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(
                            MainApplication.getContext()).setContentIntent(contentIntent)
                                    .setSmallIcon(R.drawable.ic_launcher)
                                    .setLargeIcon(BitmapFactory.decodeResource(getResources(),
                                            R.drawable.ic_launcher)) //
                                    .setTicker(text).setWhen(System.currentTimeMillis()).setAutoCancel(true)
                                    .setContentTitle(getString(R.string.rssreader_feeds)).setContentText(text)
                                    .setLights(0xffffffff, 300, 1000);

                    if (PrefUtils.getBoolean(PrefUtils.NOTIFICATIONS_VIBRATE, false)) {
                        notifBuilder.setVibrate(new long[] { 0, 1000 });
                    }

                    String ringtone = PrefUtils.getString(PrefUtils.NOTIFICATIONS_RINGTONE, null);
                    if (ringtone != null && ringtone.length() > 0) {
                        notifBuilder.setSound(Uri.parse(ringtone));
                    }

                    if (Constants.NOTIF_MGR != null) {
                        Constants.NOTIF_MGR.notify(0, notifBuilder.getNotification());
                    }
                }
            } else if (Constants.NOTIF_MGR != null) {
                Constants.NOTIF_MGR.cancel(0);
            }
        }

        downloadAllImages();

        PrefUtils.putBoolean(PrefUtils.IS_REFRESHING, false);
        broadcastRefreshFinished();
    }
}

From source file:com.snt.bt.recon.activities.MainActivity.java

public void syncServerDatabase() {
    //check for connectivity
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    //sync database
    if (isConnected) {
        boolean wifiOnly = sp.getBoolean("preferred_sync", false);
        boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
        if (!isWiFi && wifiOnly) {
            logDebug("syncServerDatabase",
                    "Phone isConnected - Not Synchronizing upon user request because connection is not WiFi");
        } else {//from  w ww .j  ava  2s  .c om
            logDebug("syncServerDatabase", "Phone isConnected - Synchronizing");

            syncSQLiteMySQLDB(Trip.class, "tripsJSON", "https://.../api/insert_trip.php");//TODO
            syncSQLiteMySQLDB(GPSLocation.class, "locationsJSON", "https://.../api/insert_locations.php");//TODO
            syncSQLiteMySQLDB(BluetoothClassicEntry.class, "bcJSON", "https://.../api/insert_bc.php");//TODO
            syncSQLiteMySQLDB(BluetoothLowEnergyEntry.class, "bleJSON", "https://.../api/insert_ble.php");//TODO
        }
    } else {
        logDebug("syncServerDatabase", "Phone isNotConnected");

    }
}

From source file:at.alladin.rmbt.android.util.InformationCollector.java

/** Returns the network that the phone is on (e.g. Wifi, Edge, GPRS, etc). */
public int getNetwork() {
    int result = TelephonyManager.NETWORK_TYPE_UNKNOWN;

    if (connManager != null) {
        final NetworkInfo activeNetworkInfo = connManager.getActiveNetworkInfo();
        if (activeNetworkInfo != null) {
            final int type = activeNetworkInfo.getType();
            switch (type) {
            case ConnectivityManager.TYPE_WIFI:
                result = NETWORK_WIFI;/*from  w  w w. j  av  a  2  s .c  o  m*/
                break;

            case ConnectivityManager.TYPE_BLUETOOTH:
                result = NETWORK_BLUETOOTH;
                break;

            case ConnectivityManager.TYPE_ETHERNET:
                result = NETWORK_ETHERNET;
                break;

            case ConnectivityManager.TYPE_MOBILE:
            case ConnectivityManager.TYPE_MOBILE_DUN:
            case ConnectivityManager.TYPE_MOBILE_HIPRI:
            case ConnectivityManager.TYPE_MOBILE_MMS:
            case ConnectivityManager.TYPE_MOBILE_SUPL:
                result = telManager.getNetworkType();
                break;
            }
        }
    }

    /* detect change from wifi to mobile or reverse */
    final int lastNetworkType = this.lastNetworkType.get();
    if (result != TelephonyManager.NETWORK_TYPE_UNKNOWN
            && lastNetworkType != TelephonyManager.NETWORK_TYPE_UNKNOWN) {
        if ((result == ConnectivityManager.TYPE_WIFI && lastNetworkType != ConnectivityManager.TYPE_WIFI)
                || (result != ConnectivityManager.TYPE_WIFI
                        && lastNetworkType == ConnectivityManager.TYPE_WIFI))
            illegalNetworkTypeChangeDetcted.set(true);
    }
    if (result != lastNetworkType) {
        this.lastNetworkType.set(result);
        if (telListener != null)
            telListener.onSignalStrengthsChanged(null);
    }

    return result;
}

From source file:com.android.providers.downloads.DownloadInfo.java

/**
 * Returns whether this download is allowed to use the network.
 *///from w w  w.ja  v a  2 s  .  c om
public NetworkState checkCanUseNetwork(long totalBytes) {
    final NetworkInfo info = mSystemFacade.getActiveNetworkInfo(mUid);
    if (info == null || !info.isConnected()) {
        return NetworkState.NO_CONNECTION;
    }
    if (DetailedState.BLOCKED.equals(info.getDetailedState())) {
        return NetworkState.BLOCKED;
    }
    if (mSystemFacade.isNetworkRoaming() && !isRoamingAllowed()) {
        return NetworkState.CANNOT_USE_ROAMING;
    }
    if (mSystemFacade.isActiveNetworkMetered() && !mAllowMetered) {
        return NetworkState.TYPE_DISALLOWED_BY_REQUESTOR;
    }
    return checkIsNetworkTypeAllowed(info.getType(), totalBytes);
}

From source file:org.openhab.habdroid.ui.OpenHABWidgetListActivity.java

/**
 * This is called when activity is created. Initializes the state, performs network
 * state based selection for app initialization and starts the widget list
 *///  w  w  w.j  a  va  2s . c o  m
@Override
public void onCreate(Bundle savedInstanceState) {
    Log.d("OpenHABWidgetListActivity", "onCreate");
    // Set default values, false means do it one time during the very first launch
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    // Set non-persistant HABDroid version preference to current version from application package
    try {
        PreferenceManager.getDefaultSharedPreferences(this).edit().putString("default_openhab_appversion",
                getPackageManager().getPackageInfo(getPackageName(), 0).versionName).commit();
    } catch (NameNotFoundException e1) {
        if (e1 != null)
            Log.d(TAG, e1.getMessage());
    }
    // Set the theme to one from preferences
    Util.setActivityTheme(this);
    // Fetch openHAB service type name from strings.xml
    openHABServiceType = getString(R.string.openhab_service_type);
    // Enable progress ring bar
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    requestWindowFeature(Window.FEATURE_PROGRESS);
    setProgressBarIndeterminateVisibility(true);
    // Initialize crittercism reporting
    JSONObject crittercismConfig = new JSONObject();
    try {
        crittercismConfig.put("shouldCollectLogcat", true);
    } catch (JSONException e) {
        if (e.getMessage() != null)
            Log.e(TAG, e.getMessage());
        else
            Log.e(TAG, "Crittercism JSON exception");
    }
    Crittercism.init(getApplicationContext(), "5117659f59e1bd4ba9000004", crittercismConfig);
    // Initialize activity view
    super.onCreate(savedInstanceState);
    setContentView(R.layout.openhabwidgetlist);
    // Disable screen timeout if set in preferences
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    if (settings.getBoolean("default_openhab_screentimeroff", false)) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
    // Check if we got all needed permissions
    PackageManager pm = getPackageManager();
    if (!(pm.checkPermission(permission.CHANGE_WIFI_MULTICAST_STATE,
            getPackageName()) == PackageManager.PERMISSION_GRANTED)) {
        showAlertDialog(getString(R.string.erorr_no_wifi_mcast_permission));
        serviceDiscoveryEnabled = false;
    }
    if (!(pm.checkPermission(permission.ACCESS_WIFI_STATE,
            getPackageName()) == PackageManager.PERMISSION_GRANTED)) {
        showAlertDialog(getString(R.string.erorr_no_wifi_state_permission));
        serviceDiscoveryEnabled = false;
    }
    // Get username/password from preferences
    openHABUsername = settings.getString("default_openhab_username", null);
    openHABPassword = settings.getString("default_openhab_password", null);
    // Create new data source and adapter and set it to list view
    openHABWidgetDataSource = new OpenHABWidgetDataSource();
    openHABWidgetAdapter = new OpenHABWidgetAdapter(OpenHABWidgetListActivity.this,
            R.layout.openhabwidgetlist_genericitem, widgetList);
    getListView().setAdapter(openHABWidgetAdapter);
    // Set adapter parameters
    openHABWidgetAdapter.setOpenHABUsername(openHABUsername);
    openHABWidgetAdapter.setOpenHABPassword(openHABPassword);
    // Enable app logo as home button
    this.getActionBar().setHomeButtonEnabled(true);
    // Check if we have openHAB page url in saved instance state?
    if (savedInstanceState != null) {
        displayPageUrl = savedInstanceState.getString("displayPageUrl");
        openHABBaseUrl = savedInstanceState.getString("openHABBaseUrl");
        sitemapRootUrl = savedInstanceState.getString("sitemapRootUrl");
        openHABWidgetAdapter.setOpenHABBaseUrl(openHABBaseUrl);
    }
    // Check if this is a launch from myself (drill down navigation)
    if (getIntent() != null) {
        if (getIntent().getAction() != null) {
            if (getIntent().getAction().equals("org.openhab.habdroid.ui.OpwnHABWidgetListActivity")) {
                displayPageUrl = getIntent().getExtras().getString("displayPageUrl");
                openHABBaseUrl = getIntent().getExtras().getString("openHABBaseUrl");
                sitemapRootUrl = getIntent().getExtras().getString("sitemapRootUrl");
                this.setTitle(getIntent().getExtras().getString("pageTitle"));
                openHABWidgetAdapter.setOpenHABBaseUrl(openHABBaseUrl);
            }
        }
    }
    // If yes, then just go to it (means restore activity from it's saved state)
    if (displayPageUrl.length() > 0) {
        Log.d(TAG, "displayPageUrl = " + displayPageUrl);
        showPage(displayPageUrl, false);
        // If not means it is a clean start
    } else {
        if (getIntent() != null) {
            Log.i(TAG, "Launch intent = " + getIntent().getAction());
            // If this is a launch through NFC tag reading
            if (getIntent().getAction() != null) {
                if (getIntent().getAction().equals("android.nfc.action.NDEF_DISCOVERED")) {
                    // Save url which we got from NFC tag
                    nfcTagData = getIntent().getDataString();
                }
            }
        }
        // If we are in demo mode, ignore all settings and use demo url from strings
        if (settings.getBoolean("default_openhab_demomode", false)) {
            openHABBaseUrl = getString(R.string.openhab_demo_url);
            Log.i(TAG, "Demo mode, connecting to " + openHABBaseUrl);
            Toast.makeText(getApplicationContext(), getString(R.string.info_demo_mode), Toast.LENGTH_LONG)
                    .show();
            showTime();
        } else {
            openHABBaseUrl = normalizeUrl(settings.getString("default_openhab_url", ""));
            // Check if we have a direct URL in preferences, if yes - use it
            if (openHABBaseUrl.length() > 0) {
                Log.i(TAG, "Connecting to configured URL = " + openHABBaseUrl);
                Toast.makeText(getApplicationContext(), getString(R.string.info_conn_url), Toast.LENGTH_SHORT)
                        .show();
                showTime();
            } else {
                // Get current network information
                ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
                        Context.CONNECTIVITY_SERVICE);
                NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
                if (activeNetworkInfo != null) {
                    Log.i(TAG, "Network is connected");
                    // If network is mobile, try to use remote URL
                    if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE
                            || serviceDiscoveryEnabled == false) {
                        if (!serviceDiscoveryEnabled) {
                            Log.i(TAG, "openHAB discovery is disabled");
                        } else {
                            Log.i(TAG, "Network is Mobile (" + activeNetworkInfo.getSubtypeName() + ")");
                        }
                        openHABBaseUrl = normalizeUrl(settings.getString("default_openhab_alturl", ""));
                        // If remote URL is configured
                        if (openHABBaseUrl.length() > 0) {
                            Toast.makeText(getApplicationContext(), getString(R.string.info_conn_rem_url),
                                    Toast.LENGTH_SHORT).show();
                            Log.i(TAG, "Connecting to remote URL " + openHABBaseUrl);
                            showTime();
                        } else {
                            Toast.makeText(getApplicationContext(), getString(R.string.error_no_url),
                                    Toast.LENGTH_LONG).show();
                        }
                        // If network is WiFi or Ethernet
                    }
                    if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI
                            || activeNetworkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
                        Log.i(TAG, "Network is WiFi or Ethernet");
                        // Start service discovery
                        this.serviceResolver = new AsyncServiceResolver(this, openHABServiceType);
                        progressDialog = ProgressDialog.show(this, "", "Discovering openHAB. Please wait...",
                                true);
                        this.serviceResolver.start();
                        // We don't know how to handle this network type
                    } else {
                        Log.i(TAG, "Network type (" + activeNetworkInfo.getTypeName() + ") is unsupported");
                    }
                    // Network is not available
                } else {
                    Log.i(TAG, "Network is not available");
                    Toast.makeText(getApplicationContext(), getString(R.string.error_network_not_available),
                            Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}

From source file:com.appsimobile.appsii.module.weather.WeatherLoadingService.java

private void syncImages(SyncResult result, ConnectivityManager cm, PreferenceHelper preferenceHelper,
        SimpleArrayMap<String, String> woeidTimezones, SimpleArrayMap<String, WeatherData> previousData,
        WeatherData weatherData) throws VolleyError {

    NetworkInfo netInfo;
    String woeid = weatherData.woeid;
    WeatherData previous = previousData.get(woeid);
    File[] photos = mWeatherUtils.getCityPhotos(mContext, woeid);

    boolean changed = photos == null || previous == null
            || previous.nowConditionCode != weatherData.nowConditionCode;

    if (changed) {

        boolean downloadEnabled = preferenceHelper.getUseFlickrImages();
        boolean downloadOnWifiOnly = preferenceHelper.getDownloadImagesOnWifiOnly();
        boolean downloadWhenRoaming = preferenceHelper.getDownloadWhenRoaming();

        netInfo = cm.getActiveNetworkInfo();
        if (netInfo == null)
            return;
        boolean wifi = netInfo.getType() == ConnectivityManager.TYPE_WIFI;
        boolean roaming = netInfo.isRoaming();

        // tell the sync we got an io exception
        // so it knows we would like to try again later
        if (roaming && !downloadWhenRoaming) {
            result.stats.numIoExceptions++;
            return;
        }/* w  w w.j  a v  a2  s  .co m*/

        // well, we are not on wifi, and the user
        // only wants to sync this when wifi
        // is enabled.
        if (!wifi && downloadOnWifiOnly) {
            result.stats.numIoExceptions++;
            return;
        }

        // only download when the user has the option
        // to download flickr images enabled in
        // settings
        if (downloadEnabled) {
            String timezone = woeidTimezones.get(woeid);
            downloadWeatherImages(mContext, mBitmapUtils, woeid, weatherData, timezone);
            result.stats.numInserts++;
        }
    }
}

From source file:fr.inria.ucn.collectors.NetworkStateCollector.java

/**
 * //from  ww w. ja v  a 2  s .  c  om
 * @param c
 * @param ts
 * @param change
 */
@SuppressWarnings("deprecation")
@SuppressLint({ "DefaultLocale", "NewApi" })
public void run(Context c, long ts, boolean change) {
    try {
        // current active interface (wifi or mobile) and config
        ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
        TelephonyManager tm = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();

        JSONObject data = new JSONObject();
        data.put("on_network_state_change", change); // this collection run was triggered by network change
        data.put("is_connected", (ni != null && ni.isConnectedOrConnecting()));
        data.put("is_roaming", tm.isNetworkRoaming());

        // airplane mode ?
        if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            data.put("is_airplane_mode",
                    (Settings.System.getInt(c.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0));
        } else {
            data.put("is_airplane_mode",
                    (Settings.Global.getInt(c.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0));
        }

        if (ni != null) {
            JSONObject active = new JSONObject();
            active.put("type", ni.getType());
            active.put("subtype", ni.getSubtype());
            active.put("type_name", ni.getTypeName());
            active.put("subtype_name", ni.getSubtypeName());
            active.put("state", ni.getState().toString());
            active.put("detailed_state", ni.getDetailedState().toString());
            active.put("is_wifi", (ni.getType() == ConnectivityManager.TYPE_WIFI));
            data.put("active_network", active);

            if (ni.getType() == ConnectivityManager.TYPE_WIFI) {
                data.put("wifi_network", getWifi(c));
            }
        }

        // mobile network details
        data.put("mobile_network", getMobile(tm));

        // kernel network statistics
        data.put("netstat", getNetstat());

        // interfaces config
        Map<String, JSONObject> stats = networkStats();
        data.put("ifconfig", getIfconfig(stats));

        // double check interfaces
        data.put("ip_addr_show", getIpAddr(stats));

        Helpers.sendResultObj(c, "network_state", ts, data);

    } catch (JSONException jex) {
        Log.w(Constants.LOGTAG, "failed to create json object", jex);
    }
}

From source file:com.chen.emailsync.SyncManager.java

/**
 * Determine whether the account is allowed to sync automatically, as opposed to manually, based
 * on whether the "require manual sync when roaming" policy is in force and applicable
 * @param account the account/*  w ww. ja  v a 2s.  c  o m*/
 * @return whether or not the account can sync automatically
 */
/*package*/ public static boolean canAutoSync(Account account) {
    SyncManager ssm = INSTANCE;
    if (ssm == null) {
        return false;
    }
    NetworkInfo networkInfo = ssm.mNetworkInfo;

    // Enforce manual sync only while roaming here
    long policyKey = account.mPolicyKey;
    // Quick exit from this check
    if ((policyKey != 0) && (networkInfo != null) && isNetworkTypeMobile(networkInfo.getType())) {
        // We'll cache the Policy data here
        Policy policy = account.mPolicy;
        if (policy == null) {
            policy = Policy.restorePolicyWithId(INSTANCE, policyKey);
            account.mPolicy = policy;
            if (!PolicyServiceProxy.isActive(ssm, policy)) {
                PolicyServiceProxy.setAccountHoldFlag(ssm, account, true);
                log("canAutoSync; policies not active, set hold flag");
                return false;
            }
        }
        if (policy != null && policy.mRequireManualSyncWhenRoaming && networkInfo.isRoaming()) {
            return false;
        }
    }
    return true;
}

From source file:com.vonglasow.michael.satstat.GpsEventReceiver.java

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

    // some logic to use the pre-1.7 setting KEY_PREF_UPDATE_WIFI as a
    // fallback if KEY_PREF_UPDATE_NETWORKS is not set
    Set<String> fallbackUpdateNetworks = new HashSet<String>();
    if (sharedPref.getBoolean(Const.KEY_PREF_UPDATE_WIFI, false)) {
        fallbackUpdateNetworks.add(Const.KEY_PREF_UPDATE_NETWORKS_WIFI);
    }/*from ww  w.  j  a v  a 2  s.  c om*/
    Set<String> updateNetworks = sharedPref.getStringSet(Const.KEY_PREF_UPDATE_NETWORKS,
            fallbackUpdateNetworks);

    if (intent.getAction().equals(Const.GPS_ENABLED_CHANGE)
            || intent.getAction().equals(Const.GPS_ENABLED_CHANGE)) {
        //FIXME: why are we checking for the same intent twice? Should on of them be GPS_FIX_CHANGE?
        // an application has connected to GPS or disconnected from it, check if notification needs updating
        boolean notifyFix = sharedPref.getBoolean(Const.KEY_PREF_NOTIFY_FIX, false);
        boolean notifySearch = sharedPref.getBoolean(Const.KEY_PREF_NOTIFY_SEARCH, false);
        if (notifyFix || notifySearch) {
            boolean isRunning = false;
            ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
                if (PasvLocListenerService.class.getName().equals(service.service.getClassName())) {
                    isRunning = true;
                }
            }
            if (!isRunning) {
                Intent startServiceIntent = new Intent(context, PasvLocListenerService.class);
                startServiceIntent.setAction(intent.getAction());
                startServiceIntent.putExtras(intent.getExtras());
                context.startService(startServiceIntent);
            }
        }
    } else if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)
            && updateNetworks.contains(Const.KEY_PREF_UPDATE_NETWORKS_WIFI)) {
        // change in WiFi connectivity, check if we are connected and need to refresh AGPS
        //FIXME: KEY_PREF_UPDATE_WIFI as fallback only
        NetworkInfo netinfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
        if (netinfo == null)
            return;
        if (!netinfo.isConnected())
            return;
        //Toast.makeText(context, "WiFi is connected", Toast.LENGTH_SHORT).show();
        Log.i(this.getClass().getSimpleName(), "WiFi is connected");
        refreshAgps(context, true, false);
    } else if ((intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION))
            || (intent.getAction().equals(Const.AGPS_DATA_EXPIRED))) {
        // change in network connectivity or AGPS expiration timer fired
        boolean isAgpsExpired = false;
        if (intent.getAction().equals(Const.AGPS_DATA_EXPIRED)) {
            Log.i(this.getClass().getSimpleName(), "AGPS data expired, checking available networks");
            isAgpsExpired = true;
        }
        NetworkInfo netinfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE))
                .getActiveNetworkInfo();
        if (netinfo == null)
            return;
        if (!netinfo.isConnected())
            return;
        String type;
        if ((netinfo.getType() < ConnectivityManager.TYPE_MOBILE_MMS)
                || (netinfo.getType() > ConnectivityManager.TYPE_MOBILE_HIPRI)) {
            type = Integer.toString(netinfo.getType());
        } else {
            // specific mobile data connections will be treated as TYPE_MOBILE
            type = Const.KEY_PREF_UPDATE_NETWORKS_MOBILE;
        }
        if (!updateNetworks.contains(type))
            return;
        if (!isAgpsExpired)
            Log.i(this.getClass().getSimpleName(),
                    "Network of type " + netinfo.getTypeName() + " is connected");
        // Enforce the update interval if we were called by a network event
        // but not if we were called by a timer, because in that case the
        // check has already been done. (I am somewhat paranoid and don't
        // count on alarms not going off a few milliseconds too early.)
        refreshAgps(context, !isAgpsExpired, false);
    }
}

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);/*from w  ww .  j a  va2s.  c  o  m*/
    } 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);
        }
    }
}