Example usage for android.telephony PhoneStateListener LISTEN_CALL_STATE

List of usage examples for android.telephony PhoneStateListener LISTEN_CALL_STATE

Introduction

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

Prototype

int LISTEN_CALL_STATE

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

Click Source Link

Document

Listen for changes to the device call state.

Usage

From source file:com.smedic.tubtub.BackgroundAudioService.java

private void initPhoneCallListener() {
    PhoneStateListener phoneStateListener = new PhoneStateListener() {
        @Override/*from  ww  w.j a  v a  2 s.  c om*/
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
            case TelephonyManager.CALL_STATE_RINGING:
                pauseVideo();
                break;
            case TelephonyManager.CALL_STATE_IDLE:
                resumeVideo();
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
            default:
                break;
            }

            super.onCallStateChanged(state, incomingNumber);
        }
    };

    TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    if (mgr != null) {
        mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    }
}

From source file:se.erichansander.retrotimer.TimerKlaxon.java

@Override
public void onCreate() {
    TinyTracelog.trace("3");

    mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

    // Listen for incoming calls to kill the alarm.
    mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

    if (android.os.Build.VERSION.SDK_INT >= 8) {
        mAudioFocusHelper = new AudioFocusHelper(this);
    } else {//w ww  . j a  v a2s  .com
        mAudioFocusHelper = null;
    }

    WakeLockHolder.acquireScreenCpuWakeLock(this);
}

From source file:ru.org.sevn.audiobookplayer.AppService.java

@Override
public void onCreate() {
    defaultIcon = BitmapFactory.decodeResource(getResources(), R.drawable.picture);
    defaultIcon = Util.getScaledImage(defaultIcon, ICON_SIZE, ICON_SIZE, Util.getImageFactor(getResources()));

    audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
    audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    super.onCreate();
    mp3Player.initialize();/*from ww  w  .j ava  2  s.c om*/
    restoreSettings();
    mp3Player.getMediaPlayer().addChangeStateListener(this);
    mp3Player.getAppSettings().addPropertyChangeListener(this);

    TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    if (mgr != null) {
        mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    }

    musicIntentReceiver = new MusicIntentReceiver();
    registerReceiver(musicIntentReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));

}

From source file:com.pandoroid.PandoraRadioService.java

@Override
public void onCreate() {
    m_paused = false;/*from www  .  j a va 2  s  . c o m*/
    m_pandora_remote = new PandoraRadio();
    image_downloader = new ImageDownloader();
    m_stations = new ArrayList<Station>();

    connectivity_manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    m_prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    // Register the listener with the telephony manager
    telephonyManager.listen(new PhoneStateListener() {
        boolean pausedForRing = false;

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {

            case TelephonyManager.CALL_STATE_IDLE:
                if (pausedForRing && m_song_playback != null) {
                    if (m_prefs.getBoolean("behave_resumeOnHangup", true)) {
                        if (m_song_playback != null && !m_paused) {
                            m_song_playback.play();
                        }
                    }
                }

                pausedForRing = false;
                break;

            case TelephonyManager.CALL_STATE_OFFHOOK:
            case TelephonyManager.CALL_STATE_RINGING:
                if (m_song_playback != null) {
                    m_song_playback.pause();
                }

                pausedForRing = true;
                break;
            }
        }
    }, PhoneStateListener.LISTEN_CALL_STATE);

    m_music_intent_receiver = new MusicIntentReceiver();
    this.registerReceiver(m_music_intent_receiver, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));
}

From source file:za.co.neilson.alarm.alert.AlarmAlertActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
            | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
    window.addFlags(/* w w  w.j av a2  s . c  o  m*/
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

    setContentView(R.layout.alarm_alert);

    Bundle bundle = this.getIntent().getExtras();
    alarm = (Alarm) bundle.getSerializable("alarm");

    sendNotification(this, alarm.getAlarmName(), alarm);

    this.setTitle(alarm.getAlarmName());

    switch (alarm.getDifficulty()) {
    case SUPEREASY:
        mathProblem = new MathProblem(1);
        break;
    case EASY:
        mathProblem = new MathProblem(3);
        break;
    case MEDIUM:
        mathProblem = new MathProblem(4);
        break;
    case HARD:
        mathProblem = new MathProblem(5);
        break;
    }

    answerString = String.valueOf(mathProblem.getAnswer());
    if (answerString.endsWith(".0")) {
        answerString = answerString.substring(0, answerString.length() - 2);
    }

    problemView = (TextView) findViewById(R.id.textView1);
    problemView.setText(mathProblem.toString());

    answerView = (TextView) findViewById(R.id.textView2);
    answerView.setText("= ?");

    ((Button) findViewById(R.id.Button0)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button1)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button2)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button3)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button4)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button5)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button6)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button7)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button8)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button9)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button_clear)).setOnClickListener(this);
    final AlarmAlertActivity foo = this;
    ((Button) findViewById(R.id.Button_alarm_off)).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            alarmActive = false; //Toast.makeText(getApplicationContext(),"off",Toast.LENGTH_SHORT).show();
            foo.finish();
        }
    });
    ((Button) findViewById(R.id.Button_decimal)).setOnClickListener(this);
    ((Button) findViewById(R.id.Button_minus)).setOnClickListener(this);

    TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);

    PhoneStateListener phoneStateListener = new PhoneStateListener() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
            case TelephonyManager.CALL_STATE_RINGING:
                Log.d(getClass().getSimpleName(), "Incoming call: " + incomingNumber);
                try {
                    mediaPlayer.pause();
                } catch (IllegalStateException e) {

                }
                break;
            case TelephonyManager.CALL_STATE_IDLE:
                Log.d(getClass().getSimpleName(), "Call State Idle");
                try {
                    mediaPlayer.start();
                } catch (IllegalStateException e) {

                }
                break;
            }
            super.onCallStateChanged(state, incomingNumber);
        }
    };

    telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

    // Toast.makeText(this, answerString, Toast.LENGTH_LONG).show();

    startAlarm();

}

