Example usage for android.telephony ServiceState getState

List of usage examples for android.telephony ServiceState getState

Introduction

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

Prototype

public int getState() 

Source Link

Document

Get current voice service state

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;//  ww  w.  j  a v a 2  s.  c om

    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   w  ww.j a  v a 2s .c o  m
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.google.android.apps.mytracks.services.TrackRecordingService.java

@Override
public void onServiceStateChanged(ServiceState serviceState) {
    if (serviceState.getState() == serviceState.STATE_OUT_OF_SERVICE
            || serviceState.getState() == serviceState.STATE_POWER_OFF)
        gsmSignal = Constants.UNKNOWN_SIGNAL;

}

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

@Override
public void onServiceStateChanged(ServiceState serviceState) {
    super.onServiceStateChanged(serviceState);
    if (serviceState == null)
        return;//from   ww  w. j  ava 2 s. co 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;

}