Example usage for android.telephony ServiceState STATE_IN_SERVICE

List of usage examples for android.telephony ServiceState STATE_IN_SERVICE

Introduction

In this page you can find the example usage for android.telephony ServiceState STATE_IN_SERVICE.

Prototype

int STATE_IN_SERVICE

To view the source code for android.telephony ServiceState STATE_IN_SERVICE.

Click Source Link

Document

Normal operation condition, the phone is registered with an operator either in home network or in roaming.

Usage

From source file:com.ultrafunk.network_info.service.MobileDataStateListener.java

@Override
public void onServiceStateChanged(ServiceState serviceState) {
    switch (serviceState.getState()) {
    case ServiceState.STATE_EMERGENCY_ONLY:
    case ServiceState.STATE_OUT_OF_SERVICE:
        NetworkStateService.setMobileOutOfService(true);
        LocalBroadcastManager.getInstance(context)
                .sendBroadcast(new Intent(Constants.ACTION_SERVICE_STATE_CHANGED));
        break;/*from  ww w .j  a  v  a2 s.com*/

    default: {
        NetworkStateService.setMobileOutOfService(false);

        // If the device is network roaming but mobile data roaming is disabled, this
        // broadcast is necessary to properly update the widget on service state changes.
        if ((serviceState.getState() == ServiceState.STATE_IN_SERVICE) && serviceState.getRoaming())
            LocalBroadcastManager.getInstance(context)
                    .sendBroadcast(new Intent(Constants.ACTION_SERVICE_STATE_CHANGED));
    }
        break;
    }
}

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

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override/*from ww  w . ja  v  a2  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:org.restcomm.app.utillib.ContentProvider.ContentValuesGenerator.java

/**
 * This method generates a ContentValues object from the signal object so that it may
 * be stored in the database./*w  ww . j a va  2  s. c  o  m*/
 * @param signal
 * @param phoneType This is the phone type and must be one of {@link TelephonyManager#PHONE_TYPE_CDMA}
 * or {@link TelephonyManager#PHONE_TYPE_GSM}.
 * @param stagedEventId This is the id of the event that this signal has to be related to
 * @return
 */
public static ContentValues generateFromSignal(SignalEx signal, int phoneType, int networkType,
        int serviceState, int dataState, long stagedEventId, int wifiSignal, JSONObject serviceMode) {
    ContentValues values = new ContentValues();
    Integer dBm = 0;
    Integer signalDB = null;
    try {
        if (serviceMode != null && serviceMode.getLong("time") + 5000 < System.currentTimeMillis())
            serviceMode = null;
        if (signal == null) // as a result of a service outage
        {
            LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, "ContentValues", "generateFromSignal",
                    "signal == null");
            values.put(Tables.SignalStrengths.SIGNAL, -256);
            //now do the common parameters
            values.put(Tables.SignalStrengths.TIMESTAMP, System.currentTimeMillis());
            values.put(Tables.SignalStrengths.EVENT_ID, stagedEventId);
            values.put(Tables.SignalStrengths.COVERAGE, 0);
            return values;
        }
        if (signal.getSignalStrength() == null) // as a result of a screen off (signal unknown)
            values.put(Tables.SignalStrengths.SIGNAL, (Integer) null);
        //do phone type specific actions first
        else if (phoneType == TelephonyManager.PHONE_TYPE_CDMA) {
            boolean isEvdo = true;

            if (networkType == TelephonyManager.NETWORK_TYPE_1xRTT
                    || networkType == TelephonyManager.NETWORK_TYPE_CDMA) {
                isEvdo = false;
                dBm = signal.getCdmaDbm();
            } else {
                dBm = signal.getEvdoDbm();
                int evdoDbm = signal.getEvdoDbm();
                // If there is no EVDO signal but there is CDMA signal, then use CDMA signal
                if (evdoDbm <= -120 || evdoDbm >= -1) {
                    int cdmaDbm = signal.getCdmaDbm();
                    if (cdmaDbm <= -120 || cdmaDbm >= -1)
                        dBm = evdoDbm; // no cdma signal either, so send the evdo signal afterall
                    else {
                        dBm = cdmaDbm;
                        isEvdo = false; // display and report the CDMA signal if CDMA has signal and EVDO does not
                    }
                }
            }

            //if (dBm == -1) // When Scott had a network outage on CDMA, he got -1, we want -256
            //   dBm = -256;
            if (dBm == -120 && networkType == TelephonyManager.NETWORK_TYPE_LTE)
                dBm = null; // signal not known, this seems to happen with LTE advanced
            values.put(Tables.SignalStrengths.SIGNAL, dBm
            //isEvdo ? signal.getSignalStrength().getEvdoDbm() : signal.getSignalStrength().getCdmaDbm()
            );
            values.put(Tables.SignalStrengths.ECI0,
                    isEvdo ? signal.getEvdoEcio() / 10.0 : signal.getCdmaEcio() / 10.0);
            values.put(Tables.SignalStrengths.SNR, isEvdo ? signal.getEvdoSnr() : null);
            //if (isEvdo)
            values.put(Tables.SignalStrengths.SIGNAL2G, signal.getCdmaDbm()
            //isEvdo ? signal.getSignalStrength().getCdmaDbm() : null
            );
            signalDB = dBm;
        } else if (phoneType == TelephonyManager.PHONE_TYPE_GSM) {

            if (getPlatform() == 1) //On Android device
                signalDB = signal.getGsmSignalStrength();
            else if (getPlatform() == 3) {//On Blackberry device
                signalDB = PreferenceManager.getDefaultSharedPreferences(service.getApplicationContext())
                        .getInt(PreferenceKeys.Miscellaneous.BB_SIGNAL, 99);

            }
            if (signalDB == 99 || signalDB == -1 || signalDB == null) {
                signalDB = null;
                //            Integer signalLte = signal.getLayer3("mLteSignalStrength");
                //            if (signalLte != null && signalLte < 99)
                //            {
                //               if (signalLte == 0)
                //                  signalDB = -120;
                //               else
                //                  signalDB = -113 + signalLte*2;
                //            }

                // If signal is unknown but signal bars are known, send bars
                Integer signalBar = signal.getLayer3("mGsmSignalBar");
                if (signalBar != null && signalBar != -1) {
                    signalDB = getSignalDBFromBars(signalBar);
                    values.put(Tables.SignalStrengths.SIGNALBARS, signalBar);
                }

            } else if (getPlatform() == 1)
                signalDB = signal.getDbmValue(networkType, phoneType);

            Integer ecio = signal.getLayer3("mUmtsEcio");
            if (ecio == null)
                ecio = signal.getLayer3("mgw_ecio");
            if (ecio == null)
                ecio = signal.getLayer3("mGsmEcio");
            //         if (ecio == null)
            //         {
            //            ecio = signal.getLayer3("lastEcIoIndex");
            //            if (ecio != null)
            //               ecio = 2*signal.getLayer3Array("lastEcIoValues", ecio);
            //         }

            Integer ecno = signal.getLayer3("mUmtsEcno");
            if (ecno == null)
                ecno = signal.getLayer3("mGsmEcno");
            Integer rscp = signal.getLayer3("mUmtsRscp");
            if (rscp == null)
                rscp = signal.getLayer3("mGsmRscp");
            if (rscp == null)
                rscp = signal.getLayer3("mWcdmaRscp");
            if ((signalDB == null || signalDB <= -120) && rscp != null && rscp > -120 && rscp < -20)
                signalDB = rscp;

            values.put(Tables.SignalStrengths.ECI0, ecio);
            values.put(Tables.SignalStrengths.RSCP, rscp);
            values.put(Tables.SignalStrengths.ECN0, ecno);
            values.put(Tables.SignalStrengths.SIGNAL, signalDB);
            values.put(Tables.SignalStrengths.BER,
                    signal.getGsmBitErrorRate() == 99 ? null : signal.getGsmBitErrorRate());
        }
        values.put(Tables.SignalStrengths.WIFISIGNAL, wifiSignal);
        // check for LTE signal signal quality parameters only if connected to LTE
        if (networkType == TelephonyManager.NETWORK_TYPE_LTE) {
            Integer lteRsrp = -1, lteRsrq, lteSnr, lteCqi;

            lteRsrp = signal.getLayer3("mLteRsrp");
            lteRsrq = signal.getLayer3("mLteRsrq");
            lteSnr = signal.getLayer3("mLteRssnr");
            if (lteRsrp != null && lteRsrp >= 40 && lteRsrp < 140)
                lteRsrp = -lteRsrp;
            else if (lteRsrp != null && lteRsrp > 0 && lteRsrp <= 32)
                lteRsrp = (lteRsrp - 2) * 2 + -109;
            if (lteSnr == null || lteSnr > 1000)
                lteSnr = signal.getLayer3("mLteSnr");
            if (lteSnr == null || lteSnr < -200 || lteSnr > 1000)
                lteSnr = null;
            if (lteRsrp != null && lteRsrp > 1000)
                lteRsrp = lteRsrq = null;

            lteCqi = signal.getLayer3("mLteCqi");
            values.put(Tables.SignalStrengths.LTE_RSRP, lteRsrp);
            values.put(Tables.SignalStrengths.LTE_RSRQ, lteRsrq);
            values.put(Tables.SignalStrengths.LTE_SNR, lteSnr);
            values.put(Tables.SignalStrengths.LTE_CQI, lteCqi);

        }
        // check for the LTE signal regardless, at least it will indicate of device supports LTE
        Integer lteRssi = signal.getLayer3("mLteRssi");
        if (lteRssi == null)
            lteRssi = signal.getLayer3("mLteSignalStrength");
        if (lteRssi != null) {
            if (lteRssi >= 0 && lteRssi < 32) {
                if (lteRssi == 0)
                    lteRssi = -120; // officially 0 means -113dB or less, but since lowest possible signal on Blackberry = -120, call it -120 for consistency
                else if (lteRssi == 1)
                    lteRssi = -111; // officially 1 = -111 dB
                else if (lteRssi > 1 && lteRssi <= 31)
                    lteRssi = (lteRssi - 2) * 2 + -109;
            }

            // allow for the possibility of sending a 3G signal and LTE signal at the same time
            // but if LTE signal is present, and 3G signal says -120 or worse, ignore regular signal
            if (lteRssi > -120 && (dBm == null || dBm <= -120))
                values.put(Tables.SignalStrengths.SIGNAL, (Integer) lteRssi);

        }
        values.put(Tables.SignalStrengths.LTE_SIGNAL, lteRssi);

        if (serviceMode != null && serviceMode.getLong("time") + 20000 > System.currentTimeMillis()) {
            if (serviceMode.has("ecio") && serviceMode.getString("ecio").length() > 1) {
                int svc_ecio = Integer.parseInt(serviceMode.getString("ecio"), 10);
                if (svc_ecio <= -2 && svc_ecio >= -30) {
                    values.put(Tables.SignalStrengths.ECI0, svc_ecio);
                }
            }
            if (serviceMode.has("rscp") && serviceMode.getString("rscp").length() > 1) {
                int svc_rscp = Integer.parseInt(serviceMode.getString("rscp"), 10);
                if (svc_rscp <= -20 && svc_rscp >= -120) //  && (signalDB == null || signalDB <= -120))
                    values.put(Tables.SignalStrengths.SIGNAL, svc_rscp);
            }

            if (serviceMode.has("snr") && serviceMode.getString("snr").length() > 1) {
                float svc_fsnr = Float.parseFloat(serviceMode.getString("snr"));
                int svc_snr = (int) (svc_fsnr * 10);
                if (svc_snr > -200 && svc_snr < 2000)
                    values.put(Tables.SignalStrengths.LTE_SNR, svc_snr);
            }

            if (serviceMode.has("rsrp") && serviceMode.getString("rsrp").length() > 1) {
                int svc_rsrp = Integer.parseInt(serviceMode.getString("rsrp"), 10);
                if (svc_rsrp <= -20 && svc_rsrp >= -140)
                    values.put(Tables.SignalStrengths.LTE_RSRP, svc_rsrp);
            }

            if (serviceMode.has("rsrq") && serviceMode.getString("rsrq").length() > 1) {
                int svc_rsrq = Integer.parseInt(serviceMode.getString("rsrp"), 10);
                if (svc_rsrq <= -1 && svc_rsrq >= -30)
                    values.put(Tables.SignalStrengths.LTE_RSRQ, svc_rsrq);
            }

        }

        //now do the common parameters
        values.put(Tables.SignalStrengths.TIMESTAMP, signal.getTimestamp());
        values.put(Tables.SignalStrengths.EVENT_ID, stagedEventId);
        int coverage = 0;
        if (networkType == 0) {
            if (serviceState == ServiceState.STATE_IN_SERVICE)
                networkType = 1;
            //else if (serviceState == ServiceState.STATE_POWER_OFF)
            //   networkType = -1;
        }
        int networkTier = PhoneState.getNetworkGeneration(networkType);
        if (networkTier == 0) // dont make it 0 unless truly out of service
            networkTier = 1;
        if (serviceState == ServiceState.STATE_OUT_OF_SERVICE && (dataState != TelephonyManager.DATA_CONNECTED
                || networkType != TelephonyManager.NETWORK_TYPE_LTE)) // Sprint can be connected to LTE and say outofservice
            networkTier = 0;
        else if (serviceState == ServiceState.STATE_POWER_OFF
                || serviceState == ServiceState.STATE_EMERGENCY_ONLY
                || serviceState == ServiceState.STATE_POWER_OFF || serviceState == 9) // 9 = MMCPhoneStateListenerOld.SERVICE_STATE_AIRPLANE)
            networkTier = -1;

        // tier 5 becomes 11111, tier 1 = 00001
        coverage = networkTier; // (1 << networkTier) - 1;

        //String reflect = listSignalFields (signal);

        values.put(Tables.SignalStrengths.COVERAGE, coverage);
        //MMCLogger.logToFile(MMCLogger.Level.DEBUG, "", "onSignal.listSignalFields", reflect);
        //MMCLogger.logToFile(MMCLogger.Level.DEBUG, "", "onSignal.values", values.toString());
    } catch (Exception e) {
        LoggerUtil.logToFile(LoggerUtil.Level.ERROR, "ContentValuesGenerator", "generateFromSignal",
                "exception", e);
    }
    return values;
}

From source file:org.restcomm.app.qoslib.Services.LibPhoneStateListener.java

@Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
    super.onSignalStrengthsChanged(signalStrength);
    if (DeviceInfoOld.getPlatform() != 1) //Not an Android device
        return;/*  ww w  .  j a v a  2s  .c  o  m*/

    if (!owner.isMMCActiveOrRunning()) {
        mPhoneState.lastKnownSignalStrength = signalStrength;
        return;
    }
    mPhoneState.lastKnownSignalStrength = null;
    //if (signalStrength != null)
    //   MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "onSignalStrengthsChanged", signalStrength.toString());
    int pref = networkPreference(owner.getApplicationContext());
    try {
        if (mPhoneState.previousServiceState == ServiceState.STATE_IN_SERVICE
                || mPhoneState.previousServiceState == ServiceState.STATE_EMERGENCY_ONLY) {
            SignalEx mmcSignal = new SignalEx(signalStrength);
            processNewMMCSignal(mmcSignal);

        } else {
            SignalEx mmcSignal = new SignalEx();
            processNewMMCSignal(mmcSignal);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            List<CellInfo> cells = telephonyManager.getAllCellInfo();
            if (cells != null)
                onCellInfoChanged(cells);
            //            for (int c =0; c<cells.size(); c++)
            //            { 
            //               String msg =  "cells[" + c + "]=" + cells.get(c).toString();
            //               MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "onSignalStrengthsChanged", "cells[" + c + "]=" + cells.get(c).toString());
            //               //Log.d(TAG, "cells[" + c + "]=" + cells.get(c).toString());
            //            }
        }

    } catch (Exception e) {
        LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "onSignalStrengthsChanged",
                "Exception " + e.getMessage());
    }
}