From source file:chat.client.gui.ChatActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    myNum = tm.getLine1Number();/*from w w  w.j  av  a2 s  .c  o  m*/

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        nickname = extras.getString("nickname");
    }
    provider = LocationManager.GPS_PROVIDER;
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Location location = locationManager.getLastKnownLocation(provider);

    locationManager.requestLocationUpdates(provider, 0, 0, new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            // if (location != null)
            // updateWithNewLocation(location);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    });

    try {
        chatClientInterface = MicroRuntime.getAgent(nickname).getO2AInterface(ChatClientInterface.class);
    } catch (StaleProxyException e) {
        showAlertDialog(getString(R.string.msg_interface_exc), true);
    } catch (ControllerException e) {
        showAlertDialog(getString(R.string.msg_controller_exc), true);
    }

    myReceiver = new MyReceiver();

    IntentFilter refreshChatFilter = new IntentFilter();
    refreshChatFilter.addAction("jade.demo.chat.REFRESH_CHAT");
    registerReceiver(myReceiver, refreshChatFilter);

    IntentFilter clearChatFilter = new IntentFilter();
    clearChatFilter.addAction("jade.demo.chat.CLEAR_CHAT");
    registerReceiver(myReceiver, clearChatFilter);

    setContentView(R.layout.chat);

    Button button = (Button) findViewById(R.id.button_send);
    button.setOnClickListener(buttonSendListener);

    TelephonyManager mgr = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);

    listener = new PhoneCallListener();
    mgr.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);

}

From source file:se.team05.service.MediaService.java

/**
 * Called when the media player has been prepared and is ready to play. The
 * method then starts listening for phone state events and then starts
 * playing the media./*from  w  w w.ja  v  a  2s. co  m*/
 */
@Override
public void onPrepared(MediaPlayer player) {
    telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    playMedia();
}

From source file:com.andreadec.musicplayer.MusicService.java

/**
 * Called when the service is created./*from   w ww  .  j ava2s  . c om*/
 */
