1 /*** 2 * Ambient - A music player for the Android platform 3 Copyright (C) 2007 Martin Vysny 4 5 This program is free software: you can redistribute it and/or modify 6 it under the terms of the GNU General Public License as published by 7 the Free Software Foundation, either version 3 of the License, or 8 (at your option) any later version. 9 10 This program is distributed in the hope that it will be useful, 11 but WITHOUT ANY WARRANTY; without even the implied warranty of 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 GNU General Public License for more details. 14 15 You should have received a copy of the GNU General Public License 16 along with this program. If not, see <http://www.gnu.org/licenses/>. 17 */ 18 19 package sk.baka.ambient; 20 21 import sk.baka.ambient.playerservice.PlayerStateEnum; 22 import android.content.Context; 23 import android.telephony.PhoneStateListener; 24 import android.telephony.TelephonyManager; 25 26 /*** 27 * Handles the phone state events and reacts appropriately. 28 * 29 * @author Martin Vysny 30 */ 31 final class PhoneStateHandler extends PhoneStateListener { 32 33 /*** 34 * The phone state retrieval object. 35 */ 36 private final TelephonyManager manager; 37 38 /*** 39 * Creates new phone state handler. There should be at most one instance of 40 * the handler! 41 * 42 * @param context 43 * the context 44 */ 45 PhoneStateHandler(final AmbientApplication context) { 46 super(); 47 this.app = context; 48 manager = (TelephonyManager) context 49 .getSystemService(Context.TELEPHONY_SERVICE); 50 manager.listen(this, LISTEN_CALL_STATE); 51 } 52 53 private final AmbientApplication app; 54 55 @Override 56 public void onCallStateChanged(int state, String incomingNumber) { 57 super.onCallStateChanged(state, incomingNumber); 58 switch (state) { 59 case TelephonyManager.CALL_STATE_OFFHOOK: 60 case TelephonyManager.CALL_STATE_RINGING: 61 callInitiated(); 62 break; 63 case TelephonyManager.CALL_STATE_IDLE: 64 callTerminated(); 65 break; 66 } 67 } 68 69 /*** 70 * If <code>true</code> then the phone is active (ringing or picked up). 71 */ 72 private volatile boolean phoneActive = false; 73 74 /*** 75 * The call is initiated, pause the playback if needed. 76 */ 77 private void callInitiated() { 78 if (phoneActive) 79 return; 80 phoneActive = true; 81 prevState = app.getPlaylist().getPlaybackState(); 82 if (prevState == PlayerStateEnum.Playing) { 83 app.getPlaylist().pause(); 84 } 85 } 86 87 /*** 88 * The playback state when the phone was activated. 89 */ 90 private PlayerStateEnum prevState; 91 92 /*** 93 * The call has ended, resume the playback if it was paused before. 94 */ 95 private void callTerminated() { 96 if (!phoneActive) 97 return; 98 phoneActive = false; 99 if (prevState == PlayerStateEnum.Playing) { 100 app.getPlaylist().pause(); 101 } 102 } 103 }