Example usage for android.media MediaPlayer setAudioStreamType

List of usage examples for android.media MediaPlayer setAudioStreamType

Introduction

In this page you can find the example usage for android.media MediaPlayer setAudioStreamType.

Prototype

public void setAudioStreamType(int streamtype) 

Source Link

Document

Sets the audio stream type for this MediaPlayer.

Usage

From source file:mp.teardrop.PlaybackService.java

/**
 * Returns a new MediaPlayer object/*from w  w  w.  ja v a  2s.  co m*/
 */
private MediaPlayer getNewMediaPlayer() {
    MediaPlayer mp = new MediaPlayer();
    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mp.setOnCompletionListener(this);
    mp.setOnErrorListener(this);
    mp.setOnPreparedListener(this);
    return mp;
}

From source file:org.kontalk.ui.AbstractComposeFragment.java

private boolean prepareAudio(File audioFile, final AudioContentViewControl view, final long messageId) {
    stopMediaPlayerUpdater();//  w ww.j  a  va  2  s. c  o  m
    try {
        AudioFragment audio = getAudioFragment();
        final MediaPlayer player = audio.getPlayer();
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.setDataSource(audioFile.getAbsolutePath());
        player.prepare();

        // prepare was successful
        audio.setMessageId(messageId);
        mAudioControl = view;

        view.prepare(player.getDuration());
        player.seekTo(view.getPosition());
        view.setProgressChangeListener(true);
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                stopMediaPlayerUpdater();
                view.end();
                AudioFragment audio = getAudioFragment();
                if (audio != null) {
                    // this is mainly to get the wake lock released
                    audio.pausePlaying();
                    audio.seekPlayerTo(0);
                }
                setAudioStatus(AudioContentView.STATUS_ENDED);
            }
        });
        return true;
    } catch (IOException e) {
        Toast.makeText(getActivity(), R.string.err_file_not_found, Toast.LENGTH_SHORT).show();
        return false;
    }
}

From source file:github.daneren2005.dsub.service.DownloadServiceImpl.java

private synchronized void doPlay(final DownloadFile downloadFile, final int position, final boolean start) {
    try {/*ww  w.  ja  v  a  2  s  .  com*/
        downloadFile.setPlaying(true);
        final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                : downloadFile.getPartialFile();
        isPartial = file.equals(downloadFile.getPartialFile());
        downloadFile.updateModificationDate();

        mediaPlayer.setOnCompletionListener(null);
        mediaPlayer.reset();
        setPlayerState(IDLE);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        String dataSource = file.getPath();
        if (isPartial) {
            if (proxy == null) {
                proxy = new StreamProxy(this);
                proxy.start();
            }
            dataSource = String.format("http://127.0.0.1:%d/%s", proxy.getPort(),
                    URLEncoder.encode(dataSource, Constants.UTF_8));
            Log.i(TAG, "Data Source: " + dataSource);
        } else if (proxy != null) {
            proxy.stop();
            proxy = null;
        }
        mediaPlayer.setDataSource(dataSource);
        setPlayerState(PREPARING);

        mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                Log.i(TAG, "Buffered " + percent + "%");
                if (percent == 100) {
                    mediaPlayer.setOnBufferingUpdateListener(null);
                }
            }
        });

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mediaPlayer) {
                try {
                    setPlayerState(PREPARED);

                    synchronized (DownloadServiceImpl.this) {
                        if (position != 0) {
                            Log.i(TAG, "Restarting player from position " + position);
                            mediaPlayer.seekTo(position);
                        }
                        cachedPosition = position;

                        if (start) {
                            mediaPlayer.start();
                            setPlayerState(STARTED);
                        } else {
                            setPlayerState(PAUSED);
                        }
                    }

                    lifecycleSupport.serializeDownloadQueue();
                } catch (Exception x) {
                    handleError(x);
                }
            }
        });

        setupHandlers(downloadFile, isPartial);

        mediaPlayer.prepareAsync();
    } catch (Exception x) {
        handleError(x);
    }
}