From source file:org.restcomm.app.qoslib.Services.Events.EventManager.java

/**
 * At the start of the event, stores like-timestamped entries in the tables for signals, cells and locations
 * This is so that querying the timespan of the event recording will easily return records for the beginning of the event
 * among other things//from ww  w .  jav a2  s.  c  o m
 * @param event
 */
public void signalSnapshot(EventObj event) {
    // In case the signal hasn't changed recently (last 30 sec or so), 
    // the signal won't be retrieved by the cursor unless we timestamp the last known signal now
    try {

        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        // Update the database and intents with a snapshot of the last known signal, cell, location
        SignalEx signal = context.getPhoneState().getLastMMCSignal();
        long timestamp = System.currentTimeMillis();
        if (event != null)
            timestamp = event.getEventTimestamp();
        if (signal != null) {
            signal.setTimestamp(timestamp);
            context.getPhoneState().clearLastMMCSignal(); // to force a duplicate signal to be added
            context.getPhoneStateListener().processNewMMCSignal(signal);
        }

        CellLocationEx cell = context.getPhoneStateListener().getLastCellLocation();
        if (cell != null) {
            cell.setCellIdTimestamp(timestamp);
            context.getPhoneStateListener().clearLastCellLocation();
            context.getPhoneStateListener().processNewCellLocation(cell);
        }

        if (event == null)
            return;

        ongoingEvents.add(event);
        Location location = context.getLastLocation();
        int satellites = context.getLastNumSatellites();
        if (location != null) {
            location.setTime(timestamp);
            context.setLastLocation(null); // to force a duplicate location to be added
            context.processNewFilteredLocation(location, satellites);
        }

        // set an initial location on the event if it is recent, but update it if a better location becomes available
        location = context.getLastLocation();
        event.setSignal(context.getPhoneState().getLastMMCSignal());
        event.setCell(context.getPhoneStateListener().getLastCellLocation());
        event.setServiceState(context.getPhoneState().getLastServiceStateObj());

        if (location != null && location.getTime() - 10000 > System.currentTimeMillis())
            event.setLocation(location, context.getLastNumSatellites());

        // Also, set the coverage flags at the time of the event
        int tier = context.getPhoneState().getNetworkGeneration();
        int servicestate = context.getPhoneState().getLastServiceState();
        int datastate = telephonyManager.getDataState();
        int activeConnection = PhoneState.ActiveConnection(context);
        if (activeConnection == 10)
            event.setFlag(EventObj.SERVICE_WIFI, true);
        else if (activeConnection == 11)
            event.setFlag(EventObj.SERVICE_WIMAX, true);
        ReportManager reportManager = ReportManager.getInstance(context);
        if (reportManager.manualPlottingEvent != null || event.getEventType() == EventType.MAN_PLOTTING)
            event.setFlag(EventObj.MANUAL_SAMPLES, true);

        if (datastate == TelephonyManager.DATA_CONNECTED || activeConnection > 1)
            event.setFlag(EventObj.SERVICE_DATA, true);
        else if (datastate == TelephonyManager.DATA_SUSPENDED && servicestate == ServiceState.STATE_IN_SERVICE) // not counted as data outage if data turned off
            event.setFlag(EventObj.SERVICE_DATA, true);
        else
            event.setFlag(EventObj.SERVICE_DATA, false);
        if (servicestate == ServiceState.STATE_OUT_OF_SERVICE
                || servicestate == ServiceState.STATE_EMERGENCY_ONLY)
            event.setFlag(EventObj.SERVICE_VOICE, false);
        else
            event.setFlag(EventObj.SERVICE_VOICE, true);
        if (tier > 2)
            event.setFlag(EventObj.SERVICE_3G, true);
        if (tier > 4)
            event.setFlag(EventObj.SERVICE_4G, true);
        if (context.getPhoneState().isCallConnected() || context.getPhoneState().isCallDialing()
                || event.getEventType().getIntValue() <= 6)
            event.setFlag(EventObj.PHONE_INUSE, true);

        // dropped call detection support using logcat or precise call state?
        if (event.getEventType().getIntValue() <= 7) {
            String pname = context.getPackageName();
            int permissionForReadLogs = context.getPackageManager()
                    .checkPermission(android.Manifest.permission.READ_LOGS, pname); //0 means allowed
            int permissionForPrecise = context.getPackageManager()
                    .checkPermission("android.permission.READ_PRECISE_PHONE_STATE", pname); // 0 means allowed
            if (permissionForPrecise == 0)
                event.setFlag(EventObj.CALL_PRECISE, true);
            else if (permissionForReadLogs == 0)
                event.setFlag(EventObj.CALL_LOGCAT, true);
        }

        event.setBattery(DeviceInfoOld.battery);
        if (event.getEventType() == EventType.COV_VOD_NO || event.getEventType() == EventType.COV_VOD_YES
                || event.getEventType() == EventType.COV_UPDATE
                || event.getEventType() == EventType.TRAVEL_CHECK) {
            long duration = 0;
            if (mLastServiceStateChangeTimeStamp != 0) {
                duration = System.currentTimeMillis() - mLastServiceStateChangeTimeStamp;
                mLastServiceStateChangeTimeStamp = System.currentTimeMillis();
                event.setDuration(duration);
            } else
                duration = mLastScreenOffDuration;

        }
        if (event.getEventType() == EventType.COV_3G_NO || event.getEventType() == EventType.COV_3G_YES
                || event.getEventType() == EventType.COV_UPDATE
                || event.getEventType() == EventType.TRAVEL_CHECK) {
            long duration = 0;
            if (mLast3GStateChangeTimeStamp != 0) {
                duration = System.currentTimeMillis() - mLast3GStateChangeTimeStamp;
                if (event.getEventType() == EventType.COV_UPDATE
                        || event.getEventType() == EventType.TRAVEL_CHECK)
                    event.setEventIndex(duration);
                else
                    event.setDuration(duration);
                mLast3GStateChangeTimeStamp = System.currentTimeMillis();
            }
        }
        //context.getCellHistory ().snapshotHistory();
        String conn = context.getConnectionHistory().updateConnectionHistory(telephonyManager.getNetworkType(),
                telephonyManager.getDataState(), telephonyManager.getDataActivity(),
                context.getPhoneState().getLastServiceStateObj(),
                context.getConnectivityManager().getActiveNetworkInfo());
        context.getIntentDispatcher().updateConnection(conn, true);

        WifiInfo wifiinfo = getWifiInfo();
        WifiConfiguration wifiConfig = getWifiConfig();
        event.setWifi(wifiinfo, wifiConfig);

        localReportEvent(event);
    } catch (Exception e) {
        LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "signalSnapshot", "error", e);
    }
}

