Example usage for android.telephony TelephonyManager getCallState

List of usage examples for android.telephony TelephonyManager getCallState

Introduction

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

Prototype

public @CallState int getCallState() 

Source Link

Document

Returns the state of all calls on the device.

Usage

From source file:com.android.mms.transaction.MessagingNotification.java

/**
 * updateNotification is *the* main function for building the actual notification handed to
 * the NotificationManager//from w  w w . j  av a 2  s. co  m
 * @param context
 * @param newThreadId the new thread id
 * @param uniqueThreadCount
 * @param notificationSet the set of notifications to display
 */
private static void updateNotification(Context context, long newThreadId, int uniqueThreadCount,
        SortedSet<NotificationInfo> notificationSet) {
    boolean isNew = newThreadId != THREAD_NONE;
    CMConversationSettings conversationSettings = CMConversationSettings.getOrNew(context, newThreadId);

    // If the user has turned off notifications in settings, don't do any notifying.
    if ((isNew && !conversationSettings.getNotificationEnabled())
            || !MessagingPreferenceActivity.getNotificationEnabled(context)) {
        if (DEBUG) {
            Log.d(TAG, "updateNotification: notifications turned off in prefs, bailing");
        }
        return;
    }

    // Figure out what we've got -- whether all sms's, mms's, or a mixture of both.
    final int messageCount = notificationSet.size();
    NotificationInfo mostRecentNotification = notificationSet.first();

    final NotificationCompat.Builder noti = new NotificationCompat.Builder(context)
            .setWhen(mostRecentNotification.mTimeMillis);

    if (isNew) {
        noti.setTicker(mostRecentNotification.mTicker);
    }

    // If we have more than one unique thread, change the title (which would
    // normally be the contact who sent the message) to a generic one that
    // makes sense for multiple senders, and change the Intent to take the
    // user to the conversation list instead of the specific thread.

    // Cases:
    //   1) single message from single thread - intent goes to ComposeMessageActivity
    //   2) multiple messages from single thread - intent goes to ComposeMessageActivity
    //   3) messages from multiple threads - intent goes to ConversationList

    final Resources res = context.getResources();
    String title = null;
    Bitmap avatar = null;
    PendingIntent pendingIntent = null;
    boolean isMultiNewMessages = MessageUtils.isMailboxMode() ? messageCount > 1 : uniqueThreadCount > 1;
    if (isMultiNewMessages) { // messages from multiple threads
        Intent mainActivityIntent = getMultiThreadsViewIntent(context);
        pendingIntent = PendingIntent.getActivity(context, 0, mainActivityIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        title = context.getString(R.string.message_count_notification, messageCount);
    } else { // same thread, single or multiple messages
        title = mostRecentNotification.mTitle;
        avatar = mostRecentNotification.mSender.getAvatar(context);
        noti.setSubText(mostRecentNotification.mSimName); // no-op in single SIM case
        if (avatar != null) {
            // Show the sender's avatar as the big icon. Contact bitmaps are 96x96 so we
            // have to scale 'em up to 128x128 to fill the whole notification large icon.
            final int idealIconHeight = res
                    .getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
            final int idealIconWidth = res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width);
            noti.setLargeIcon(BitmapUtil.getRoundedBitmap(avatar, idealIconWidth, idealIconHeight));
        }

        pendingIntent = PendingIntent.getActivity(context, 0, mostRecentNotification.mClickIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    }
    // Always have to set the small icon or the notification is ignored
    noti.setSmallIcon(R.drawable.stat_notify_sms);

    NotificationManagerCompat nm = NotificationManagerCompat.from(context);

    // Update the notification.
    noti.setContentTitle(title).setContentIntent(pendingIntent)
            .setColor(context.getResources().getColor(R.color.mms_theme_color))
            .setCategory(Notification.CATEGORY_MESSAGE).setPriority(Notification.PRIORITY_DEFAULT); // TODO: set based on contact coming
                                                                                                                                                                                                                                  // from a favorite.

    // Tag notification with all senders.
    for (NotificationInfo info : notificationSet) {
        Uri peopleReferenceUri = info.mSender.getPeopleReferenceUri();
        if (peopleReferenceUri != null) {
            noti.addPerson(peopleReferenceUri.toString());
        }
    }

    int defaults = 0;

    if (isNew) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);

        if (conversationSettings.getVibrateEnabled()) {
            String pattern = conversationSettings.getVibratePattern();

            if (!TextUtils.isEmpty(pattern)) {
                noti.setVibrate(parseVibratePattern(pattern));
            } else {
                defaults |= Notification.DEFAULT_VIBRATE;
            }
        }

        String ringtoneStr = conversationSettings.getNotificationTone();
        noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr));
        Log.d(TAG, "updateNotification: new message, adding sound to the notification");
    }

    defaults |= Notification.DEFAULT_LIGHTS;

    noti.setDefaults(defaults);

    // set up delete intent
    noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0, sNotificationOnDeleteIntent, 0));

    // See if QuickMessage pop-up support is enabled in preferences
    boolean qmPopupEnabled = MessagingPreferenceActivity.getQuickMessageEnabled(context);

    // Set up the QuickMessage intent
    Intent qmIntent = null;
    if (mostRecentNotification.mIsSms) {
        // QuickMessage support is only for SMS
        qmIntent = new Intent();
        qmIntent.setClass(context, QuickMessagePopup.class);
        qmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP
                | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NAME_EXTRA, mostRecentNotification.mSender.getName());
        qmIntent.putExtra(QuickMessagePopup.SMS_FROM_NUMBER_EXTRA, mostRecentNotification.mSender.getNumber());
        qmIntent.putExtra(QuickMessagePopup.SMS_NOTIFICATION_OBJECT_EXTRA, mostRecentNotification);
    }

    // Start getting the notification ready
    final Notification notification;

    //Create a WearableExtender to add actions too
    WearableExtender wearableExtender = new WearableExtender();

    if (messageCount == 1 || uniqueThreadCount == 1) {
        // Add the Quick Reply action only if the pop-up won't be shown already
        if (!qmPopupEnabled && qmIntent != null) {

            // This is a QR, we should show the keyboard when the user taps to reply
            qmIntent.putExtra(QuickMessagePopup.QR_SHOW_KEYBOARD_EXTRA, true);

            // Create the pending intent and add it to the notification
            CharSequence qmText = context.getText(R.string.menu_reply);
            PendingIntent qmPendingIntent = PendingIntent.getActivity(context, 0, qmIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            noti.addAction(R.drawable.ic_reply, qmText, qmPendingIntent);

            //Wearable
            noti.extend(wearableExtender.addAction(
                    new NotificationCompat.Action.Builder(R.drawable.ic_reply, qmText, qmPendingIntent)
                            .build()));
        }

        // Add the 'Mark as read' action
        CharSequence markReadText = context.getText(R.string.qm_mark_read);
        Intent mrIntent = new Intent();
        mrIntent.setClass(context, QmMarkRead.class);
        mrIntent.putExtra(QmMarkRead.SMS_THREAD_ID, mostRecentNotification.mThreadId);
        PendingIntent mrPendingIntent = PendingIntent.getBroadcast(context, 0, mrIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        noti.addAction(R.drawable.ic_mark_read, markReadText, mrPendingIntent);

        // Add the Call action
        CharSequence callText = context.getText(R.string.menu_call);
        Intent callIntent = new Intent(Intent.ACTION_CALL);
        callIntent.setData(Uri.parse("tel:" + mostRecentNotification.mSender.getNumber()));
        PendingIntent callPendingIntent = PendingIntent.getActivity(context, 0, callIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        noti.addAction(R.drawable.ic_menu_call, callText, callPendingIntent);

        //Wearable
        noti.extend(wearableExtender.addAction(
                new NotificationCompat.Action.Builder(R.drawable.ic_menu_call, callText, callPendingIntent)
                        .build()));

        //Set up remote input
        String replyLabel = context.getString(R.string.qm_wear_voice_reply);
        RemoteInput remoteInput = new RemoteInput.Builder(QuickMessageWear.EXTRA_VOICE_REPLY)
                .setLabel(replyLabel).build();
        //Set up pending intent for voice reply
        Intent voiceReplyIntent = new Intent(context, QuickMessageWear.class);
        voiceReplyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP
                | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        voiceReplyIntent.putExtra(QuickMessageWear.SMS_CONATCT, mostRecentNotification.mSender.getName());
        voiceReplyIntent.putExtra(QuickMessageWear.SMS_SENDER, mostRecentNotification.mSender.getNumber());
        voiceReplyIntent.putExtra(QuickMessageWear.SMS_THEAD_ID, mostRecentNotification.mThreadId);
        PendingIntent voiceReplyPendingIntent = PendingIntent.getActivity(context, 0, voiceReplyIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        //Wearable voice reply action
        NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_reply,
                context.getString(R.string.qm_wear_reply_by_voice), voiceReplyPendingIntent)
                        .addRemoteInput(remoteInput).build();
        noti.extend(wearableExtender.addAction(action));
    }

    if (messageCount == 1) {
        // We've got a single message

        // This sets the text for the collapsed form:
        noti.setContentText(mostRecentNotification.formatBigMessage(context));

        if (mostRecentNotification.mAttachmentBitmap != null) {
            // The message has a picture, show that

            NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle(noti)
                    .bigPicture(mostRecentNotification.mAttachmentBitmap)
                    .setSummaryText(mostRecentNotification.formatPictureMessage(context));

            notification = noti.setStyle(bigPictureStyle).build();
        } else {
            // Show a single notification -- big style with the text of the whole message
            NotificationCompat.BigTextStyle bigTextStyle1 = new NotificationCompat.BigTextStyle(noti)
                    .bigText(mostRecentNotification.formatBigMessage(context));

            notification = noti.setStyle(bigTextStyle1).build();
        }
        if (DEBUG) {
            Log.d(TAG, "updateNotification: single message notification");
        }
    } else {
        // We've got multiple messages
        if (!isMultiNewMessages) {
            // We've got multiple messages for the same thread.
            // Starting with the oldest new message, display the full text of each message.
            // Begin a line for each subsequent message.
            SpannableStringBuilder buf = new SpannableStringBuilder();
            NotificationInfo infos[] = notificationSet.toArray(new NotificationInfo[messageCount]);
            int len = infos.length;
            for (int i = len - 1; i >= 0; i--) {
                NotificationInfo info = infos[i];

                buf.append(info.formatBigMessage(context));

                if (i != 0) {
                    buf.append('\n');
                }
            }

            noti.setContentText(context.getString(R.string.message_count_notification, messageCount));

            // Show a single notification -- big style with the text of all the messages
            NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
            bigTextStyle.bigText(buf)
                    // Forcibly show the last line, with the app's smallIcon in it, if we
                    // kicked the smallIcon out with an avatar bitmap
                    .setSummaryText((avatar == null) ? null : " ");
            notification = noti.setStyle(bigTextStyle).build();
            if (DEBUG) {
                Log.d(TAG, "updateNotification: multi messages for single thread");
            }
        } else {
            // Build a set of the most recent notification per threadId.
            HashSet<Long> uniqueThreads = new HashSet<Long>(messageCount);
            ArrayList<NotificationInfo> mostRecentNotifPerThread = new ArrayList<NotificationInfo>();
            Iterator<NotificationInfo> notifications = notificationSet.iterator();
            while (notifications.hasNext()) {
                NotificationInfo notificationInfo = notifications.next();
                if (!uniqueThreads.contains(notificationInfo.mThreadId)) {
                    uniqueThreads.add(notificationInfo.mThreadId);
                    mostRecentNotifPerThread.add(notificationInfo);
                }
            }
            // When collapsed, show all the senders like this:
            //     Fred Flinstone, Barry Manilow, Pete...
            noti.setContentText(formatSenders(context, mostRecentNotifPerThread));
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(noti);

            // We have to set the summary text to non-empty so the content text doesn't show
            // up when expanded.
            inboxStyle.setSummaryText(" ");

            // At this point we've got multiple messages in multiple threads. We only
            // want to show the most recent message per thread, which are in
            // mostRecentNotifPerThread.
            int uniqueThreadMessageCount = mostRecentNotifPerThread.size();
            int maxMessages = Math.min(MAX_MESSAGES_TO_SHOW, uniqueThreadMessageCount);

            for (int i = 0; i < maxMessages; i++) {
                NotificationInfo info = mostRecentNotifPerThread.get(i);
                inboxStyle.addLine(info.formatInboxMessage(context));
            }
            notification = inboxStyle.build();

            uniqueThreads.clear();
            mostRecentNotifPerThread.clear();

            if (DEBUG) {
                Log.d(TAG, "updateNotification: multi messages," + " showing inboxStyle notification");
            }
        }
    }

    notifyUserIfFullScreen(context, title);
    nm.notify(NOTIFICATION_ID, notification);

    // Trigger the QuickMessage pop-up activity if enabled
    // But don't show the QuickMessage if the user is in a call or the phone is ringing
    if (qmPopupEnabled && qmIntent != null) {
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (tm.getCallState() == TelephonyManager.CALL_STATE_IDLE && !ConversationList.mIsRunning
                && !ComposeMessageActivity.mIsRunning) {
            context.startActivity(qmIntent);
        }
    }
}

From source file:com.yangtsaosoftware.pebblemessenger.services.PebbleCenter.java

@Override
public void onCreate() {
    super.onCreate();
    Handler pebbleCenterHandler = new PebbleCenterHandler();
    mPebbleCenterHandler = new Messenger(pebbleCenterHandler);
    Constants.log(TAG_NAME, "Create PebbleCenter Messenger.");
    loadPref();//  w  w  w  .  j  a v a 2  s . c  o m
    _contex = this;
    //   busyBegin=new Time();
    //        waitQueue=new ArrayDeque<PebbleMessage>();
    sendQueue = new ArrayDeque<PebbleDictionary>();
    bindService(new Intent(this, MessageProcessingService.class), connToMessageProcessing,
            Context.BIND_AUTO_CREATE);
    Thread prepareThread = new PrepareThread();
    prepareThread.start();
    Thread sendMsgThread = new SendMsgThread();
    sendMsgThread.start();
    isPebbleEnable = PebbleKit.isWatchConnected(_contex);
    PebbleKit.registerReceivedDataHandler(_contex, new PebbleKit.PebbleDataReceiver(Constants.PEBBLE_UUID) {
        @Override
        public void receiveData(Context context, int transactionId, PebbleDictionary data) {
            PebbleKit.sendAckToPebble(_contex, transactionId);
            //          appStatue++;
            Constants.log(TAG_NAME, "Received data form pebble");
            switch (data.getUnsignedIntegerAsLong(ID_COMMAND).intValue()) {
            case REQUEST_TRANSID_CALL_TABLE: {
                Constants.log(TAG_NAME, "Request call table.");
                clean_SendQue();
                Message msg = Message.obtain();
                msg.what = MessageProcessingService.MSG_GET_CALL_TABLE;
                try {
                    rMessageProcessingHandler.send(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
                break;
            case REQUEST_TRANSID_MESSAGE_TABLE: {
                Constants.log(TAG_NAME, "Request message table.");
                clean_SendQue();
                Message msg = Message.obtain();
                msg.what = MessageProcessingService.MSG_GET_MESSAGE_TABLE;
                try {
                    rMessageProcessingHandler.send(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
                break;
            case REQUEST_TRANSID_CALL: {
                clean_SendQue();
                Message msg = Message.obtain();
                msg.what = MessageProcessingService.MSG_GET_CALL;
                Bundle b = new Bundle();
                b.putString(MessageDbHandler.COL_CALL_ID, data.getString(ID_EXTRA_DATA));
                Constants.log(TAG_NAME, "Request call id:" + data.getString(ID_EXTRA_DATA));

                msg.setData(b);
                try {
                    rMessageProcessingHandler.send(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

            }
                break;
            case REQUEST_TRANSID_MESSAGE:
                clean_SendQue();
                Message msg = Message.obtain();
                msg.what = MessageProcessingService.MSG_GET_MESSAGE;
                Bundle b = new Bundle();
                b.putString(MessageDbHandler.COL_MESSAGE_ID, data.getString(ID_EXTRA_DATA));
                Constants.log(TAG_NAME, "Request message id:" + data.getString(ID_EXTRA_DATA));

                msg.setData(b);
                try {
                    rMessageProcessingHandler.send(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
            case REQUEST_TRANSID_PICKUP_PHONE:
                TelephonyManager telMag = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                Constants.log("Receivephone", "Receive phone:" + data.getString(ID_EXTRA_DATA2));
                if (telMag.getCallState() == TelephonyManager.CALL_STATE_RINGING) {
                    switch (data.getUnsignedIntegerAsLong(ID_EXTRA_DATA).intValue()) {
                    case REQUEST_EXTRA_SPEAKER_ON:
                        answerCall(true);
                        break;
                    case REQUEST_EXTRA_SPEAKER_OFF:
                        answerCall(false);
                        break;
                    }
                } else {
                    switch (data.getUnsignedIntegerAsLong(ID_EXTRA_DATA).intValue()) {
                    case REQUEST_EXTRA_SPEAKER_ON:
                        dialNumber(data.getString(ID_EXTRA_DATA2), true);
                        break;
                    case REQUEST_EXTRA_SPEAKER_OFF:
                        dialNumber(data.getString(ID_EXTRA_DATA2), false);
                        break;
                    }

                }
                //                pebbleBusy = false;
                break;
            case REQUEST_TRANSID_HANGOFF_PHONE:
                endCall();
                //                pebbleBusy=false;

                break;
            case REQUEST_TRANSID_HANGOFF_SMS1:
                Constants.log(TAG_NAME, "Request hangoff and send sms1");

                endCall();
                doSendSMSTo(data.getString(ID_EXTRA_DATA), sms1);
                //               pebbleBusy=false;

                break;
            case REQUEST_TRANSID_HANGOFF_SMS2:
                Constants.log(TAG_NAME, "Request hangoff and send sms2");

                endCall();
                doSendSMSTo(data.getString(ID_EXTRA_DATA), sms2);
                //              pebbleBusy=false;

                break;
            case REQUEST_TRANSID_CLOSE_APP:
                Constants.log(TAG_NAME, "Request close app command.");
                sendMsgThreadHandler.sendEmptyMessage(SEND_CLOSE_APP);
                //               need_delay=true;

                break;
            case REQUEST_TRANSID_NEXTPAGE:
                Constants.log(TAG_NAME, "Request send next page.");

                sendMsgThreadHandler.sendEmptyMessage(SEND_NEXT_PAGE);
                break;
            case REQUEST_TRANSID_READ_NOTIFY: {
                Constants.log(TAG_NAME, "Request  read msg");
                Message read_msg = Message.obtain();
                read_msg.what = MessageProcessingService.MSG_READ;
                Bundle bd = new Bundle();
                bd.putString(MessageDbHandler.COL_MESSAGE_ID,
                        data.getUnsignedIntegerAsLong(ID_EXTRA_DATA).toString());
                read_msg.setData(bd);
                try {
                    rMessageProcessingHandler.send(read_msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
                break;
            case REQUEST_TRANSID_IM_FREE:
                Constants.log(TAG_NAME, "Request pebble app is free to receive data.");

                //               need_delay = data.getUnsignedInteger(ID_EXTRA_DATA).intValue() == REQUEST_EXTRA_DELAY_ON ;
                //               clean_SendQue();
                break;
            case REQUEST_TRANSID_VERSION: {
                send_test_get_return = true;
                String result = data.getString(ID_EXTRA_DATA);
                Constants.log("PmpVersion", result);
                StringTokenizer tokens = new StringTokenizer(result, ".");

                Intent inner_intent = new Intent(SetupFragment.class.getName());
                inner_intent.putExtra(Constants.BROADCAST_VERSION,
                        new byte[] { Byte.parseByte(tokens.nextToken()), Byte.parseByte(tokens.nextToken()),
                                Byte.parseByte(tokens.nextToken()) });
                LocalBroadcastManager.getInstance(context).sendBroadcast(inner_intent);
                sendMsgThreadHandler.sendEmptyMessage(SEND_CLOSE_APP);
                break;
            }
            }
        }
    });

    PebbleKit.registerReceivedAckHandler(_contex, new PebbleKit.PebbleAckReceiver(Constants.PEBBLE_UUID) {
        @Override
        public void receiveAck(Context context, int transactionId) {
            Constants.log(TAG_NAME, "Get a receiveAck:" + String.valueOf(transactionId));
            switch (transactionId) {
            case TRANS_ID_COMMON:
                Constants.log(TAG_NAME, "Send continue...");
                //                  pebbleBusy=true;
                sendMsgThreadHandler.sendEmptyMessage(SEND_CONTINUE);
                break;
            case TRANS_ID_END:
                send_full_page = true;
                break;
            case TRANS_ID_EMPTY:
                //                 pebbleBusy=true;
                sendMsgThreadHandler.sendEmptyMessage(SEND_CONTINUE);
                break;
            case TRANS_ID_TEST: {
                break;
            }
            }
        }
    });

    PebbleKit.registerReceivedNackHandler(_contex, new PebbleKit.PebbleNackReceiver(Constants.PEBBLE_UUID) {
        @Override
        public void receiveNack(Context context, int transactionId) {
            Constants.log(TAG_NAME, "Get a receivedNack:" + String.valueOf(transactionId));
            if (PebbleKit.isWatchConnected(_contex)) {
                switch (transactionId) {
                case TRANS_ID_COMMON:
                    sendMsgThreadHandler.sendEmptyMessage(SEND_CONTINUE);
                    break;
                case TRANS_ID_END:
                    send_full_page = true;
                    break;
                case TRANS_ID_EMPTY:
                    //                   appStatue=0;
                    sendMsgThreadHandler.sendEmptyMessage(SEND_OPEN_APP);
                    break;
                case TRANS_ID_TEST: {
                    Intent inner_intent = new Intent(SetupFragment.class.getName());
                    inner_intent.putExtra(Constants.BROADCAST_VERSION, new byte[] { 0, 0, 0 });
                    LocalBroadcastManager.getInstance(context).sendBroadcast(inner_intent);
                }
                }
            } else {
                sendMsgThreadHandler.sendEmptyMessage(SEND_CLOSE_APP);
            }

        }
    });

    PebbleKit.registerPebbleConnectedReceiver(_contex, new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            isPebbleEnable = true;
        }
    });

    PebbleKit.registerPebbleDisconnectedReceiver(_contex, new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            isPebbleEnable = false;
            sendMsgThreadHandler.sendEmptyMessage(SEND_CLOSE_APP);
        }
    });

    BroadcastReceiver br = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int command = intent.getIntExtra(Constants.BROADCAST_COMMAND, Constants.BROADCAST_PREFER_CHANGED);

            switch (command) {
            case Constants.BROADCAST_PREFER_CHANGED:
                loadPref();
                break;
            case Constants.BROADCAST_CALL_IDLE:
                if (callEnable) {
                    sendMsgThreadHandler.sendEmptyMessage(SEND_CALL_END);
                }
                break;
            case Constants.BROADCAST_CALL_HOOK:
                if (callEnable) {
                    sendMsgThreadHandler.sendEmptyMessage(SEND_CALL_HOOK);
                }
                break;
            case Constants.BROADCAST_PEBBLE_TEST:
                if (isPebbleEnable) {
                    prepareThreadHandler.sendEmptyMessage(PREPARE_TEST);
                }
                break;
            }
        }
    };
    IntentFilter intentFilter = new IntentFilter(PebbleCenter.class.getName());
    LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(br, intentFilter);
}

From source file:org.yammp.MusicPlaybackService.java

/**
 * Starts playback of a previously opened file.
 *//* w w w.ja v  a  2s  .c o m*/
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.android.mms.ui.ComposeMessageActivity.java

@Override
protected void onResume() {
    super.onResume();

    // OLD: get notified of presence updates to update the titlebar.
    // NEW: we are using ContactHeaderWidget which displays presence, but updating presence
    //      there is out of our control.
    //Contact.startPresenceObserver();

    addRecipientsListeners();//w ww  .ja  v  a 2  s  .c o m

    if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
        log("update title, mConversation=" + mConversation.toString());
    }

    // There seems to be a bug in the framework such that setting the title
    // here gets overwritten to the original title.  Do this delayed as a
    // workaround.
    mMessageListItemHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            ContactList recipients = isRecipientsEditorVisible()
                    ? mRecipientsEditor.constructContactsFromInput(false)
                    : getRecipients();
            updateTitle(recipients);
        }
    }, 100);

    // Load the selected input type
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences((Context) ComposeMessageActivity.this);
    mInputMethod = Integer.parseInt(prefs.getString(MessagingPreferenceActivity.INPUT_TYPE,
            Integer.toString(InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE)));
    mTextEditor.setInputType(InputType.TYPE_CLASS_TEXT | mInputMethod | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT
            | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES | InputType.TYPE_TEXT_FLAG_MULTI_LINE);

    TelephonyManager tm = (TelephonyManager) getSystemService(Service.TELEPHONY_SERVICE);
    if (MessagingPreferenceActivity.getSmartCallEnabled((Context) ComposeMessageActivity.this)
            && tm.getCallState() == TelephonyManager.CALL_STATE_IDLE) {
        mMultiSensorManager.enable();
    }

    mIsRunning = true;
    updateThreadIdIfRunning();
    mConversation.markAsRead(true);
}