From source file:org.kontalk.ui.ComposeMessageFragment.java

private boolean prepareAudio(File audioFile, final AudioContentViewControl view, final long messageId) {
    stopMediaPlayerUpdater();/*from  w w  w. j av a 2  s.  co  m*/
    try {
        AudioFragment audio = getAudioFragment();
        final MediaPlayer player = audio.getPlayer();
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.setDataSource(audioFile.getAbsolutePath());
        player.prepare();

        // prepare was successful
        audio.setMessageId(messageId);
        mAudioControl = view;

        view.prepare(player.getDuration());
        player.seekTo(view.getPosition());
        view.setProgressChangeListener(true);
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                stopMediaPlayerUpdater();
                view.end();
                AudioFragment audio = findAudioFragment();
                if (audio != null)
                    audio.seekPlayerTo(0);
                setAudioStatus(AudioContentView.STATUS_ENDED);
            }
        });
        return true;
    } catch (IOException e) {
        Toast.makeText(getActivity(), R.string.err_file_not_found, Toast.LENGTH_SHORT).show();
        return false;
    }
}

From source file:github.daneren2005.dsub.service.DownloadService.java

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

    final SharedPreferences prefs = Util.getPreferences(this);
    new Thread(new Runnable() {
        public void run() {
            Looper.prepare();/* w  ww .  j av a  2  s.c  o  m*/

            mediaPlayer = new MediaPlayer();
            mediaPlayer.setWakeMode(DownloadService.this, PowerManager.PARTIAL_WAKE_LOCK);

            audioSessionId = -1;
            Integer id = prefs.getInt(Constants.CACHE_AUDIO_SESSION_ID, -1);
            if (id != -1) {
                try {
                    audioSessionId = id;
                    mediaPlayer.setAudioSessionId(audioSessionId);
                } catch (Throwable e) {
                    audioSessionId = -1;
                }
            }

            if (audioSessionId == -1) {
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    audioSessionId = mediaPlayer.getAudioSessionId();
                    prefs.edit().putInt(Constants.CACHE_AUDIO_SESSION_ID, audioSessionId).commit();
                } catch (Throwable t) {
                    // Froyo or lower
                }
            }

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
                    handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")"));
                    return false;
                }
            });

            try {
                Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
                i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, audioSessionId);
                i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
                sendBroadcast(i);
            } catch (Throwable e) {
                // Froyo or lower
            }

            effectsController = new AudioEffectsController(DownloadService.this, audioSessionId);
            if (prefs.getBoolean(Constants.PREFERENCES_EQUALIZER_ON, false)) {
                getEqualizerController();
            }

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);

            if (runListenersOnInit) {
                onSongsChanged();
                onSongProgress();
                onStateUpdate();
            }

            Looper.loop();
        }
    }, "DownloadService").start();

    Util.registerMediaButtonEventReceiver(this);

    if (mRemoteControl == null) {
        // Use the remote control APIs (if available) to set the playback state
        mRemoteControl = RemoteControlClientHelper.createInstance();
        ComponentName mediaButtonReceiverComponent = new ComponentName(getPackageName(),
                MediaButtonIntentReceiver.class.getName());
        mRemoteControl.register(this, mediaButtonReceiverComponent);
    }

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    wakeLock.setReferenceCounted(false);

    try {
        timerDuration = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_SLEEP_TIMER_DURATION, "5"));
    } catch (Throwable e) {
        timerDuration = 5;
    }
    sleepTimer = null;

    keepScreenOn = prefs.getBoolean(Constants.PREFERENCES_KEY_KEEP_SCREEN_ON, false);

    mediaRouter = new MediaRouteManager(this);

    instance = this;
    shufflePlayBuffer = new ShufflePlayBuffer(this);
    artistRadioBuffer = new ArtistRadioBuffer(this);
    lifecycleSupport.onCreate();
}

