Example usage for android.telephony PhoneStateListener PhoneStateListener

List of usage examples for android.telephony PhoneStateListener PhoneStateListener

Introduction

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

Prototype

public PhoneStateListener() 

Source Link

Document

Create a PhoneStateListener for the Phone with the default subscription.

Usage

From source file:net.sf.asap.PlayerService.java

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);

    registerReceiver(headsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
    registerMediaButtonEventReceiver("registerMediaButtonEventReceiver");

    TelephonyManager telephony = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    telephony.listen(new PhoneStateListener() {
        public void onCallStateChanged(int state, String incomingNumber) {
            if (state == TelephonyManager.CALL_STATE_RINGING)
                pause();/*from   w w  w  .j a  v  a2 s .c o  m*/
        }
    }, PhoneStateListener.LISTEN_CALL_STATE);

    Uri uri = intent.getData();
    String playlistUri = intent.getStringExtra(EXTRA_PLAYLIST);
    if (playlistUri != null)
        setPlaylist(Uri.parse(playlistUri), false);
    else if ("file".equals(uri.getScheme())) {
        if (ASAPInfo.isOurFile(uri.toString()))
            setPlaylist(Util.getParent(uri), false);
        else {
            setPlaylist(uri, true);
            uri = playlist.get(0);
        }
    }
    playFile(uri, SONG_DEFAULT);
}

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

/**
 * Updates Neighbouring Cell details/*from   w  w w  .  jav a  2  s. co  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:org.pixmob.freemobile.netstat.MonitorService.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override/* ww  w . j a  v a  2 s  .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:leoisasmendi.android.com.suricatepodcast.services.MediaPlayerService.java

private void callStateListener() {
    // Get the telephony manager
    telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    //Starting listening for PhoneState changes
    phoneStateListener = new PhoneStateListener() {
        @Override//  w  w w .ja  va  2 s  .c  om
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
            //if at least one call exists or the phone is ringing
            //pause the MediaPlayer
            case TelephonyManager.CALL_STATE_OFFHOOK:
            case TelephonyManager.CALL_STATE_RINGING:
                if (mediaPlayer != null) {
                    pauseMedia();
                    ongoingCall = true;
                }
                break;
            case TelephonyManager.CALL_STATE_IDLE:
                // Phone idle. Start playing.
                if (mediaPlayer != null) {
                    if (ongoingCall) {
                        ongoingCall = false;
                        resumeMedia();
                    }
                }
                break;
            }
        }
    };
    // Register the listener with the telephony manager
    // Listen for changes to the device call state.
    telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}

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

/**
 * Start FemtoCell detection tracking (For CDMA Devices ONLY!)
 *///w w  w. ja  va2  s  . c om
public void startTrackingFemto() {

    /* Check if it is a CDMA phone */
    if (device.getPhoneId() != TelephonyManager.PHONE_TYPE_CDMA) {
        Helpers.msgShort(context, context.getString(R.string.femtocell_only_on_cdma_devices));
        return;
    }

    trackingFemtocell = true;
    mPhoneStateListener = new PhoneStateListener() {
        public void onServiceStateChanged(ServiceState s) {
            log.debug(context.getString(R.string.service_state_changed));
            getServiceStateInfo(s);
        }
    };
    tm.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CELL_LOCATION);
    tm.listen(mPhoneStateListener, PhoneStateListener.LISTEN_SERVICE_STATE);
    setNotification();
}

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

/**
 * Start FemtoCell detection tracking//from   ww  w. j  a  va2  s .c o  m
 * CDMA Devices ONLY
 */
public void startTrackingFemto() {

    /* Check if it is a CDMA phone */
    if (mDevice.getPhoneID() != TelephonyManager.PHONE_TYPE_CDMA) {
        Helpers.msgShort(this, "AIMSICD can only detect Femtocell connections on CDMA devices.");
        return;
    }

    mTrackingFemtocell = true;
    mPhoneStateListener = new PhoneStateListener() {
        public void onServiceStateChanged(ServiceState s) {
            Log.d(TAG, "Service State changed!");
            getServiceStateInfo(s);
        }
    };
    tm.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CELL_LOCATION);
    tm.listen(mPhoneStateListener, PhoneStateListener.LISTEN_SERVICE_STATE);
    setNotification();
}