From source file:org.restcomm.app.qoslib.Utils.QosInfo.java

public String getServiceStateName(int state) {
    String name = "";
    if (state >= 10) {
        name = "roam ";
        if (state == 10)
            return name;
        else//from   ww w .  j  ava 2s  . c o m
            state = state - 10;
    }
    switch (state) {
    case ServiceState.STATE_OUT_OF_SERVICE:
        name += "no service";
        break;
    case ServiceState.STATE_EMERGENCY_ONLY:
        name += "911 only";
        break;
    case PhoneState.SERVICE_STATE_AIRPLANE:
        name += "airplane";
        break;
    case ServiceState.STATE_IN_SERVICE:
        name += "in service";
        break;
    case ServiceState.STATE_POWER_OFF:
        name += "power off";
        break;
    }
    return name;
}

From source file:org.restcomm.app.qoslib.Services.LibPhoneStateListener.java

@Override
public void onServiceStateChanged(ServiceState serviceState) {
    super.onServiceStateChanged(serviceState);
    if (serviceState == null)
        return;//from   w ww .  j a va2s .  c  o m

    boolean isRoaming = serviceState.getRoaming();
    String operator = serviceState.getOperatorAlphaLong();
    String mccmnc = serviceState.getOperatorNumeric();

    //owner.getConnectionHistory().updateConnectionHistory(cellnettype, state, activity, networkInfo)
    try {
        String activity = owner.getConnectionHistory().updateConnectionHistory(
                telephonyManager.getNetworkType(), telephonyManager.getDataState(),
                telephonyManager.getDataActivity(), serviceState,
                owner.getConnectivityManager().getActiveNetworkInfo());
        if (activity != null)
            owner.getIntentDispatcher().updateConnection(activity, false);
    } catch (Exception e) {
        LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "onServiceStateChanged",
                "exception with updateConnectionHistory:", e);
    }

    //MMCLogger.logToFile(MMCLogger.Level.DEBUG, TAG, "onServiceStateChanged", String.format("State: %s, roaming: %s, operator: %s, mccmnc: %s",
    //         serviceState, isRoaming, operator, mccmnc));
    //MMCLogger.logToFile(MMCLogger.Level.DEBUG, TAG, "onServiceStateChanged", "Reflected: " + listServiceStateFields(serviceState));

    boolean wasRoaming = PreferenceManager.getDefaultSharedPreferences(owner)
            .getBoolean(PreferenceKeys.Miscellaneous.WAS_ROAMING, false);

    //If roaming, track time spend doing this         
    if (mPhoneState.isRoaming() != wasRoaming) {
        int roamValue = 2; //off
        String status = "off";
        if (mPhoneState.isRoaming()) {
            roamValue = 1; //on
            status = "on";
            //For DataMonitor tracking
            Intent intent = new Intent(IntentHandler.ROAMING_ON);
            owner.sendBroadcast(intent);
        } else {
            Intent intent = new Intent(IntentHandler.ROAMING_OFF);
            owner.sendBroadcast(intent);
        }
        LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onServiceStateChanged", "roaming status: " + status);
        owner.trackAccessPoints(roamValue);
        if (!EventObj.isDisabledEvent(owner, EventObj.DISABLE_ROAMUPDATE))
            owner.getEventManager().triggerUpdateEvent(false, false);
        PreferenceManager.getDefaultSharedPreferences(owner).edit()
                .putBoolean(PreferenceKeys.Miscellaneous.WAS_ROAMING, mPhoneState.isRoaming()).commit();
    }

    //If wimax, track time spend doing this
    if (PhoneState.ActiveConnection(owner) == 12) {
        Intent intent = new Intent(IntentHandler.WIMAX_STATE_CHANGE);
        owner.sendBroadcast(intent);
    }

    //in airplane mode
    if (isAirplaneModeOn(owner.getApplicationContext()) == true) {
        LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onServiceStateChanged", "airplane mode on");
        mPhoneState.previousServiceState = mPhoneState.SERVICE_STATE_AIRPLANE;
        try {
            SignalEx mmcSignal = new SignalEx();
            processNewMMCSignal(mmcSignal);
        } catch (Exception e) {
        }
        return;
    }

    if (serviceState.getState() == ServiceState.STATE_IN_SERVICE) {
        if (mPhoneState.previousServiceState != ServiceState.STATE_IN_SERVICE) {

            //state changed from OUT_OF_SERVICE to IN_SERVICE
            LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onServiceStateChanged",
                    "trigger regain service");
            owner.getEventManager().stopPhoneEvent(EventType.COV_VOD_NO, EventType.COV_VOD_YES);
            mPhoneState.mLastServiceStateChangeTimeStamp = System.currentTimeMillis();

        }
    } else if (serviceState.getState() == ServiceState.STATE_OUT_OF_SERVICE) {// || serviceState.getState() == ServiceState.STATE_EMERGENCY_ONLY) {
        if (mPhoneState.previousServiceState == mPhoneState.SERVICE_STATE_AIRPLANE)
            return; // discard 'no-service' occurring after exiting airplane mode

        if (mPhoneState.previousServiceState == ServiceState.STATE_IN_SERVICE) { // && previousServiceState != SERVICE_STATE_AIRPLANE) {

            mPhoneState.previousServiceState = serviceState.getState();
            SignalEx signal = mPhoneState.getLastMMCSignal();
            processNewMMCSignal(signal);

            // Outage needs to last longer than 5 seconds to actually trigger
            int delay = 5000;
            if (mPhoneState.isCallConnected()
                    || mPhoneState.disconnectTime + 12000 > System.currentTimeMillis())
                delay = 1; // If phone call is connected (or recently disconnected), no delay, dont ignore short outages
            owner.handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // If longer outage after 2 seconds, do nothing
                    if (mPhoneState.previousServiceState != ServiceState.STATE_OUT_OF_SERVICE) //  && previousServiceState != ServiceState.STATE_EMERGENCY_ONLY)
                    {
                        LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onServiceStateChanged",
                                "Outage lasted < 5 sec, ignoring");
                        return;
                    }
                    // Officially an outage now
                    // If service dropped straight from 3G to nothing, trigger a 3G outage as well
                    // If was connected to wifi when service was lost, does not count as a 3G outage
                    if (PhoneState.ActiveConnection(owner) <= 1 && mPhoneState.previousNetworkTier >= 3) // 10=Wifi, 11=Wimax, 12=Ethernet, 0=other
                    {
                        owner.getEventManager().startPhoneEvent(EventType.COV_3G_NO, EventType.COV_3G_YES);
                        if (mPhoneState.previousNetworkTier >= 5)
                            owner.getEventManager().startPhoneEvent(EventType.COV_4G_NO, EventType.COV_4G_YES);
                    }
                    mPhoneState.mLastServiceStateChangeTimeStamp = System.currentTimeMillis();

                    LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onServiceStateChanged",
                            "trigger lost service");
                    //state changed from IN_SERVICE to OUT_OF_SERVICE 
                    owner.getEventManager().startPhoneEvent(EventType.COV_VOD_NO, EventType.COV_VOD_YES);
                    if (mPhoneState.previousNetworkTier >= 2)
                        owner.getEventManager().startPhoneEvent(EventType.COV_DATA_NO, EventType.COV_DATA_YES);
                    SignalEx signal = mPhoneState.getLastMMCSignal();
                    processNewMMCSignal(signal);
                    mPhoneState.previousNetworkTier = 0;
                    //previousNetworkState = 0;
                }
            }, delay);

        }
    }
    mPhoneState.previousServiceState = serviceState.getState();
    mPhoneState.previousServiceStateObj = serviceState;

}