From source file:github.daneren2005.dsub.service.DownloadService.java

private synchronized void doPlay(final DownloadFile downloadFile, final int position, final boolean start) {
    try {// ww  w. j  a  v  a2 s  .co m
        downloadFile.setPlaying(true);
        final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                : downloadFile.getPartialFile();
        boolean isPartial = file.equals(downloadFile.getPartialFile());
        downloadFile.updateModificationDate();

        subtractPosition = 0;
        mediaPlayer.setOnCompletionListener(null);
        mediaPlayer.setOnPreparedListener(null);
        mediaPlayer.setOnErrorListener(null);
        mediaPlayer.reset();
        setPlayerState(IDLE);
        try {
            mediaPlayer.setAudioSessionId(audioSessionId);
        } catch (Throwable e) {
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        }
        String dataSource = file.getAbsolutePath();
        if (isPartial && !Util.isOffline(this)) {
            if (proxy == null) {
                proxy = new BufferProxy(this);
                proxy.start();
            }
            proxy.setBufferFile(downloadFile);
            dataSource = proxy.getPrivateAddress(dataSource);
            Log.i(TAG, "Data Source: " + dataSource);
        } else if (proxy != null) {
            proxy.stop();
            proxy = null;
        }
        mediaPlayer.setDataSource(dataSource);
        setPlayerState(PREPARING);

        mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                Log.i(TAG, "Buffered " + percent + "%");
                if (percent == 100) {
                    mediaPlayer.setOnBufferingUpdateListener(null);
                }
            }
        });

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mediaPlayer) {
                try {
                    setPlayerState(PREPARED);

                    synchronized (DownloadService.this) {
                        if (position != 0) {
                            Log.i(TAG, "Restarting player from position " + position);
                            mediaPlayer.seekTo(position);
                        }
                        cachedPosition = position;

                        applyReplayGain(mediaPlayer, downloadFile);

                        if (start || autoPlayStart) {
                            mediaPlayer.start();
                            setPlayerState(STARTED);

                            // Disable autoPlayStart after done
                            autoPlayStart = false;
                        } else {
                            setPlayerState(PAUSED);
                            onSongProgress();
                        }
                    }

                    // Only call when starting, setPlayerState(PAUSED) already calls this
                    if (start) {
                        lifecycleSupport.serializeDownloadQueue();
                    }
                } catch (Exception x) {
                    handleError(x);
                }
            }
        });

        setupHandlers(downloadFile, isPartial, start);

        mediaPlayer.prepareAsync();
    } catch (Exception x) {
        handleError(x);
    }
}

