Example usage for android.telephony PhoneStateListener LISTEN_DATA_CONNECTION_STATE

List of usage examples for android.telephony PhoneStateListener LISTEN_DATA_CONNECTION_STATE

Introduction

In this page you can find the example usage for android.telephony PhoneStateListener LISTEN_DATA_CONNECTION_STATE.

Prototype

int LISTEN_DATA_CONNECTION_STATE

To view the source code for android.telephony PhoneStateListener LISTEN_DATA_CONNECTION_STATE.

Click Source Link

Document

Listen for changes to the data connection state (cellular).

Usage

From source file:com.secupwn.aimsicd.service.CellTracker.java

/**
 *  Description:    Updates Neighboring Cell details
 *
 *                  TODO: add more details...
 *
 *
 *///from w  w  w. j ava 2s.  c  o m
public List<Cell> updateNeighboringCells() {
    List<Cell> neighboringCells = new ArrayList<>();
    List<NeighboringCellInfo> neighboringCellInfo = tm.getNeighboringCellInfo();
    if (neighboringCellInfo == null) {
        neighboringCellInfo = new ArrayList<>();
    }

    Boolean nclp = tinydb.getBoolean("nc_list_present"); // NC list present? (default is false)

    //if nclp = true then check for neighboringCellInfo
    if (neighboringCellInfo != null && neighboringCellInfo.size() == 0 && nclp) {

        log.info("NeighboringCellInfo is empty: start polling...");

        // Try to poll the neighboring cells for a few seconds
        neighboringCellBlockingQueue = new LinkedBlockingQueue<>(100); // TODO What is this ??

        //LISTEN_CELL_INFO added in API 17
        // TODO: See issue #555 (DeviceApi17.java is using API 18 CellInfoWcdma calls.
        if (Build.VERSION.SDK_INT > 17) {
            DeviceApi18.startListening(tm, phoneStatelistener);
        } else {
            tm.listen(phoneStatelistener,
                    PhoneStateListener.LISTEN_CELL_LOCATION | PhoneStateListener.LISTEN_CELL_INFO | // API 17
                            PhoneStateListener.LISTEN_DATA_CONNECTION_STATE
                            | PhoneStateListener.LISTEN_SERVICE_STATE
                            | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
        }

        // TODO: Consider removing ??
        for (int i = 0; i < 10 && neighboringCellInfo.size() == 0; i++) {
            try {
                log.debug("NeighboringCellInfo empty: trying " + i);
                NeighboringCellInfo info = neighboringCellBlockingQueue.poll(1, TimeUnit.SECONDS);
                if (info == null) {
                    neighboringCellInfo = tm.getNeighboringCellInfo();
                    if (neighboringCellInfo != null) {
                        if (neighboringCellInfo.size() > 0) {
                            // Can we think of a better log message here?
                            log.debug("NeighboringCellInfo found on " + i + " try. (time based)");
                            break;
                        } else {
                            continue;
                        }
                    }
                }
                List<NeighboringCellInfo> cellInfoList = new ArrayList<>(
                        neighboringCellBlockingQueue.size() + 1);
                while (info != null) {
                    cellInfoList.add(info);
                    info = neighboringCellBlockingQueue.poll(1, TimeUnit.SECONDS);
                }
                neighboringCellInfo = cellInfoList;
            } catch (InterruptedException e) {
                // TODO: Add a more valuable message here!
                log.error("", e);
            }
        }
    }

    //log.debug(mTAG + ": neighboringCellInfo size: " + neighboringCellInfo.size());

    // Add NC list to DBi_measure:nc_list
    for (NeighboringCellInfo neighborCell : neighboringCellInfo) {
        log.info("NeighboringCellInfo -" + " LAC:" + neighborCell.getLac() + " CID:" + neighborCell.getCid()
                + " PSC:" + neighborCell.getPsc() + " RSSI:" + neighborCell.getRssi());

        final Cell cell = new Cell(neighborCell.getCid(), neighborCell.getLac(), neighborCell.getRssi(),
                neighborCell.getPsc(), neighborCell.getNetworkType(), false);
        neighboringCells.add(cell);
    }
    return neighboringCells;
}

From source file:org.pixmob.freemobile.netstat.MonitorService.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override/* w w  w  .  ja va2 s  .c  om*/
public void onCreate() {
    super.onCreate();

    pm = (PowerManager) getSystemService(POWER_SERVICE);
    tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

    prefs = getSharedPreferences(SP_NAME, MODE_PRIVATE);
    prefs.registerOnSharedPreferenceChangeListener(this);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        final int largeIconWidth = getResources()
                .getDimensionPixelSize(android.R.dimen.notification_large_icon_width);
        final int largeIconHeight = getResources()
                .getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
        if ((largeIconWidth > 0) && (largeIconHeight > 0)) {
            Bitmap freeLargeIconTmp = BitmapFactory.decodeResource(getResources(),
                    R.drawable.ic_stat_notify_service_free_large);
            if ((freeLargeIconTmp != null) && (freeLargeIconTmp.getWidth() > 0)
                    && (freeLargeIconTmp.getHeight() > 0)) {
                freeLargeIcon = Bitmap.createScaledBitmap(freeLargeIconTmp, largeIconWidth, largeIconHeight,
                        true);
            }

            Bitmap freeFemtoLargeIconTmp = BitmapFactory.decodeResource(getResources(),
                    R.drawable.ic_stat_notify_service_free_femto_large);
            if ((freeFemtoLargeIconTmp != null) && (freeFemtoLargeIconTmp.getHeight() > 0)
                    && (freeFemtoLargeIconTmp.getWidth() > 0)) {
                freeFemtoLargeIcon = Bitmap.createScaledBitmap(freeFemtoLargeIconTmp, largeIconWidth,
                        largeIconHeight, true);
            }

            Bitmap orangeLargeIconTmp = BitmapFactory.decodeResource(getResources(),
                    R.drawable.ic_stat_notify_service_orange_large);
            if ((orangeLargeIconTmp != null) && (orangeLargeIconTmp.getHeight() > 0)
                    && (orangeLargeIconTmp.getWidth() > 0)) {
                orangeLargeIcon = Bitmap.createScaledBitmap(orangeLargeIconTmp, largeIconWidth, largeIconHeight,
                        true);
            }
        }
    }

    // Initialize and start a worker thread for inserting rows into the
    // application database.
    final Context c = getApplicationContext();
    pendingInsert = new ArrayBlockingQueue<>(8);
    new PendingInsertWorker(c, pendingInsert).start();

    // This intent is fired when the application notification is clicked.
    openUIPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_NOTIFICATION),
            PendingIntent.FLAG_CANCEL_CURRENT);

    // This intent is only available as a Jelly Bean notification action in
    // order to open network operator settings.
    Intent networkSettingsIntent = IntentFactory.networkOperatorSettings(this);
    if (networkSettingsIntent != null) {
        networkOperatorSettingsPendingIntent = PendingIntent.getActivity(this, 0, networkSettingsIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
    }
    Intent wirelessSettingsIntent = IntentFactory.wirelessSettings(this);
    if (wirelessSettingsIntent != null) {
        wirelessSettingsPendingIntent = PendingIntent.getActivity(this, 0, wirelessSettingsIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);
    }

    // Watch screen light: is the screen on?
    screenMonitor = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            updateEventDatabase();
        }
    };

    final IntentFilter screenIntentFilter = new IntentFilter();
    screenIntentFilter.addAction(Intent.ACTION_SCREEN_ON);
    screenIntentFilter.addAction(Intent.ACTION_SCREEN_OFF);
    registerReceiver(screenMonitor, screenIntentFilter);

    // Watch Wi-Fi connections.
    connectionMonitor = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (onConnectivityUpdated()) {
                updateEventDatabase();
            }
        }
    };

    final IntentFilter connectionIntentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(connectionMonitor, connectionIntentFilter);

    // Watch mobile connections.
    phoneMonitor = new PhoneStateListener() {
        @Override
        public void onDataConnectionStateChanged(int state, int networkType) {
            updateService();
        }

        @Override
        public void onServiceStateChanged(ServiceState serviceState) {
            if (stopServiceIfSimOperatorIsNotFreeMobile())
                return;

            mobileNetworkConnected = (serviceState != null)
                    && (serviceState.getState() == ServiceState.STATE_IN_SERVICE);

            updateService();
        }

        @Override
        public void onCellInfoChanged(List<CellInfo> cellInfo) {
            updateService();
        }

        private void updateService() {
            if (tm != null) { // Fix NPE - found by Acralyzer
                mobileNetworkType = tm.getNetworkType(); //update the network type to have the latest
            }
            final int phoneStateUpdated = onPhoneStateUpdated();
            if (phoneStateUpdated >= 0)
                updateEventDatabase();

            updateNotification(true, phoneStateUpdated == 1);
        }
    };
    int events = PhoneStateListener.LISTEN_SERVICE_STATE | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
        events |= PhoneStateListener.LISTEN_CELL_INFO;

    tm.listen(phoneMonitor, events);

    // Watch battery level.
    batteryMonitor = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            updateEventDatabase();
        }
    };

    batteryIntentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(batteryMonitor, batteryIntentFilter);

    shutdownMonitor = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            onDeviceShutdown();
        }
    };
    final IntentFilter shutdownIntentFilter = new IntentFilter();
    shutdownIntentFilter.addAction(Intent.ACTION_SHUTDOWN);
    // HTC devices use a different Intent action:
    // http://stackoverflow.com/q/5076410/422906
    shutdownIntentFilter.addAction("android.intent.action.QUICKBOOT_POWEROFF");
    registerReceiver(shutdownMonitor, shutdownIntentFilter);

    if (prefs.getBoolean(SP_KEY_ENABLE_AUTO_RESTART_SERVICE, false) && Arrays
            .asList(ANDROID_VERSIONS_ALLOWED_TO_AUTO_RESTART_SERVICE).contains(Build.VERSION.RELEASE)) {
        // Kitkat and JellyBean auto-kill service workaround
        // http://stackoverflow.com/a/20735519/1527491
        ensureServiceStaysRunning();
    }
}

