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.cw.litenote.DrawerActivity.java

@Override
protected void onResume() {
    System.out.println("DrawerActivity / _onResume");

    // mDrawerActivity will be destroyed after adding note with a YouTube link,
    // so it is necessary to recreate activity
    //      if(Build.VERSION.SDK_INT >= 17)
    //      {//from   w  w  w  .j  av  a 2s.co  m
    //         if (mDrawerActivity.isDestroyed()) {
    //            System.out.println("DrawerActivity / _onResume / do recreate");//??? can run this?
    //            recreate();
    //         }
    //      }

    // To Registers a listener object to receive notification when incoming call
    TelephonyManager telMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    if (telMgr != null) {
        telMgr.listen(UtilAudio.phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    }
    super.onResume();
}

From source file:org.tomahawk.tomahawk_android.services.PlaybackService.java

@Override
public void onCreate() {
    super.onCreate();

    EventBus.getDefault().register(this);

    mMediaPlayers.add(VLCMediaPlayer.get());
    mMediaPlayers.add(DeezerMediaPlayer.get());
    mMediaPlayers.add(SpotifyMediaPlayer.get());
    mMediaPlayers.add(RdioMediaPlayer.get());

    startService(new Intent(this, MicroService.class));

    ServiceConnection connection = new ServiceConnection() {
        @Override//  w w  w .  j  a  v a  2 s .c  o  m
        public void onServiceConnected(ComponentName name, IBinder service) {
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        bindService(new Intent(this, RemoteControllerService.class), connection, Context.BIND_AUTO_CREATE);
    }

    mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);

    // Initialize PhoneCallListener
    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    telephonyManager.listen(mPhoneCallListener, PhoneStateListener.LISTEN_CALL_STATE);

    // Initialize WakeLock
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

    mMediaButtonReceiverComponent = new ComponentName(this, MediaButtonReceiver.class);
    mAudioFocusHelper = new AudioFocusHelper(getApplicationContext(), this);

    // Initialize killtime handler (watchdog style)
    mKillTimerHandler.removeCallbacksAndMessages(null);
    Message msg = mKillTimerHandler.obtainMessage();
    mKillTimerHandler.sendMessageDelayed(msg, DELAY_TO_KILL);

    mPlaylist = Playlist.fromEmptyList(TomahawkMainActivity.getLifetimeUniqueStringId(), false, "");
    mQueue = Playlist.fromEmptyList(TomahawkMainActivity.getLifetimeUniqueStringId(), false, "");
    Log.d(TAG, "PlaybackService has been created");
}

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.  j av a  2 s. com*/
        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:edu.umbc.cs.ebiquity.mithril.parserapp.contentparsers.contacts.ContactDetailFragment.java

/**
 * Builds a phone number LinearLayout based on phone number info from the Contacts Provider.
 * Each phone number gets its own LinearLayout object; for example, if the contact
 * has three phone numbers, then 3 LinearLayouts are generated.
 *
 * @param addressType From//  w w  w .j  a  v  a  2 s.c  o  m
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#TYPE}
 * @param addressTypeLabel From
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#LABEL}
 * @param address From
 * {@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#FORMATTED_ADDRESS}
 * @return A LinearLayout to add to the contact details layout,
 *         populated with the provided phone details.
 */
private LinearLayout buildPhoneLayout(String phoneNumber, int phoneType) {

    // Inflates the phone number layout
    final LinearLayout phoneLayout = (LinearLayout) LayoutInflater.from(getActivity())
            .inflate(R.layout.contact_phone_item, mPhoneLayout, false);

    // Gets handles to the view objects in the layout
    final TextView headerTextView = (TextView) phoneLayout.findViewById(R.id.contact_phone_header);
    final TextView phoneTextView = (TextView) phoneLayout.findViewById(R.id.contact_phone_item);
    final ImageButton dialNumberButton = (ImageButton) phoneLayout.findViewById(R.id.button_call_number);

    // If there's no phone number for the contact, shows the empty view and message, and hides the
    // header and button.
    if (phoneNumber == null && phoneType == 0) {
        headerTextView.setText("");
        dialNumberButton.setVisibility(View.GONE);
        phoneTextView.setText(R.string.no_address);
    } else {
        headerTextView.setText("Phone Number");
        phoneTextView.setText(phoneNumber);

        // add PhoneStateListener
        PhoneCallListener phoneListener = new PhoneCallListener();
        TelephonyManager telephonyManager = (TelephonyManager) getActivity()
                .getSystemService(Context.TELEPHONY_SERVICE);
        telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);

        // Defines an onClickListener object for the call number button
        dialNumberButton.setOnClickListener(new View.OnClickListener() {
            // Defines what to do when users click the address button
            @Override
            public void onClick(View view) {
                Intent dialIntent = null;
                if (!phoneTextView.equals("")) {
                    Uri number = Uri.parse("tel:" + phoneTextView.getText());
                    //                  Log.v(ParserApplication.getDebugTag(), "Calling the number: "+number.toString());
                    dialIntent = new Intent(Intent.ACTION_CALL, number);
                    startActivity(dialIntent);
                }
                // A PackageManager instance is needed to verify that there's a default app
                // that handles ACTION_VIEW and a geo Uri.
                final PackageManager packageManager = getActivity().getPackageManager();

                // Checks for an activity that can handle this intent. Preferred in this
                // case over Intent.createChooser() as it will still let the user choose
                // a default (or use a previously set default) for geo Uris.
                if (packageManager.resolveActivity(dialIntent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
                    startActivity(dialIntent);
                } else {
                    // If no default is found, displays a message that no activity can handle
                    // the view button.
                    Toast.makeText(getActivity(), R.string.no_intent_found, Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
    return phoneLayout;
}

From source file:com.xperia64.timidityae.MusicService.java

@Override
public void onCreate() {
    super.onCreate();
    if (serviceReceiver != null) {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(getResources().getString(R.string.msrv_rec));
        intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
        intentFilter.addAction(Intent.ACTION_MEDIA_BUTTON);
        registerReceiver(serviceReceiver, intentFilter);
    }//from   w  w  w  .  j  ava2 s. com
    pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Timidity AE");
    wl.setReferenceCounted(false);
    if (shouldDoWidget)
        ids = AppWidgetManager.getInstance(getApplication())
                .getAppWidgetIds(new ComponentName(getApplication(), TimidityAEWidgetProvider.class));

    TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    if (mgr != null) {
        mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
    }
    //foreground=false;
    if (wl.isHeld())
        wl.release();

    stopForeground(true);

}

From source file:org.mariotaku.harmony.MusicPlaybackService.java

/**
 * Starts playback of a previously opened file.
 *///from w  ww .  ja v  a 2s  .c  om
public void play() {
    final TrackInfo track = getTrackInfo();
    if (track == null)
        return;

    if (mTelephonyManager.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK)
        return;

    mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
    mAudioManager.registerMediaButtonEventReceiver(
            new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName()));

    mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

    if (mPlayer.isInitialized()) {
        // if we are at the end of the song, go to the next song first
        long duration = mPlayer.getDuration();
        if (mRepeatMode != REPEAT_MODE_CURRENT && duration > 2000 && mPlayer.getPosition() >= duration - 2000) {
            next(true);
        }

        mPlayer.start();

        // make sure we fade in, in case a previous fadein was stopped
        // because
        // of another focus loss
        mMediaplayerHandler.removeMessages(FADEDOWN);
        mMediaplayerHandler.sendEmptyMessage(FADEUP);

        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        final NotificationCompat.Style style = new NotificationCompat.BigPictureStyle();
        builder.setSmallIcon(R.drawable.ic_stat_playback);
        builder.setContentTitle(track.title);
        if (!TrackInfo.isUnknownArtist(track)) {
            builder.setContentText(track.artist);
        } else if (!TrackInfo.isUnknownAlbum(track)) {
            builder.setContentText(track.album);
        } else {
            builder.setContentText(getString(R.string.unknown_artist));
        }
        final AlbumInfo album = AlbumInfo.getAlbumInfo(this, track);
        builder.setLargeIcon(getAlbumArtForNotification(album != null ? album.album_art : null));
        builder.setStyle(style);
        builder.setOngoing(true);
        builder.setOnlyAlertOnce(true);
        builder.setWhen(0);
        builder.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(INTENT_PLAYBACK_VIEWER), 0));

        startForeground(ID_NOTIFICATION_PLAYBACK, builder.getNotification());

        if (!mIsSupposedToBePlaying) {
            mIsSupposedToBePlaying = true;
            notifyChange(BROADCAST_PLAY_STATE_CHANGED);
        }

    } else if (mPlayListLen <= 0) {
        // This is mostly so that if you press 'play' on a bluetooth headset
        // without every having played anything before, it will still play
        // something.
        setShuffleMode(SHUFFLE_MODE_ALL);
    }
}

From source file:com.rks.musicx.services.MusicXService.java

@Override
public void checkTelephonyState() {
    if (Extras.getInstance().getHeadset()) {
        telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if (telephonyManager != null) {
            telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        }//from  w w  w  .j ava2s  .  co  m
    }
}

From source file:com.csipsimple.service.SipService.java

/**
 * Register broadcast receivers.//from w w w  .  ja v a2 s. c o m
 */
private void registerBroadcasts() {
    // Register own broadcast receiver
    if (deviceStateReceiver == null) {
        IntentFilter intentfilter = new IntentFilter();
        intentfilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        intentfilter.addAction(SipManager.ACTION_SIP_ACCOUNT_CHANGED);
        intentfilter.addAction(SipManager.ACTION_SIP_ACCOUNT_DELETED);
        intentfilter.addAction(SipManager.ACTION_SIP_CAN_BE_STOPPED);
        intentfilter.addAction(SipManager.ACTION_SIP_REQUEST_RESTART);
        intentfilter.addAction(DynamicReceiver4.ACTION_VPN_CONNECTIVITY);
        if (Compatibility.isCompatible(5)) {
            deviceStateReceiver = new DynamicReceiver5(this);
        } else {
            deviceStateReceiver = new DynamicReceiver4(this);
        }
        registerReceiver(deviceStateReceiver, intentfilter);
        deviceStateReceiver.startMonitoring();
    }
    // Telephony
    if (phoneConnectivityReceiver == null) {
        Log.d(THIS_FILE, "Listen for phone state ");
        phoneConnectivityReceiver = new ServicePhoneStateReceiver();

        telephonyManager.listen(phoneConnectivityReceiver, /*PhoneStateListener.LISTEN_DATA_CONNECTION_STATE
                                                           | */PhoneStateListener.LISTEN_CALL_STATE);
    }
    // Content observer
    if (statusObserver == null) {
        statusObserver = new AccountStatusContentObserver(serviceHandler);
        getContentResolver().registerContentObserver(SipProfile.ACCOUNT_STATUS_URI, true, statusObserver);
    }

}

From source file:org.yammp.MusicPlaybackService.java

/**
 * Starts playback of a previously opened file.
 *//*from w  ww  . j a v  a 2s  .  c om*/
public void play() {

    CharSequence contentTitle, contentText = null;

    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    if (telephonyManager.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK)
        return;

    mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
    mAudioManager.registerMediaButtonEventReceiver(
            new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName()));

    telephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);

    if (mPlayer.isInitialized()) {
        // if we are at the end of the song, go to the next song first
        long duration = mPlayer.duration();
        if (mRepeatMode != REPEAT_CURRENT && duration > 2000 && mPlayer.position() >= duration - 2000) {
            next(true);
        }

        mPlayer.start();

        // make sure we fade in, in case a previous fadein was stopped
        // because
        // of another focus loss
        mMediaplayerHandler.removeMessages(FADEDOWN);
        mMediaplayerHandler.sendEmptyMessage(FADEUP);

        contentTitle = getTrackName();

        String artist = getArtistName();
        boolean isUnknownArtist = artist == null || MediaStore.UNKNOWN_STRING.equals(artist);

        String album = getAlbumName();
        boolean isUnknownAlbum = album == null || MediaStore.UNKNOWN_STRING.equals(album);

        if (!isUnknownArtist && !isUnknownAlbum) {
            contentText = getString(R.string.notification_artist_album, artist, album);
        } else if (isUnknownArtist && !isUnknownAlbum) {
            contentText = album;
        } else if (!isUnknownArtist && isUnknownAlbum) {
            contentText = artist;
        }

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(INTENT_PLAYBACK_VIEWER), 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setOngoing(true);
        builder.setSmallIcon(R.drawable.ic_stat_playback);
        builder.setContentIntent(contentIntent);
        builder.setContentTitle(contentTitle);
        builder.setContentText(contentText);
        mNotificationManager.notify(ID_NOTIFICATION_PLAYBACK, builder.getNotification());

        if (!mIsSupposedToBePlaying) {
            mIsSupposedToBePlaying = true;
            notifyChange(BROADCAST_PLAYSTATE_CHANGED);
        }

    } else if (mPlayListLen <= 0) {
        // This is mostly so that if you press 'play' on a bluetooth headset
        // without every having played anything before, it will still play
        // something.
        setShuffleMode(SHUFFLE_NORMAL);
    }
}

From source file:com.xperia64.timidityae.MusicService.java

public void updateNotification(String title, boolean paused) {
    //System.out.println("Updating notification");

    remoteViews = new RemoteViews(getPackageName(), R.layout.music_notification);
    remoteViews.setTextViewText(R.id.titley, currTitle);
    remoteViews.setImageViewResource(R.id.notPause,
            (paused) ? R.drawable.ic_media_play : R.drawable.ic_media_pause);
    // Previous/*  w  w  w.  ja v  a2  s.  c  o  m*/
    Intent new_intent = new Intent();
    //new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    new_intent.setAction(getResources().getString(R.string.msrv_rec));
    new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 4);
    PendingIntent pendingNotificationIntent = PendingIntent.getBroadcast(this, 1, new_intent, 0);
    remoteViews.setOnClickPendingIntent(R.id.notPrev, pendingNotificationIntent);
    // Play/Pause
    new_intent = new Intent();
    //new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    new_intent.setAction(getResources().getString(R.string.msrv_rec));
    new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 2);
    pendingNotificationIntent = PendingIntent.getBroadcast(this, 2, new_intent, 0);
    remoteViews.setOnClickPendingIntent(R.id.notPause, pendingNotificationIntent);
    // Next
    new_intent = new Intent();
    //new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    new_intent.setAction(getResources().getString(R.string.msrv_rec));
    new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 3);
    pendingNotificationIntent = PendingIntent.getBroadcast(this, 3, new_intent, 0);
    remoteViews.setOnClickPendingIntent(R.id.notNext, pendingNotificationIntent);
    // Stop
    new_intent = new Intent();
    //new_intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    new_intent.setAction(getResources().getString(R.string.msrv_rec));
    new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 5);
    pendingNotificationIntent = PendingIntent.getBroadcast(this, 4, new_intent, 0);
    remoteViews.setOnClickPendingIntent(R.id.notStop, pendingNotificationIntent);
    final Intent emptyIntent = new Intent(this, TimidityActivity.class);
    //emptyIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 5, emptyIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setContentTitle(getResources().getString(R.string.app_name)).setContentText(currTitle)
            .setContentIntent(pendingIntent).setContent(remoteViews);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        mBuilder.setSmallIcon(R.drawable.ic_lol);
    else
        mBuilder.setSmallIcon(R.drawable.ic_launcher);
    n = mBuilder.build();
    n.flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_ONGOING_EVENT;
    if (!foreground) {
        foreground = true;
        startForeground(13901858, n);
        if (!wl.isHeld())
            wl.acquire();

        TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if (mgr != null) {
            mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        }
    } else {
        if (!wl.isHeld())
            wl.acquire();
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(13901858, n);
    }
    if (shouldDoWidget) {
        Intent intent = new Intent(this, TimidityAEWidgetProvider.class);
        //Intent intent = new Intent("Ilikepotatoes");
        intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        // Use an array and EXTRA_APPWIDGET_IDS instead of AppWidgetManager.EXTRA_APPWIDGET_ID,
        // since it seems the onUpdate() is only fired on that:
        //intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
        intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.paused", paused);
        intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.title", currTitle);
        intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.onlyart", true);
        sendBroadcast(intent);
    }
}