From source file:github.popeen.dsub.service.DownloadService.java

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

    final SharedPreferences prefs = Util.getPreferences(this);
    new Thread(new Runnable() {
        public void run() {
            Looper.prepare();//from  w  w  w .  j a va2  s  .  c  om

            mediaPlayer = new MediaPlayer();
            mediaPlayer.setWakeMode(DownloadService.this, PowerManager.PARTIAL_WAKE_LOCK);

            // We want to change audio session id's between upgrading Android versions.  Upgrading to Android 7.0 is broken (probably updated session id format)
            audioSessionId = -1;
            int id = prefs.getInt(Constants.CACHE_AUDIO_SESSION_ID, -1);
            int versionCode = prefs.getInt(Constants.CACHE_AUDIO_SESSION_VERSION_CODE, -1);
            if (versionCode == Build.VERSION.SDK_INT && id != -1) {
                try {
                    audioSessionId = id;
                    mediaPlayer.setAudioSessionId(audioSessionId);
                } catch (Throwable e) {
                    Log.w(TAG, "Failed to use cached audio session", e);
                    audioSessionId = -1;
                }
            }

            if (audioSessionId == -1) {
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    audioSessionId = mediaPlayer.getAudioSessionId();

                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putInt(Constants.CACHE_AUDIO_SESSION_ID, audioSessionId);
                    editor.putInt(Constants.CACHE_AUDIO_SESSION_VERSION_CODE, Build.VERSION.SDK_INT);
                    editor.commit();
                } catch (Throwable t) {
                    // Froyo or lower
                }
            }

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int what, int more) {
                    handleError(new Exception("MediaPlayer error: " + what + " (" + more + ")"));
                    return false;
                }
            });

            /*try {
               Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION);
               i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, audioSessionId);
               i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName());
               sendBroadcast(i);
            } catch(Throwable e) {
               // Froyo or lower
            }*/

            effectsController = new AudioEffectsController(DownloadService.this, audioSessionId);
            if (prefs.getBoolean(Constants.PREFERENCES_EQUALIZER_ON, false)) {
                getEqualizerController();
            }

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);

            if (runListenersOnInit) {
                onSongsChanged();
                onSongProgress();
                onStateUpdate();
            }

            Looper.loop();
        }
    }, "DownloadService").start();

    Util.registerMediaButtonEventReceiver(this);
    audioNoisyReceiver = new AudioNoisyReceiver();
    registerReceiver(audioNoisyReceiver, audioNoisyIntent);

    if (mRemoteControl == null) {
        // Use the remote control APIs (if available) to set the playback state
        mRemoteControl = RemoteControlClientBase.createInstance();
        ComponentName mediaButtonReceiverComponent = new ComponentName(getPackageName(),
                MediaButtonIntentReceiver.class.getName());
        mRemoteControl.register(this, mediaButtonReceiverComponent);
    }

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
    wakeLock.setReferenceCounted(false);

    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "downloadServiceLock");

    try {
        timerDuration = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_SLEEP_TIMER_DURATION, "5"));
    } catch (Throwable e) {
        timerDuration = 5;
    }
    sleepTimer = null;

    keepScreenOn = prefs.getBoolean(Constants.PREFERENCES_KEY_KEEP_SCREEN_ON, false);

    mediaRouter = new MediaRouteManager(this);

    instance = this;
    shufflePlayBuffer = new ShufflePlayBuffer(this);
    artistRadioBuffer = new ArtistRadioBuffer(this);
    lifecycleSupport.onCreate();

    if (Build.VERSION.SDK_INT >= 26) {
        Notifications.shutGoogleUpNotification(this);
    }
}

From source file:github.popeen.dsub.service.DownloadService.java