From source file:com.SecUpwN.AIMSICD.service.AimsicdService.java

/**
 * Updates Neighbouring Cell details/*from   w  w w . j av a  2  s  .  c o m*/
 */
public List<Cell> updateNeighbouringCells() {
    List<Cell> neighboringCells = new ArrayList<>();

    List<NeighboringCellInfo> neighboringCellInfo;
    neighboringCellInfo = tm.getNeighboringCellInfo();
    if (neighboringCellInfo.size() == 0) {
        // try to poll the neighboring cells for a few seconds
        final LinkedBlockingQueue<NeighboringCellInfo> neighboringCellBlockingQueue = new LinkedBlockingQueue<>(
                100);
        final PhoneStateListener listener = new PhoneStateListener() {
            private void handle() {
                List<NeighboringCellInfo> neighboringCellInfo;
                neighboringCellInfo = tm.getNeighboringCellInfo();
                if (neighboringCellInfo.size() == 0) {
                    return;
                }
                Log.i(TAG, "neighbouringCellInfo empty - event based polling succeeded!");
                tm.listen(this, PhoneStateListener.LISTEN_NONE);
                neighboringCellBlockingQueue.addAll(neighboringCellInfo);
            }

            @Override
            public void onServiceStateChanged(ServiceState serviceState) {
                handle();
            }

            @Override
            public void onDataConnectionStateChanged(int state) {
                handle();
            }

            @Override
            public void onDataConnectionStateChanged(int state, int networkType) {
                handle();
            }

            @Override
            public void onSignalStrengthsChanged(SignalStrength signalStrength) {
                handle();
            }

            @Override
            public void onCellInfoChanged(List<CellInfo> cellInfo) {
                handle();
            }
        };
        Log.i(TAG, "neighbouringCellInfo empty - start polling");

        //LISTEN_CELL_INFO added in API 17
        if (Build.VERSION.SDK_INT > 16) {
            tm.listen(listener, PhoneStateListener.LISTEN_CELL_INFO | PhoneStateListener.LISTEN_CELL_LOCATION
                    | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE | PhoneStateListener.LISTEN_SERVICE_STATE
                    | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
        } else {
            tm.listen(listener,
                    PhoneStateListener.LISTEN_CELL_LOCATION | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE
                            | PhoneStateListener.LISTEN_SERVICE_STATE
                            | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
        }

        for (int i = 0; i < 10 && neighboringCellInfo.size() == 0; i++) {
            try {
                Log.i(TAG, "neighbouringCellInfo empty - try " + i);
                NeighboringCellInfo info = neighboringCellBlockingQueue.poll(1, TimeUnit.SECONDS);
                if (info == null) {
                    neighboringCellInfo = tm.getNeighboringCellInfo();
                    if (neighboringCellInfo.size() > 0) {
                        Log.i(TAG, "neighbouringCellInfo empty - try " + i + " succeeded time based");
                        break;
                    } else {
                        continue;
                    }
                }
                ArrayList<NeighboringCellInfo> cellInfoList = new ArrayList<NeighboringCellInfo>(
                        neighboringCellBlockingQueue.size() + 1);
                while (info != null) {
                    cellInfoList.add(info);
                    info = neighboringCellBlockingQueue.poll(1, TimeUnit.SECONDS);
                }
                neighboringCellInfo = cellInfoList;
            } catch (InterruptedException e) {
                // normal
            }
        }
    }

    Log.i(TAG, "neighbouringCellInfo Size - " + neighboringCellInfo.size());
    for (NeighboringCellInfo neighbourCell : neighboringCellInfo) {
        Log.i(TAG, "neighbouringCellInfo - CID:" + neighbourCell.getCid() + " LAC:" + neighbourCell.getLac()
                + " RSSI:" + neighbourCell.getRssi() + " PSC:" + neighbourCell.getPsc());

        final Cell cell = new Cell(neighbourCell.getCid(), neighbourCell.getLac(), neighbourCell.getRssi(),
                neighbourCell.getPsc(), neighbourCell.getNetworkType(), false);
        neighboringCells.add(cell);
    }

    return neighboringCells;
}

From source file:android_network.hetnet.vpn_service.ActivitySettings.java

@Override
protected void onResume() {
    super.onResume();

    // Check if permissions were revoked
    checkPermissions();/*from   w ww.  j  a  va2  s  .  com*/

    // Listen for preference changes
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.registerOnSharedPreferenceChangeListener(this);

    // Listen for interactive state changes
    IntentFilter ifInteractive = new IntentFilter();
    ifInteractive.addAction(Intent.ACTION_SCREEN_ON);
    ifInteractive.addAction(Intent.ACTION_SCREEN_OFF);
    registerReceiver(interactiveStateReceiver, ifInteractive);

    // Listen for connectivity updates
    IntentFilter ifConnectivity = new IntentFilter();
    ifConnectivity.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(connectivityChangedReceiver, ifConnectivity);

    if (Util.hasPhoneStatePermission(this)) {
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        tm.listen(phoneStateListener,
                PhoneStateListener.LISTEN_DATA_CONNECTION_STATE | PhoneStateListener.LISTEN_SERVICE_STATE);
        phone_state = true;
    }
}

From source file:com.github.jthuraisamy.yellowusage.ui.MainActivity.java

@Override
public void onStart() {
    super.onStart();

    // Set Realm change listener.
    realm.addChangeListener(new RealmChangeListener() {
        @Override//www .ja  va 2 s  .com
        public void onChange() {
            // TODO: Something useful should happen here.
            Log.i(TAG, "RealmChangeListener: Changed.");
        }
    });

    // Set TelephonyManager listener.
    telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);

    // Set mobile data protection switch and listener.
    if (isMobileDataEnabled(connectivityManager))
        dataProtectionSwitch.setChecked(false);
    else
        dataProtectionSwitch.setChecked(true);
    dataProtectionSwitch.setOnCheckedChangeListener(dataProtectionSwitchListener);

    // Set voice protection switch and listener.
    if (PreferenceHelper.isVoiceOverageProtectionEnabled(this))
        voiceProtectionSwitch.setChecked(true);
    else
        voiceProtectionSwitch.setChecked(false);
    voiceProtectionSwitch.setOnCheckedChangeListener(voiceProtectionSwitchListener);

    // Set messaging protection switch and listener.
    if (PreferenceHelper.isMessagingOverageProtectionEnabled(this))
        messagingProtectionSwitch.setChecked(true);
    else
        messagingProtectionSwitch.setChecked(false);
    messagingProtectionSwitch.setOnCheckedChangeListener(messagingProtectionSwitchListener);

    // Set PanelSlideListener to change panel state icon based on expanded/collapsed state.
    feesPanel.setPanelSlideListener(panelSlideListener);

    // Set OnClickListener on bottomBar to expand/collapse the sliding panel.
    bottomBar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (feesPanel.getPanelState() == PanelState.COLLAPSED) {
                feesPanel.expandPanel();
            } else if (feesPanel.getPanelState() == PanelState.EXPANDED) {
                feesPanel.collapsePanel();
            }
        }
    });
}