@Override
public void onCreate() {
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MusicServiceWakelock");

    // Initialize the telephony manager
    telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    phoneStateListener = new MusicPhoneStateListener();
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // Initialize pending intents
    quitPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.andreadec.musicplayer.quit"), 0);
    previousPendingIntent = PendingIntent.getBroadcast(this, 0,
            new Intent("com.andreadec.musicplayer.previous"), 0);
    playpausePendingIntent = PendingIntent.getBroadcast(this, 0,
            new Intent("com.andreadec.musicplayer.playpause"), 0);
    nextPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.andreadec.musicplayer.next"), 0);
    pendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP),
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Read saved user preferences
    preferences = PreferenceManager.getDefaultSharedPreferences(this);

    // Initialize the media player
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK); // Enable the wake lock to keep CPU running when the screen is switched off

    shuffle = preferences.getBoolean(Constants.PREFERENCE_SHUFFLE, Constants.DEFAULT_SHUFFLE);
    repeat = preferences.getBoolean(Constants.PREFERENCE_REPEAT, Constants.DEFAULT_REPEAT);
    repeatAll = preferences.getBoolean(Constants.PREFERENCE_REPEATALL, Constants.DEFAULT_REPEATALL);
    try { // This may fail if the device doesn't support bass boost
        bassBoost = new BassBoost(1, mediaPlayer.getAudioSessionId());
        bassBoost.setEnabled(
                preferences.getBoolean(Constants.PREFERENCE_BASSBOOST, Constants.DEFAULT_BASSBOOST));
        setBassBoostStrength(preferences.getInt(Constants.PREFERENCE_BASSBOOSTSTRENGTH,
                Constants.DEFAULT_BASSBOOSTSTRENGTH));
        bassBoostAvailable = true;
    } catch (Exception e) {
        bassBoostAvailable = false;
    }
    try { // This may fail if the device doesn't support equalizer
        equalizer = new Equalizer(1, mediaPlayer.getAudioSessionId());
        equalizer.setEnabled(
                preferences.getBoolean(Constants.PREFERENCE_EQUALIZER, Constants.DEFAULT_EQUALIZER));
        setEqualizerPreset(
                preferences.getInt(Constants.PREFERENCE_EQUALIZERPRESET, Constants.DEFAULT_EQUALIZERPRESET));
        equalizerAvailable = true;
    } catch (Exception e) {
        equalizerAvailable = false;
    }
    random = new Random(System.nanoTime()); // Necessary for song shuffle

    shakeListener = new ShakeListener(this);
    if (preferences.getBoolean(Constants.PREFERENCE_SHAKEENABLED, Constants.DEFAULT_SHAKEENABLED)) {
        shakeListener.enable();
    }

    telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); // Start listen for telephony events

    // Inizialize the audio manager
    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mediaButtonReceiverComponent = new ComponentName(getPackageName(), MediaButtonReceiver.class.getName());
    audioManager.registerMediaButtonEventReceiver(mediaButtonReceiverComponent);
    audioManager.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    // Initialize remote control client
    if (Build.VERSION.SDK_INT >= 14) {
        icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
        mediaButtonIntent.setComponent(mediaButtonReceiverComponent);
        PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
                mediaButtonIntent, 0);

        remoteControlClient = new RemoteControlClient(mediaPendingIntent);
        remoteControlClient.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE
                | RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS | RemoteControlClient.FLAG_KEY_MEDIA_NEXT);
        audioManager.registerRemoteControlClient(remoteControlClient);
    }

    updateNotificationMessage();

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("com.andreadec.musicplayer.quit");
    intentFilter.addAction("com.andreadec.musicplayer.previous");
    intentFilter.addAction("com.andreadec.musicplayer.previousNoRestart");
    intentFilter.addAction("com.andreadec.musicplayer.playpause");
    intentFilter.addAction("com.andreadec.musicplayer.next");
    intentFilter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("com.andreadec.musicplayer.quit")) {
                sendBroadcast(new Intent("com.andreadec.musicplayer.quitactivity"));
                stopSelf();
                return;
            } else if (action.equals("com.andreadec.musicplayer.previous")) {
                previousItem(false);
            } else if (action.equals("com.andreadec.musicplayer.previousNoRestart")) {
                previousItem(true);
            } else if (action.equals("com.andreadec.musicplayer.playpause")) {
                playPause();
            } else if (action.equals("com.andreadec.musicplayer.next")) {
                nextItem();
            } else if (action.equals(AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {
                if (preferences.getBoolean(Constants.PREFERENCE_STOPPLAYINGWHENHEADSETDISCONNECTED,
                        Constants.DEFAULT_STOPPLAYINGWHENHEADSETDISCONNECTED)) {
                    pause();
                }
            }
        }
    };
    registerReceiver(broadcastReceiver, intentFilter);

    if (!isPlaying()) {
        loadLastSong();
    }

    startForeground(Constants.NOTIFICATION_MAIN, notification);
}

From source file:sintef.android.gravity.AlarmFragment.java

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    if (getView() == null)
        return;//ww w  . java  2  s .c  o m

    ButterKnife.inject(this, getView());

    mAlarmView.setOnStopListener(new AlarmView.OnStopListener() {
        @Override
        public void onStop() {
            if (sVibrator != null)
                sVibrator.cancel();
            EventBus.getDefault().post(EventTypes.ALARM_STOPPED);
        }
    });
    mAlarmView.setOnAlarmListener(new AlarmView.OnAlarmListener() {
        @Override
        public void onAlarm() {

            EventBus.getDefault().post(EventTypes.STOP_ALARM);
            Log.w("Alarm", "notifying EMHT");
            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    try {
                        String data = "";
                        data += "type=fall&";
                        data += "callee.phoneNumber=" + getResources().getString(R.string.callee_phone_number)
                                + "&";
                        data += "callee.name=" + getResources().getString(R.string.callee_name) + "&";
                        data += "callee.address=" + getResources().getString(R.string.callee_address);
                        Log.w("Alarm", "postdata is: " + data);
                        URL url = new URL(getResources().getString(R.string.server_address) + "/alarm");
                        Log.w("Alarm", "emht server url is: " + url.toString());
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.setInstanceFollowRedirects(false);
                        connection.setRequestMethod("POST");
                        BufferedWriter bw = null;
                        try {
                            bw = new BufferedWriter(
                                    new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
                            bw.write(data);
                            bw.flush();
                        } finally {
                            if (bw != null)
                                bw.close();
                        }
                        Log.w("Alarm", "connection response code is: " + connection.getResponseCode());
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    return null;
                }
            }.execute();

            Log.w("Alarm", "calling nextofkin");
            sManager.listen(sPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
            sCallFromApp = true;

            Intent intent = new Intent(Intent.ACTION_CALL);
            intent.setData(
                    Uri.parse("tel:" + PreferencesHelper.getString(Constants.PREFS_NEXT_OF_KIN_TELEPHONE)));
            getActivity().startActivity(intent);
        }
    });

    EventBus.getDefault().register(this);

    boolean start_alarm = getArguments().getBoolean(AlarmService.ALARM_STARTED);

    if (start_alarm)
        mAlarmView.startAlarm();
}