private synchronized void doPlay(final DownloadFile downloadFile, final int position, final boolean start) {
    try {/*www.  ja v  a 2 s.  co  m*/
        subtractPosition = 0;
        mediaPlayer.setOnCompletionListener(null);
        mediaPlayer.setOnPreparedListener(null);
        mediaPlayer.setOnErrorListener(null);
        mediaPlayer.reset();
        setPlayerState(IDLE);
        try {
            mediaPlayer.setAudioSessionId(audioSessionId);
        } catch (Throwable e) {
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        }

        String dataSource;
        boolean isPartial = false;
        if (downloadFile.isStream()) {
            dataSource = downloadFile.getStream();
            Log.i(TAG, "Data Source: " + dataSource);
        } else {
            downloadFile.setPlaying(true);
            final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                    : downloadFile.getPartialFile();
            isPartial = file.equals(downloadFile.getPartialFile());
            downloadFile.updateModificationDate();

            dataSource = file.getAbsolutePath();
            if (isPartial && !Util.isOffline(this)) {
                if (proxy == null) {
                    proxy = new BufferProxy(this);
                    proxy.start();
                }
                proxy.setBufferFile(downloadFile);
                dataSource = proxy.getPrivateAddress(dataSource);
                Log.i(TAG, "Data Source: " + dataSource);
            } else if (proxy != null) {
                proxy.stop();
                proxy = null;
            }
        }

        mediaPlayer.setDataSource(dataSource);
        setPlayerState(PREPARING);

        mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                Log.i(TAG, "Buffered " + percent + "%");
                if (percent == 100) {
                    mediaPlayer.setOnBufferingUpdateListener(null);
                }
            }
        });

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mediaPlayer) {
                try {
                    setPlayerState(PREPARED);

                    synchronized (DownloadService.this) {
                        if (position != 0) {
                            Log.i(TAG, "Restarting player from position " + position);
                            mediaPlayer.seekTo(position);
                        }
                        cachedPosition = position;

                        applyReplayGain(mediaPlayer, downloadFile);

                        if (start || autoPlayStart) {
                            mediaPlayer.start();
                            applyPlaybackParamsMain();
                            setPlayerState(STARTED);

                            // Disable autoPlayStart after done
                            autoPlayStart = false;
                        } else {
                            setPlayerState(PAUSED);
                            onSongProgress();
                        }

                        updateRemotePlaylist();
                    }

                    // Only call when starting, setPlayerState(PAUSED) already calls this
                    if (start) {
                        lifecycleSupport.serializeDownloadQueue();
                    }
                } catch (Exception x) {
                    handleError(x);
                }
            }
        });

        setupHandlers(downloadFile, isPartial, start);

        mediaPlayer.prepareAsync();
    } catch (Exception x) {
        handleError(x);
    }
}

From source file:com.nest5.businessClient.Initialactivity.java

public void playSound(Context context)
        throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {
    Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    MediaPlayer mMediaPlayer = new MediaPlayer();
    mMediaPlayer.setDataSource(context, soundUri);
    final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        mMediaPlayer.setLooping(false);//ww  w  . j av  a 2 s . com
        mMediaPlayer.prepare();
        mMediaPlayer.start();
    }
}

From source file:com.tct.mail.compose.ComposeActivity.java