From source file:com.SecUpwN.AIMSICD.service.AimsicdService.java

/**
 * Cell Information Tracking and database logging
 *
 * @param track Enable/Disable tracking//from  w  w  w .ja v a  2  s .c om
 */
public void setCellTracking(boolean track) {
    if (track) {
        tm.listen(mCellSignalListener,
                PhoneStateListener.LISTEN_CELL_LOCATION | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS
                        | PhoneStateListener.LISTEN_DATA_ACTIVITY
                        | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
        if (lm != null) {
            mLocationListener = new MyLocationListener();
            Log.i(TAG, "LocationManager already existed");
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, GPS_MIN_UPDATE_TIME,
                    GPS_MIN_UPDATE_DISTANCE, mLocationListener);
        } else {
            Log.i(TAG, "LocationManager did not exist");
            lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            if (lm != null) {
                if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                    Log.i(TAG, "LocationManager created");
                    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, GPS_MIN_UPDATE_TIME,
                            GPS_MIN_UPDATE_DISTANCE, mLocationListener);
                }
            }
        }
        Helpers.msgShort(this, "Tracking cell information");
        mTrackingCell = true;
    } else {
        tm.listen(mCellSignalListener, PhoneStateListener.LISTEN_NONE);
        lm.removeUpdates(mLocationListener);
        mDevice.mCell.setLon(0.0);
        mDevice.mCell.setLat(0.0);
        mTrackingCell = false;
        mDevice.setCellInfo("[0,0]|nn|nn|");
        Helpers.msgShort(this, "Stopped tracking cell information");
    }
    setNotification();
}

From source file:com.github.jthuraisamy.yellowusage.ui.MainActivity.java

/**
 * Run queued tasks provided that mobile data is enabled and connected. If it is not enabled,
 * prompt the user to enable it so that the device can connect to data. If it is enabled but
 * connected to WiFi instead, disable WiFi first. Once a data connection is established, the
 * PhoneStateListener will call this method.
 *///w  ww  .  j  a  va2s .  com
private void runTasks() {
    if (isMobileDataEnabled(connectivityManager)) {
        Log.i(TAG, "runTasks: Data is enabled.");
        if (isMobileDataConnected(telephonyManager)) {
            Log.i(TAG, "runTasks: Data is connected.");

            // Empty and execute tasks in the task queue.
            while (!taskQueue.isEmpty())
                taskQueue.remove().execute();
        } else {
            Log.i(TAG, "runTasks: Data is disconnected.");

            if (taskQueue.isEmpty())
                return;

            if (isWifiConnected(wifiManager)) {
                Log.i(TAG, "runTasks: Disabling WiFi...");

                // Start prepare refresh animation in the app bar via onPrepareOptionsMenu().
                supportInvalidateOptionsMenu();

                // Disable WiFi, and call runTasks() again after data is connected.
                telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
                telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
                Toast.makeText(this, R.string.disabling_wifi, Toast.LENGTH_SHORT).show();
                wifiManager.setWifiEnabled(false);
                wifiWasEnabled = true;
            }
        }
    } else {
        Log.i(TAG, "runTasks: Data is disabled.");

        Toast.makeText(this, R.string.enable_mobile_data, Toast.LENGTH_LONG).show();
    }
}