protected void sendOrSave(final boolean save, final boolean showToast) {
    // Check if user is a monkey. Monkeys can compose and hit send
    // button but are not allowed to send anything off the device.
    // TS: xiaolin.li 2015-01-08 EMAIL BUGFIX-893877 DEL_S
    /*if (ActivityManager.isUserAMonkey()) {
    return;/*from  w w w  .j  av a2s. c  o m*/
    }*/
    // TS: xiaolin.li 2015-01-08 EMAIL BUGFIX-893877 DEL_E
    final SendOrSaveCallback callback = new SendOrSaveCallback() {
        // FIXME: unused
        private int mRestoredRequestId;

        @Override
        public void initializeSendOrSave(SendOrSaveTask sendOrSaveTask) {
            synchronized (mActiveTasks) {
                int numTasks = mActiveTasks.size();
                if (numTasks == 0) {
                    // Start service so we won't be killed if this app is
                    // put in the background.
                    startService(new Intent(ComposeActivity.this, EmptyService.class));
                }

                mActiveTasks.add(sendOrSaveTask);
            }
            if (sTestSendOrSaveCallback != null) {
                sTestSendOrSaveCallback.initializeSendOrSave(sendOrSaveTask);
            }
        }

        @Override
        public void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage, Message message) {
            synchronized (mDraftLock) {
                mDraftAccount = sendOrSaveMessage.mAccount;
                mDraftId = message.id;
                mDraft = message;
                if (sRequestMessageIdMap != null) {
                    sRequestMessageIdMap.put(sendOrSaveMessage.requestId(), mDraftId);
                }
                // Cache request message map, in case the process is killed
                saveRequestMap();
            }
            if (sTestSendOrSaveCallback != null) {
                sTestSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage, message);
            }
        }

        @Override
        public Message getMessage() {
            synchronized (mDraftLock) {
                return mDraft;
            }
        }

        @Override
        public void sendOrSaveFinished(SendOrSaveTask task, boolean success) {
            // Update the last sent from account.
            if (mAccount != null) {
                MailAppProvider.getInstance().setLastSentFromAccount(mAccount.uri.toString());
            }
            // TS: zhaotianyong 2015-03-25 EMAIL BUGFIX-954496 ADD_S
            // TS: zhaotianyong 2015-03-31 EMAIL BUGFIX-963249 ADD_S
            if (doSend) {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) ComposeActivity.this
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
                if (info == null) {
                    Utility.showToast(ComposeActivity.this, R.string.send_failed);
                }
            }
            // TS: zhaotianyong 2015-03-31 EMAIL BUGFIX-963249 ADD_E
            // TS: zhaotianyong 2015-03-25 EMAIL BUGFIX-954496 ADD_E
            if (success) {
                // Successfully sent or saved so reset change markers
                discardChanges();
                //TS: zheng.zou 2015-03-18 EMAIL FEATURE_996919 ADD_S
                if (!doSend && showToast) {
                    Intent intent = new Intent(DRAFT_SAVED_ACTION);
                    intent.setPackage(getString(R.string.email_package_name));
                    intent.putExtra(BaseColumns._ID, mDraftId);
                    //send ordered broadcast to execute the event in sequence in different receivers,
                    //ordered by priority
                    sendOrderedBroadcast(intent, null);
                }
                //TS: zheng.zou 2015-03-18 EMAIL FEATURE_996919 ADD_E
            } else {
                // A failure happened with saving/sending the draft
                // TODO(pwestbro): add a better string that should be used
                // when failing to send or save
                //[BUGFIX]-MOD by SCDTABLET.shujing.jin@tcl.com,08/05/2016,2635083
                Utility.showShortToast(ComposeActivity.this, R.string.send_failed);
                //Toast.makeText(ComposeActivity.this, R.string.send_failed, Toast.LENGTH_SHORT)
                //        .show();
            }

            int numTasks;
            synchronized (mActiveTasks) {
                // Remove the task from the list of active tasks
                mActiveTasks.remove(task);
                numTasks = mActiveTasks.size();
            }

            if (numTasks == 0) {
                // Stop service so we can be killed.
                stopService(new Intent(ComposeActivity.this, EmptyService.class));
            }
            if (sTestSendOrSaveCallback != null) {
                sTestSendOrSaveCallback.sendOrSaveFinished(task, success);
            }
        }

        @Override
        public void incrementRecipientsTimesContacted(final List<String> recipients) {
            ComposeActivity.this.incrementRecipientsTimesContacted(recipients);
        }
    };
    //TS: zheng.zou 2015-3-16 EMAIL BUGFIX_948927 Mod_S
    if (mReplyFromAccount == null && mAccount != null) {
        mReplyFromAccount = getDefaultReplyFromAccount(mAccount);
    }
    if (mReplyFromAccount != null) {
        setAccount(mReplyFromAccount.account);
    }
    //TS: zheng.zou 2015-3-16 EMAIL BUGFIX_948927 Mod_E
    // TS: yanhua.chen 2015-9-19 EMAIL BUGFIX_569665 ADD_S
    mIsSaveDraft = save;
    // TS: yanhua.chen 2015-9-19 EMAIL BUGFIX_569665 ADD_E

    final Spanned body = removeComposingSpans(mBodyView.getText());
    SEND_SAVE_TASK_HANDLER.post(new Runnable() {
        @Override
        public void run() {
            final Message msg = createMessage(mReplyFromAccount, mRefMessage, getMode(), body);
            // TS: kaifeng.lu 2016-4-6 EMAIL BUGFIX_1909143 ADD_S
            if (/*!mIsClickIcon &&*/ !mEditDraft && (mIsSaveDraft || doSend)) {//[BUGFIX]-MOD by SCDTABLET.shujing.jin@tcl.com,05/06/2016,2013535
                String body1 = mBodyView.getText().toString().replace("\n", "\n\r");
                SpannableString spannableString = new SpannableString(body1);
                StringBuffer bodySignature = new StringBuffer(body1);
                //[BUGFIX]-DEL begin by SCDTABLET.shujing.jin@tcl.com,05/17/2016,2013535,2148647
                //if(mCachedSettings != null){
                //    bodySignature.append(convertToPrintableSignature(mCachedSettings.signature));
                //}
                //[BUGFIX]-DEL end by SCDTABLET.shujing.jin
                spannableString = new SpannableString(bodySignature.toString());
                msg.bodyHtml = spannedBodyToHtml(spannableString, true);
                msg.bodyText = bodySignature.toString();
            }
            // TS: kaifeng.lu 2016-4-6 EMAIL BUGFIX_1909143 ADD_E
            mRequestId = sendOrSaveInternal(ComposeActivity.this, mReplyFromAccount, msg, mRefMessage,
                    mQuotedTextView.getQuotedTextIfIncluded(), callback, SEND_SAVE_TASK_HANDLER, save,
                    mComposeMode, mDraftAccount, mExtraValues);
        }
    });

    // Don't display the toast if the user is just changing the orientation,
    // but we still need to save the draft to the cursor because this is how we restore
    // the attachments when the configuration change completes.
    if (showToast && (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) {
        //TS: xinlei.sheng 2015-01-26 EMAIL FIXBUG_886976 MOD_S
        if (mLaunchContact) {
            mLaunchContact = false;
        } else {
            //TS: zheng.zou 2015-03-18 EMAIL FEATURE_996919 MDD_S
            if (!save) {
                //[BUGFIX]-MOD by SCDTABLET.shujing.jin@tcl.com,08/05/2016,2635083
                Utility.showToast(this, R.string.sending_message);
                //Toast.makeText(this, R.string.sending_message,
                //        Toast.LENGTH_LONG).show();
            }
            //                Toast.makeText(this, save ? R.string.message_saved : R.string.sending_message,
            //                        Toast.LENGTH_LONG).show();
            //TS: zheng.zou 2015-03-18 EMAIL FEATURE_996919 MOD_E
        }
        //TS: xinlei.sheng 2015-01-26 EMAIL FIXBUG_886976 MOD_E
    }

    // Need to update variables here because the send or save completes
    // asynchronously even though the toast shows right away.
    discardChanges();
    updateSaveUi();

    // If we are sending, finish the activity
    if (!save) {
        finish();
        //TS: yanhua.chen 2015-6-15 EMAIL BUGFIX_1024081 ADD_S
        //TS: lin-zhou 2015-10-15 EMAIL BUGFIX_718388 MOD_S
        Uri soundUri = Uri.parse(
                "android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.email_sent);
        MediaPlayer player = new MediaPlayer();
        try {
            if (soundUri != null) {
                player.setDataSource(getApplicationContext(), soundUri);
            }
            player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
            player.prepare();
            player.start();
        } catch (IllegalArgumentException e) {
            LogUtils.e(LOG_TAG, "Send mail mediaPlayer get dataSource occur IllegalArgumentException");
        } catch (SecurityException e) {
            LogUtils.e(LOG_TAG, "Send mail mediaPlayer get dataSource occur SecurityException");
        } catch (IllegalStateException e) {
            LogUtils.e(LOG_TAG, "Send mail mediaPlayer get dataSource occur IllegalStateException");
        } catch (IOException e) {
            LogUtils.e(LOG_TAG, "Send mail mediaPlayer get dataSource occur IOException");
        } catch (NullPointerException e) {
            LogUtils.e(LOG_TAG, "Send mail mediaPlayer get dataSource occur NullPointerException");
        }
        //TS: lin-zhou 2015-10-15 EMAIL BUGFIX_718388 MOD_E
        //TS: yanhua.chen 2015-6-15 EMAIL BUGFIX_1024081 ADD_E
    }
}