List of usage examples for android.media MediaPlayer release
public void release()
From source file:com.youku.player.base.YoukuBasePlayerActivity.java
private void initMediaPlayer() { //----------> // mediaPlayerDelegate.mediaPlayer = BaseMediaPlayer.getInstance(); mediaPlayerDelegate.mediaPlayer = RemoteInterface.baseMediaPlayer; mediaPlayerDelegate.mediaPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() { @Override/*from ww w . ja v a 2 s . c om*/ public void onBufferingUpdate(MediaPlayer mp, int percent) { if (onPause) { mp.release(); return; } if (pluginManager == null) return; pluginManager.onBufferingUpdateListener(percent); } }); mediaPlayerDelegate.mediaPlayer.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { if (mediaPlayerDelegate != null) mediaPlayerDelegate.onComplete(); if (mYoukuPlayerView != null) mYoukuPlayerView.setPlayerBlack(); } }); mediaPlayerDelegate.mediaPlayer.setOnErrorListener(new OnErrorListener() { @Override public boolean onError(MediaPlayer mp, int what, int extra) { Logger.d("PlayFlow", " MediaPlayer onError what=" + what + " !!!"); if (mYoukuPlayerView != null) mYoukuPlayerView.setDebugText("-->onError:" + what); disposeAdErrorLoss(what); if (isAdPlayError(what)) { Logger.d("PlayFlow", ":" + what + " ?:"); return loadingADOverTime(); } if (mediaPlayerDelegate != null && !mYoukuPlayerView.realVideoStart) { runOnUiThread(new Runnable() { public void run() { detectPlugin(); } }); } if (!isSendPlayBreakEvent && MediaPlayerConfiguration.getInstance().trackPlayError() && mYoukuPlayerView.realVideoStart && mediaPlayerDelegate != null && mediaPlayerDelegate.videoInfo != null) { final String videoUrl = mediaPlayerDelegate.videoInfo.getWeburl(); final TaskSendPlayBreak task = new TaskSendPlayBreak(videoUrl); task.execute(); isSendPlayBreakEvent = true; } if (mYoukuPlayerView.realVideoStart && mediaPlayerDelegate.isLoading) Track.onPlayLoadingEnd(); onLoadingFailError(); if (pluginManager == null) { Logger.d("PlayFlow", "onError:" + what + " pluginManager == null return false"); return false; } //Logger.d("PlayFlow", ":" + what + " ?:??);" int nowPostition = mediaPlayerDelegate.getCurrentPosition(); if (nowPostition > 0) { position = nowPostition; } // ? if (what == -38 && !MediaPlayerProxyUtil.isUplayerSupported()) { what = MPPErrorCode.MEDIA_INFO_PLAY_UNKNOW_ERROR; } return pluginManager.onError(what, extra); } private boolean isAdPlayError(int what) { return what == MPPErrorCode.MEDIA_INFO_PREPARED_AD_CHECK || (what == MPPErrorCode.MEDIA_INFO_DATA_SOURCE_ERROR && !mediaPlayerDelegate.isAdvShowFinished()) || (what == MPPErrorCode.MEDIA_INFO_NETWORK_ERROR && mediaPlayerDelegate.isADShowing) || (what == MPPErrorCode.MEDIA_INFO_NETWORK_CHECK && mediaPlayerDelegate.isADShowing); } //?? private void disposeAdErrorLoss(int what) { if (mediaPlayerDelegate == null || mediaPlayerDelegate.videoInfo == null) { return; } if (what == MPPErrorCode.MEDIA_INFO_DATA_SOURCE_ERROR && !mediaPlayerDelegate.videoInfo.isAdvEmpty()) { DisposableStatsUtils.disposeAdLoss(YoukuBasePlayerActivity.this, URLContainer.AD_LOSS_STEP4, SessionUnitil.playEvent_session, URLContainer.AD_LOSS_MF); } if (what == MPPErrorCode.MEDIA_INFO_PREPARED_AD_CHECK) { DisposableStatsUtils.disposeAdLoss(YoukuBasePlayerActivity.this, URLContainer.AD_LOSS_STEP6, SessionUnitil.playEvent_session, URLContainer.AD_LOSS_MF); } } }); mediaPlayerDelegate.mediaPlayer.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { if (pluginManager == null) return; pluginManager.onPrepared(); } }); mediaPlayerDelegate.mediaPlayer.setOnSeekCompleteListener(new OnSeekCompleteListener() { @Override public void onSeekComplete(MediaPlayer mp) { if (mediaPlayerDelegate != null) { mediaPlayerDelegate.isLoading = false; } Track.setTrackPlayLoading(true); if (pluginManager == null) return; runOnUiThread(new Runnable() { public void run() { pluginManager.onSeekComplete(); } }); } }); mediaPlayerDelegate.mediaPlayer.setOnVideoSizeChangedListener(new OnVideoSizeChangedListener() { @Override public void onVideoSizeChanged(MediaPlayer mp, int width, int height) { if (pluginManager == null) return; pluginManager.onVideoSizeChanged(width, height); Logger.e(TAG, "onVideoSizeChanged-->" + width + height); mediaPlayerDelegate.mediaPlayer.updateWidthAndHeight(width, height); } }); mediaPlayerDelegate.mediaPlayer.setOnTimeOutListener(new OnTimeoutListener() { @Override public void onTimeOut() { if (mediaPlayerDelegate == null) return; Logger.d("PlayFlow", "onTimeOut"); mediaPlayerDelegate.release(); runOnUiThread(new Runnable() { @Override public void run() { Track.pause(); onLoadingFailError(); } }); if (!isSendPlayBreakEvent && MediaPlayerConfiguration.getInstance().trackPlayError() && mYoukuPlayerView.realVideoStart && mediaPlayerDelegate != null && mediaPlayerDelegate.videoInfo != null) { final String videoUrl = mediaPlayerDelegate.videoInfo.getWeburl(); final TaskSendPlayBreak task = new TaskSendPlayBreak(videoUrl); task.execute(); isSendPlayBreakEvent = true; } runOnUiThread(new Runnable() { public void run() { if (pluginManager == null) return; pluginManager.onTimeout(); } }); } @Override public void onNotifyChangeVideoQuality() { if (pluginManager == null) return; Logger.d("PlayFlow", "onNotifyChangeVideoQuality"); pluginManager.onNotifyChangeVideoQuality(); } }); mediaPlayerDelegate.mediaPlayer.setOnCurrentPositionUpdateListener(new OnCurrentPositionUpdateListener() { @Override public void onCurrentPositionUpdate(final int currentPosition) { if (pluginManager == null) return; runOnUiThread(new Runnable() { @Override public void run() { try { pluginManager.onCurrentPositionChange(currentPosition); } catch (Exception e) { } } }); } }); if (PlayerUtil.useUplayer()) { mediaPlayerDelegate.mediaPlayer.setOnADPlayListener(new OnADPlayListener() { @Override public boolean onStartPlayAD(int index) { Logger.d("PlayFlow", "onstartPlayAD"); Track.onAdStart(); String vid = ""; if (mediaPlayerDelegate != null && mediaPlayerDelegate.videoInfo != null) vid = mediaPlayerDelegate.videoInfo.getVid(); Track.trackAdLoad(getApplicationContext(), vid); mYoukuPlayerView.setPlayerBlackGone(); mPluginADPlay.setInteractiveAdVisible(false); if (mediaPlayerDelegate != null) { mediaPlayerDelegate.isADShowing = true; mediaPlayerDelegate.isAdStartSended = true; if (mediaPlayerDelegate.videoInfo != null && mediaPlayerDelegate.videoInfo.videoAdvInfo != null) { if (mediaPlayerDelegate.videoInfo.videoAdvInfo.SKIP != null && mediaPlayerDelegate.videoInfo.videoAdvInfo.SKIP.equals("1")) { if (null != mPluginADPlay) { mPluginADPlay.setSkipVisible(true); } } if (mediaPlayerDelegate.videoInfo.videoAdvInfo.VAL.get(0).RST.equals("hvideo")) { if (mPluginADPlay.isInteractiveAdShow()) { mPluginADPlay.setInteractiveAdVisible(true); } else { String brs = mediaPlayerDelegate.videoInfo.videoAdvInfo.VAL.get(0).BRS; int count = mediaPlayerDelegate.videoInfo.videoAdvInfo.VAL.get(0).AL; mPluginADPlay.startInteractiveAd(brs, count); mPluginADPlay.showInteractiveAd(); } } } } updatePlugin(PLUGIN_SHOW_AD_PLAY); if (null != pluginManager) { runOnUiThread(new Runnable() { public void run() { pluginManager.onLoaded(); if (null != mPluginADPlay) { mPluginADPlay.setVisible(true); } } }); } if (mediaPlayerDelegate != null && mediaPlayerDelegate.videoInfo != null) { AnalyticsWrapper.adPlayStart(getApplicationContext(), mediaPlayerDelegate.videoInfo); } try { DisposableStatsUtils.disposeSUS(mediaPlayerDelegate.videoInfo); } catch (NullPointerException e) { Logger.e("sgh", e.toString()); } if (mediaPlayerDelegate.videoInfo.getCurrentAdvInfo() != null && (mediaPlayerDelegate.videoInfo.getCurrentAdvInfo().VSC == null || mediaPlayerDelegate.videoInfo.getCurrentAdvInfo().VSC .equalsIgnoreCase(""))) { DisposableStatsUtils.disposeVC(mediaPlayerDelegate.videoInfo); } return false; } @Override public boolean onEndPlayAD(int index) { Logger.d("PlayFlow", "onEndPlayAD"); if (mediaPlayerDelegate != null) { mediaPlayerDelegate.isADShowing = false; } Track.onAdEnd(); if (mediaPlayerDelegate != null && mediaPlayerDelegate.videoInfo != null) { AnalyticsWrapper.adPlayEnd(getApplicationContext(), mediaPlayerDelegate.videoInfo); } // removePlayedAdv? DisposableStatsUtils.disposeSUE(mediaPlayerDelegate.videoInfo); // ???? mediaPlayerDelegate.videoInfo.removePlayedAdv(); if (mediaPlayerDelegate.videoInfo.isCached()) { ICacheInfo download = IMediaPlayerDelegate.mICacheInfo; if (download != null) { if (download.isDownloadFinished(mediaPlayerDelegate.videoInfo.getVid())) { VideoCacheInfo downloadInfo = download .getDownloadInfo(mediaPlayerDelegate.videoInfo.getVid()); if (YoukuBasePlayerActivity.isHighEnd) { mediaPlayerDelegate.videoInfo.cachePath = PlayerUtil .getM3u8File(downloadInfo.savePath + "youku.m3u8"); } } } } if (null != pluginManager) { runOnUiThread(new Runnable() { public void run() { mPluginADPlay.closeInteractiveAdNotIcludeUI(); pluginManager.onLoading(); } }); } Logger.e(TAG, "onEndPlayAD"); return false; } }); mediaPlayerDelegate.mediaPlayer.setOnADCountListener(new OnADCountListener() { @Override public void onCountUpdate(final int count) { position = mediaPlayerDelegate.getCurrentPosition(); final int currentPosition = mediaPlayerDelegate.getCurrentPosition() / 1000; runOnUiThread(new Runnable() { public void run() { mPluginADPlay.notifyUpdate(count); mYoukuPlayerView.resizeMediaPlayer(false); DisposableStatsUtils.disposeSU(mediaPlayerDelegate.videoInfo, currentPosition); } }); } }); mediaPlayerDelegate.mediaPlayer.setOnNetworkSpeedListener(new OnNetworkSpeedListener() { @Override public void onSpeedUpdate(final int count) { if (null != pluginManager) { runOnUiThread(new Runnable() { public void run() { pluginManager.onNetSpeedChange(count); } }); } } }); } mediaPlayerDelegate.mediaPlayer.setOnRealVideoStartListener(new OnRealVideoStartListener() { @Override public void onRealVideoStart() { if (onPause) return; // listener?? // mediaPlayerDelegate Logger.d("PlayFlow", ""); Track.isRealVideoStarted = true; String vid = ""; if (mediaPlayerDelegate != null && mediaPlayerDelegate.videoInfo != null) vid = mediaPlayerDelegate.videoInfo.getVid(); Track.onRealVideoFirstLoadEnd(getApplicationContext(), vid); localStartSetDuration(); sentonVVBegin(); mYoukuPlayerView.setPlayerBlackGone(); if (mediaPlayerDelegate != null && mediaPlayerDelegate.videoInfo != null) { mediaPlayerDelegate.isADShowing = false; Logger.e(TAG, "onRealVideoStart" + mediaPlayerDelegate.videoInfo.IsSendVV); } else { Logger.e(TAG, "onRealVideoStart mediaPlayerDelegate"); } mediaPlayerDelegate.isLoading = false; if (null != pluginManager) { runOnUiThread(new Runnable() { public void run() { detectPlugin(); pluginManager.onRealVideoStart(); pluginManager.onLoaded(); } }); } if (mediaPlayerDelegate != null) { if (mediaPlayerDelegate.videoInfo != null && mediaPlayerDelegate.videoInfo.getProgress() > 1000 && !mediaPlayerDelegate.videoInfo.isHLS) { mediaPlayerDelegate.seekTo(mediaPlayerDelegate.videoInfo.getProgress()); Logger.e("PlayFlow", "SEEK TO" + mediaPlayerDelegate.videoInfo.getProgress()); } } runOnUiThread(new Runnable() { public void run() { if (mInvestigate != null) { mInvestigate.show(); } } }); } }); mediaPlayerDelegate.mediaPlayer.setOnLoadingStatusListener(new OnLoadingStatusListener() { @Override public void onStartLoading() { Logger.e(TAG, "onStartLoading"); if (pluginManager == null || onPause) return; Track.onPlayLoadingStart(mediaPlayerDelegate.mediaPlayer.getCurrentPosition()); if (mediaPlayerDelegate != null) { mediaPlayerDelegate.isLoading = true; } runOnUiThread(new Runnable() { @Override public void run() { if (pluginManager == null) return; pluginManager.onLoading(); if (PlayerUtil.useUplayer() && !mediaPlayerDelegate.videoInfo.isUseCachePath()) mediaPlayerDelegate.loadingPause(); } }); } @Override public void onEndLoading() { runOnUiThread(new Runnable() { @Override public void run() { if (pluginManager == null) return; pluginManager.onLoaded(); } }); Track.onPlayLoadingEnd(); if (null != mediaPlayerDelegate) { mediaPlayerDelegate.isStartPlay = true; mediaPlayerDelegate.isLoading = false; if (null != mediaPlayerDelegate.videoInfo) { id = mediaPlayerDelegate.videoInfo.getVid(); mediaPlayerDelegate.videoInfo.isFirstLoaded = true; } // mp4?? if (PlayerUtil.useUplayer() && !mediaPlayerDelegate.videoInfo.isUseCachePath()) mediaPlayerDelegate.start(); } if (!firstLoaded && !isFromLocal() && !PreferenceUtil .getPreferenceBoolean(YoukuBasePlayerActivity.this, "video_lock", false)) { if (mediaPlayerDelegate != null && !mediaPlayerDelegate.isFullScreen && mediaPlayerDelegate.videoInfo != null && StaticsUtil.PLAY_TYPE_LOCAL.equals(mediaPlayerDelegate.videoInfo.getPlayType()) || !PlayerUtil.isYoukuTablet(YoukuBasePlayerActivity.this)) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } Logger.d("lelouch", "onLoaded setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);"); firstLoaded = true; } } }); mediaPlayerDelegate.mediaPlayer.setOnPlayHeartListener(new OnPlayHeartListener() { @Override public void onPlayHeart() { if (mediaPlayerDelegate != null && mediaPlayerDelegate.videoInfo != null) Track.trackPlayHeart(getApplicationContext(), mediaPlayerDelegate.videoInfo, mediaPlayerDelegate.isFullScreen); } }); mediaPlayerDelegate.mediaPlayer.setOnVideoIndexUpdateListener(new OnVideoIndexUpdateListener() { @Override public void onVideoIndexUpdate(int currentIndex, int ip) { Logger.d("PlayFlow", "onVideoIndexUpdate:" + currentIndex + " " + ip); if (mediaPlayerDelegate != null && mediaPlayerDelegate.videoInfo != null) Track.onVideoIndexUpdate(getApplicationContext(), currentIndex, ip, mediaPlayerDelegate.videoInfo.getCurrentQuality()); } }); mediaPlayerDelegate.mediaPlayer.setOnHwDecodeErrorListener(new OnHwDecodeErrorListener() { @Override public void OnHwDecodeError() { Logger.d("PlayFlow", "OnHwDecodeError"); // DisposableHttpTask task = new DisposableHttpTask( // URLContainer.getHwErrorUrl()); // task.setRequestMethod(DisposableHttpTask.METHOD_POST); // task.start(); MediaPlayerConfiguration.getInstance().setUseHardwareDecode(false); } }); }
From source file:com.shinymayhem.radiopresets.ServiceRadioPlayer.java
protected void stopAndReleasePlayer(MediaPlayer player) { //TODO need to release looping background metadata task here somehow too if (LOCAL_LOGV) log("stopAndReleasePlayer()", "v"); if (player != null) { try {/*w w w .j a v a2 s. c om*/ if (player.isPlaying()) { player.stop(); if (LOCAL_LOGV) log("stopped mediaPlayer", "v"); } if (LOCAL_LOGV) log("mediaPlayer not playing", "v"); } catch (IllegalStateException e) { if (LOCAL_LOGV) log("player in wrong state to stop", "v"); } try { player.reset(); if (LOCAL_LOGV) log("reset mediaPlayer", "v"); } catch (IllegalStateException e) { if (LOCAL_LOGV) log("player in wrong state to reset", "v"); } player.release(); } }
From source file:net.nightwhistler.pageturner.fragment.ReadingFragment.java
/** * Called when a speech fragment has finished being played. * * @param item// ww w . j a v a 2s . com * @param mediaPlayer */ public void speechCompleted(TTSPlaybackItem item, MediaPlayer mediaPlayer) { LOG.debug("Speech completed for " + item.getFileName()); if (!ttsPlaybackItemQueue.isEmpty()) { this.ttsPlaybackItemQueue.remove(); } if (ttsIsRunning()) { startPlayback(); if (item.isLastElementOfPage()) { this.uiHandler.post(() -> pageDown(Orientation.VERTICAL)); } } mediaPlayer.release(); new File(item.getFileName()).delete(); }
From source file:com.insthub.O2OMobile.Activity.C1_PublishOrderActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.c1_publish_order); mFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); File file = new File(newFileName()); if (file.exists()) { file.delete();/* w ww .ja v a 2 s . c o m*/ } Intent intent = getIntent(); mServiceType = (SERVICE_TYPE) intent.getSerializableExtra(O2OMobileAppConst.SERVICE_TYPE); mDefaultReceiverId = intent.getIntExtra(DEFAULT_RECEIVER_ID, 0); service_list = intent.getStringExtra("service_list"); mBack = (ImageView) findViewById(R.id.top_view_back); mTitle = (TextView) findViewById(R.id.top_view_title); mBack.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub finish(); } }); mArrowImage = (ImageView) findViewById(R.id.top_view_arrow_image); mClose = (ImageView) findViewById(R.id.top_view_right_close); mTitleView = (LinearLayout) findViewById(R.id.top_view_title_view); mServiceTypeView = (FrameLayout) findViewById(R.id.c1_publish_order_service_type_view); mServiceTypeListview = (ListView) findViewById(R.id.c1_publish_order_service_type_list); mPrice = (EditText) findViewById(R.id.c1_publish_order_price); mTime = (TextView) findViewById(R.id.c1_publish_order_time); mLocation = (EditText) findViewById(R.id.c1_publish_order_location); mText = (EditText) findViewById(R.id.c1_publish_order_text); mVoice = (Button) findViewById(R.id.c1_publish_order_voice); mVoicePlay = (Button) findViewById(R.id.c1_publish_order_voicePlay); mVoiceReset = (ImageView) findViewById(R.id.c1_publish_order_voiceReset); mPublish = (Button) findViewById(R.id.c1_publish_order_publish); mVoiceView = (FrameLayout) findViewById(R.id.c1_publish_order_voice_view); mVoiceAnim = (ImageView) findViewById(R.id.c1_publish_order_voice_anim); mVoiceAnim.setImageResource(R.anim.voice_animation); mAnimationDrawable = (AnimationDrawable) mVoiceAnim.getDrawable(); mAnimationDrawable.setOneShot(false); mTitleView.setEnabled(false); mServiceTypeView.setOnClickListener(null); mServiceTypeListview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub if (mDefaultReceiverId == 0) { mTitle.setText(mHomeModel.publicServiceTypeList.get(position).title); mServiceTypeId = mHomeModel.publicServiceTypeList.get(position).id; mC1PublishOrderAdapter = new C1_PublishOrderAdapter(C1_PublishOrderActivity.this, mHomeModel.publicServiceTypeList, position); mServiceTypeListview.setAdapter(mC1PublishOrderAdapter); mClose.setVisibility(View.GONE); mArrowImage.setImageResource(R.drawable.b3_arrow_down); AnimationUtil.backAnimationFromBottom(mServiceTypeListview); Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); mServiceTypeView.setVisibility(View.GONE); } }; mHandler.sendEmptyMessageDelayed(0, 200); } else { mTitle.setText(mServiceTypeList.get(position).title); mServiceTypeId = mServiceTypeList.get(position).id; mC1PublishOrderAdapter = new C1_PublishOrderAdapter(C1_PublishOrderActivity.this, mServiceTypeList, position); mServiceTypeListview.setAdapter(mC1PublishOrderAdapter); mClose.setVisibility(View.GONE); mArrowImage.setImageResource(R.drawable.b3_arrow_down); AnimationUtil.backAnimationFromBottom(mServiceTypeListview); Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); mServiceTypeView.setVisibility(View.GONE); } }; mHandler.sendEmptyMessageDelayed(0, 200); } } }); mTitleView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (mServiceTypeView.getVisibility() == View.GONE) { mServiceTypeView.setVisibility(View.VISIBLE); mClose.setVisibility(View.VISIBLE); mArrowImage.setImageResource(R.drawable.b4_arrow_up); AnimationUtil.showAnimationFromTop(mServiceTypeListview); closeKeyBoard(); } else { mClose.setVisibility(View.GONE); mArrowImage.setImageResource(R.drawable.b3_arrow_down); AnimationUtil.backAnimationFromBottom(mServiceTypeListview); Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); mServiceTypeView.setVisibility(View.GONE); } }; mHandler.sendEmptyMessageDelayed(0, 200); } } }); mClose.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub mClose.setVisibility(View.GONE); mArrowImage.setImageResource(R.drawable.b3_arrow_down); AnimationUtil.backAnimationFromBottom(mServiceTypeListview); Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); mServiceTypeView.setVisibility(View.GONE); } }; mHandler.sendEmptyMessageDelayed(0, 200); } }); mPrice.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub if (s.toString().length() > 0) { if (s.toString().substring(0, 1).equals(".")) { s = s.toString().substring(1, s.length()); mPrice.setText(s); } } if (s.toString().length() > 1) { if (s.toString().substring(0, 1).equals("0")) { if (!s.toString().substring(1, 2).equals(".")) { s = s.toString().substring(1, s.length()); mPrice.setText(s); CharSequence charSequencePirce = mPrice.getText(); if (charSequencePirce instanceof Spannable) { Spannable spanText = (Spannable) charSequencePirce; Selection.setSelection(spanText, charSequencePirce.length()); } } } } boolean flag = false; for (int i = 0; i < s.toString().length() - 1; i++) { String getstr = s.toString().substring(i, i + 1); if (getstr.equals(".")) { flag = true; break; } } if (flag) { int i = s.toString().indexOf("."); if (s.toString().length() - 3 > i) { String getstr = s.toString().substring(0, i + 3); mPrice.setText(getstr); CharSequence charSequencePirce = mPrice.getText(); if (charSequencePirce instanceof Spannable) { Spannable spanText = (Spannable) charSequencePirce; Selection.setSelection(spanText, charSequencePirce.length()); } } } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); initData(); mHomeModel = new HomeModel(this); mHomeModel.addResponseListener(this); if (mDefaultReceiverId == 0) { mShared = getSharedPreferences(O2OMobileAppConst.USERINFO, 0); mHomeData = mShared.getString("home_data", ""); if ("".equals(mHomeData)) { mHomeModel.getServiceTypeList(); } else { try { servicetypelistResponse response = new servicetypelistResponse(); response.fromJson(new JSONObject(mHomeData)); mHomeModel.publicServiceTypeList = response.services; setServiceTypeAdater(); } catch (JSONException e) { e.printStackTrace(); } } } else { if (service_list != null && !"".equals(service_list)) { try { JSONObject userJson = new JSONObject(service_list); myservicelistResponse response = new myservicelistResponse(); response.fromJson(userJson); for (int i = 0; i < response.services.size(); i++) { SERVICE_TYPE service = new SERVICE_TYPE(); service = response.services.get(i).service_type; mServiceTypeList.add(service); } if (mServiceTypeList.size() > 0) { mTitleView.setEnabled(true); mArrowImage.setVisibility(View.VISIBLE); if (mServiceType != null) { for (int i = 0; i < mServiceTypeList.size(); i++) { if (mServiceType.id == mServiceTypeList.get(i).id) { mC1PublishOrderAdapter = new C1_PublishOrderAdapter(this, mServiceTypeList, i); mServiceTypeListview.setAdapter(mC1PublishOrderAdapter); mTitle.setText(mServiceTypeList.get(i).title); mServiceTypeId = mServiceTypeList.get(i).id; break; } } } else { mC1PublishOrderAdapter = new C1_PublishOrderAdapter(this, mServiceTypeList); mServiceTypeListview.setAdapter(mC1PublishOrderAdapter); mTitle.setText(getString(R.string.select_service)); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { mShared = getSharedPreferences(O2OMobileAppConst.USERINFO, 0); mHomeData = mShared.getString("home_data", ""); if ("".equals(mHomeData)) { mHomeModel.getServiceTypeList(); } else { try { servicetypelistResponse response = new servicetypelistResponse(); response.fromJson(new JSONObject(mHomeData)); mHomeModel.publicServiceTypeList = response.services; setServiceTypeAdater(); } catch (JSONException e) { e.printStackTrace(); } } } } mLocationInfoModel = new LocationInfoModel(this); mLocationInfoModel.addResponseListener(this); mLocationInfoModel.get(); mOrderPublishModel = new OrderPublishModel(this); mOrderPublishModel.addResponseListener(this); //?? CharSequence charSequencePirce = mPrice.getText(); if (charSequencePirce instanceof Spannable) { Spannable spanText = (Spannable) charSequencePirce; Selection.setSelection(spanText, charSequencePirce.length()); } CharSequence charSequenceLocation = mLocation.getText(); if (charSequenceLocation instanceof Spannable) { Spannable spanText = (Spannable) charSequenceLocation; Selection.setSelection(spanText, charSequenceLocation.length()); } mVoice.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (event.getAction() == MotionEvent.ACTION_DOWN) { closeKeyBoard(); mVoice.setKeepScreenOn(true); mMaxTime = MAX_TIME; mVoiceView.setVisibility(View.VISIBLE); mAnimationDrawable.start(); startRecording(); } else if (event.getAction() == MotionEvent.ACTION_UP) { mVoice.setKeepScreenOn(false); mVoiceView.setVisibility(View.GONE); mAnimationDrawable.stop(); if (mMaxTime > 28) { mVoice.setEnabled(false); Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); stopRecording(); mVoice.setEnabled(true); } }; mHandler.sendEmptyMessageDelayed(0, 500); } else { stopRecording(); } } else if (event.getAction() == MotionEvent.ACTION_CANCEL) { mVoice.setKeepScreenOn(false); mVoiceView.setVisibility(View.GONE); mAnimationDrawable.stop(); if (mMaxTime > 28) { mVoice.setEnabled(false); Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); stopRecording(); mVoice.setEnabled(true); } }; mHandler.sendEmptyMessageDelayed(0, 500); } else { stopRecording(); } } else if (event.getAction() == MotionEvent.ACTION_MOVE) { mVoice.getParent().requestDisallowInterceptTouchEvent(true); } return false; } }); mVoicePlay.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (mPlayer == null) { File file = new File(mFileName); if (file.exists()) { mPlayer = new MediaPlayer(); mVoicePlay.setBackgroundResource(R.anim.record_animation); mAnimationDrawable2 = (AnimationDrawable) mVoicePlay.getBackground(); mAnimationDrawable2.setOneShot(false); mAnimationDrawable2.start(); try { mPlayer.setDataSource(mFileName); mPlayer.prepare(); mPlayer.start(); mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { mp.reset(); mPlayer = null; mVoicePlay.setBackgroundResource(R.drawable.b5_play_btn); mAnimationDrawable2.stop(); } }); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { Toast.makeText(C1_PublishOrderActivity.this, getString(R.string.file_does_not_exist), Toast.LENGTH_SHORT).show(); } } else { mPlayer.release(); mPlayer = null; mVoicePlay.setBackgroundResource(R.drawable.b5_play_btn); mAnimationDrawable2.stop(); } } }); mVoiceReset.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (mPlayer != null) { mPlayer.release(); mPlayer = null; mVoicePlay.setBackgroundResource(R.drawable.b5_play_btn); mAnimationDrawable2.stop(); } File file = new File(mFileName); if (file.exists()) { file.delete(); } mVoice.setVisibility(View.VISIBLE); mVoicePlay.setVisibility(View.GONE); mVoiceReset.setVisibility(View.GONE); } }); mPublish.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub File file = new File(newFileName()); int duration = 0; if (file.exists()) { MediaPlayer mp = MediaPlayer.create(C1_PublishOrderActivity.this, Uri.parse(mFileName)); if (null != mp) { duration = mp.getDuration();//? ms mp.release(); } if (duration % 1000 > 500) { duration = duration / 1000 + 1; } else { duration = duration / 1000; } } else { file = null; } int num = 0; try { // ?? Date date = new Date(); Date date1 = mFormat.parse(mFormat.format(date)); Date date2 = mFormat.parse(mTime.getText().toString()); num = date2.compareTo(date1); if (num < 0) { long diff = date1.getTime() - date2.getTime(); long mins = diff / (1000 * 60); if (mins < 3) { num = 1; } } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (mServiceTypeId == 0) { ToastView toast = new ToastView(C1_PublishOrderActivity.this, getString(R.string.select_service)); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } else if (mPrice.getText().toString().equals("")) { ToastView toast = new ToastView(C1_PublishOrderActivity.this, getString(R.string.price_range)); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } else if (mPrice.getText().toString().equals("0.")) { ToastView toast = new ToastView(C1_PublishOrderActivity.this, getString(R.string.right_price)); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } else if (mTime.getText().toString().equals("")) { ToastView toast = new ToastView(C1_PublishOrderActivity.this, getString(R.string.appoint_time)); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } else if (num < 0) { ToastView toast = new ToastView(C1_PublishOrderActivity.this, getString(R.string.wrong_appoint_time_hint)); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } else if (mLocation.getText().toString().equals("")) { ToastView toast = new ToastView(C1_PublishOrderActivity.this, getString(R.string.appoint_location_hint)); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } else { mOrderPublishModel.publish(mPrice.getText().toString(), mTime.getText().toString(), mLocation.getText().toString(), mText.getText().toString(), file, mServiceTypeId, mDefaultReceiverId, duration); } } }); }
From source file:com.sentaroh.android.SMBSync.SMBSyncMain.java
private void playBackDefaultNotification() { // Thread th=new Thread(){ // @Override // public void run() { // Uri uri=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); // if (uri!=null) { //// Ringtone rt=RingtoneManager.getRingtone(mContext, uri); //// rt.play(); //// SystemClock.sleep(1000); //// rt.stop(); // MediaPlayer player = MediaPlayer.create(mContext, uri); // if (player!=null) { // int dur=player.getDuration(); // player.start(); // SystemClock.sleep(dur+10); // player.stop(); // player.reset(); // player.release(); // } // } // }// ww w . j a v a2s.c o m // }; // th.start(); Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); if (uri != null) { MediaPlayer player = MediaPlayer.create(mContext, uri); if (player != null) { int dur = player.getDuration(); player.start(); SystemClock.sleep(dur + 10); player.stop(); player.reset(); player.release(); } } }
From source file:com.aujur.ebookreader.activity.ReadingFragment.java
public void speechCompleted(TTSPlaybackItem item, MediaPlayer mediaPlayer) { LOG.debug("Speech completed for " + item.getFileName()); if (!ttsPlaybackItemQueue.isEmpty()) { this.ttsPlaybackItemQueue.remove(); }// www . j av a 2 s . co m if (ttsIsRunning()) { startPlayback(); if (item.isLastElementOfPage()) { this.uiHandler.post(new Runnable() { @Override public void run() { pageDown(Orientation.VERTICAL); } }); } } mediaPlayer.release(); new File(item.getFileName()).delete(); }
From source file:org.telegram.ui.ChatActivity.java
public void processSendingVideo(final String videoPath) { if (videoPath == null) { return;//from w w w .ja v a2 s.c o m } Bitmap thumb = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Video.Thumbnails.MINI_KIND); TLRPC.PhotoSize size = FileLoader.scaleAndSaveImage(thumb, 90, 90, 55, currentEncryptedChat != null); if (size == null) { return; } size.type = "s"; TLRPC.TL_video video = new TLRPC.TL_video(); video.thumb = size; video.caption = ""; video.id = 0; video.path = videoPath; File temp = new File(videoPath); if (temp != null && temp.exists()) { video.size = (int) temp.length(); } UserConfig.lastLocalId--; UserConfig.saveConfig(false); MediaPlayer mp = MediaPlayer.create(ApplicationLoader.applicationContext, Uri.fromFile(new File(videoPath))); if (mp == null) { return; } video.duration = (int) Math.ceil(mp.getDuration() / 1000.0f); video.w = mp.getVideoWidth(); video.h = mp.getVideoHeight(); mp.release(); MediaStore.Video.Media media = new MediaStore.Video.Media(); MessagesController.Instance.sendMessage(video, dialog_id); if (chatListView != null) { chatListView.setSelection(messages.size() + 1); } scrollToTopOnResume = true; }
From source file:org.telegram.ui.ChatActivity.java
private void stopRecording() { try {/*from w w w .j a v a 2s. c o m*/ audioRecorder.stop(); audioRecorder.release(); audioRecorder = null; recordingAudio.date = ConnectionsManager.Instance.getCurrentTime(); recordingAudio.size = (int) recordingAudioFile.length(); recordingAudio.path = recordingAudioFile.getAbsolutePath(); int duration = 0; MediaPlayer player = new MediaPlayer(); try { player.setDataSource(recordingAudio.path); player.prepare(); duration = player.getDuration(); recordingAudio.duration = duration / 1000; } catch (Exception e) { FileLog.e("tmessages", e); } finally { try { player.release(); player = null; } catch (Exception e) { FileLog.e("tmessages", e); } } if (duration > 500) { MessagesController.Instance.sendMessage(recordingAudio, dialog_id); } else { recordingAudio = null; recordingAudioFile.delete(); recordingAudioFile = null; } } catch (Exception e) { FileLog.e("tmessages", e); recordingAudio = null; recordingAudioFile.delete(); recordingAudioFile = null; } }
From source file:me.ububble.speakall.fragment.ConversationChatFragment.java
public void showMensajeAudio(int position, Context context, final Message message, View rowView, TextView icnMessageArrow) {/* ww w . j av a2 s. c om*/ final TextView prevMessages = (TextView) rowView.findViewById(R.id.showprev_messages); TextView messageTime = (TextView) rowView.findViewById(R.id.message_time); final TextView icnMesajeTempo = (TextView) rowView.findViewById(R.id.icn_message_tempo); final View icnMensajeTempoDivider = (View) rowView.findViewById(R.id.icn_message_tempo_divider); final TextView icnMesajeCopy = (TextView) rowView.findViewById(R.id.icn_message_copy); final TextView icnMesajeBack = (TextView) rowView.findViewById(R.id.icn_message_back); TextView messageStatus = (TextView) rowView.findViewById(R.id.message_status); final LinearLayout messageMenu = (LinearLayout) rowView.findViewById(R.id.messages_menu_layout); final LinearLayout mensajeLayout = (LinearLayout) rowView.findViewById(R.id.mensaje_layout); TextView messageDate = (TextView) rowView.findViewById(R.id.message_date); final TextView audioTime = (TextView) rowView.findViewById(R.id.message_audio_time); final SeekBar audioSeekBar = (SeekBar) rowView.findViewById(R.id.audio_seekbar); final TextView playAudio = (TextView) rowView.findViewById(R.id.play_audio); final ProgressBar progressBar = (ProgressBar) rowView.findViewById(R.id.progress_bar); final RelativeLayout progressLayout = (RelativeLayout) rowView.findViewById(R.id.progress_layout); final TextView progressText = (TextView) rowView.findViewById(R.id.progress_message); TFCache.apply(context, messageTime, TFCache.TF_WHITNEY_MEDIUM); TFCache.apply(context, icnMesajeTempo, TFCache.TF_SPEAKALL); TFCache.apply(context, icnMesajeCopy, TFCache.TF_SPEAKALL); TFCache.apply(context, icnMesajeBack, TFCache.TF_SPEAKALL); TFCache.apply(context, messageStatus, TFCache.TF_SPEAKALL); TFCache.apply(context, prevMessages, TFCache.TF_WHITNEY_MEDIUM); TFCache.apply(context, messageDate, TFCache.TF_WHITNEY_MEDIUM); TFCache.apply(context, audioTime, TFCache.TF_WHITNEY_MEDIUM); TFCache.apply(context, playAudio, TFCache.TF_SPEAKON); if (position == 0) { if (mensajesTotal > mensajesOffset) { prevMessages.setVisibility(View.VISIBLE); prevMessages.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { prevMessages.setVisibility(View.GONE); if (mensajesTotal - mensajesOffset >= 10) { mensajesLimit = 10; mensajesOffset += mensajesLimit; showPreviousMessages(mensajesOffset); } else { mensajesLimit = mensajesTotal - mensajesOffset; mensajesOffset += mensajesLimit; showPreviousMessages(mensajesOffset); } } }); } } DateFormat dateDay = new SimpleDateFormat("d"); DateFormat dateDayText = new SimpleDateFormat("EEEE"); DateFormat dateMonth = new SimpleDateFormat("MMMM"); DateFormat dateYear = new SimpleDateFormat("yyyy"); DateFormat timeFormat = new SimpleDateFormat("h:mm a"); Calendar fechamsj = Calendar.getInstance(); fechamsj.setTimeInMillis(message.emitedAt); String time = timeFormat.format(fechamsj.getTime()); String dayMessage = dateDay.format(fechamsj.getTime()); String monthMessage = dateMonth.format(fechamsj.getTime()); String yearMessage = dateYear.format(fechamsj.getTime()); String dayMessageText = dateDayText.format(fechamsj.getTime()); char[] caracteres = dayMessageText.toCharArray(); caracteres[0] = Character.toUpperCase(caracteres[0]); dayMessageText = new String(caracteres); Calendar fechaActual = Calendar.getInstance(); String dayActual = dateDay.format(fechaActual.getTime()); String monthActual = dateMonth.format(fechaActual.getTime()); String yearActual = dateYear.format(fechaActual.getTime()); String fechaMostrar = ""; if (dayMessage.equals(dayActual) && monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) { fechaMostrar = getString(R.string.messages_today); } else if (monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) { int days = Integer.parseInt(dayActual) - Integer.parseInt(dayMessage); if (days < 7) { switch (days) { case 1: fechaMostrar = getString(R.string.messages_yesterday); break; default: fechaMostrar = dayMessageText; break; } } else { fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase(); } } else { fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase(); } messageDate.setText(fechaMostrar); if (position != -1) { if (itemAnterior != null) { if (!fechaMostrar.equals(fechaAnterior)) { itemAnterior.findViewById(R.id.message_date).setVisibility(View.VISIBLE); } else { itemAnterior.findViewById(R.id.message_date).setVisibility(View.GONE); } } itemAnterior = rowView; fechaAnterior = fechaMostrar; } else { View v = messagesList.getChildAt(messagesList.getChildCount() - 1); if (v != null) { TextView tv = (TextView) v.findViewById(R.id.message_date); if (tv.getText().toString().equals(fechaMostrar)) { messageDate.setVisibility(View.GONE); } else { messageDate.setVisibility(View.VISIBLE); } } } messageTime.setText(time); if (message.emisor.equals(u.id)) { mensajeLayout.setBackgroundResource(R.drawable.message_out_background); GradientDrawable drawable1 = (GradientDrawable) mensajeLayout.getBackground(); drawable1.setCornerRadius(radius); drawable1.setColor(BalloonFragment.getBackgroundColor(activity)); progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.speak_all_red), PorterDuff.Mode.SRC_IN); if (message.status != -1) { rowView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (messageSelected != null) { View vista = messagesList.findViewWithTag(messageSelected); vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE); messageSelected = message.mensajeId; ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) { @Override public void doBack() { View vista = messagesList.findViewWithTag(messageSelected); vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE); ((MainActivity) activity).setOnBackPressedListener(null); messageSelected = null; } }); } else { messageSelected = message.mensajeId; ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) { @Override public void doBack() { if (messageSelected != null) { View vista = messagesList.findViewWithTag(messageSelected); vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE); ((MainActivity) activity).setOnBackPressedListener(null); messageSelected = null; } } }); } Vibrator x = (Vibrator) activity.getApplicationContext() .getSystemService(Context.VIBRATOR_SERVICE); x.vibrate(30); Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId) .executeSingle(); if (mensaje.status != 4) { icnMesajeTempo.setVisibility(View.VISIBLE); icnMensajeTempoDivider.setVisibility(View.VISIBLE); icnMesajeCopy.setVisibility(View.VISIBLE); icnMesajeBack.setVisibility(View.VISIBLE); messageMenu.setVisibility(View.VISIBLE); AnimatorSet set = new AnimatorSet(); set.playTogether(ObjectAnimator.ofFloat(icnMesajeTempo, "alpha", 0, 1), ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1), ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1), ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1), ObjectAnimator.ofFloat(icnMesajeTempo, "translationX", 150, 0), ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0), ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0)); set.setDuration(200).start(); } else { icnMesajeCopy.setVisibility(View.VISIBLE); icnMesajeBack.setVisibility(View.VISIBLE); messageMenu.setVisibility(View.VISIBLE); AnimatorSet set = new AnimatorSet(); set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1), ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1), ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1), ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0), ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0)); set.setDuration(200).start(); } return false; } }); } if (message.status == 1) { messageStatus.setTextSize(16); mensajeLayout.setBackgroundResource(R.drawable.message_out_background); GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground(); drawable.setCornerRadius(radius); drawable.setColor(BalloonFragment.getBackgroundColor(activity)); icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity)); messageStatus.setTextColor(getResources().getColor(R.color.speak_all_ligh_gray)); messageStatus.setText(Finder.STRING.ICN_MSJ_SENDING.toString()); ValueAnimator colorAnim = ObjectAnimator.ofFloat(messageStatus, "alpha", 1, 0); colorAnim.setRepeatCount(ValueAnimator.INFINITE); colorAnim.setRepeatMode(ValueAnimator.REVERSE); colorAnim.setDuration(1000).start(); animaciones.put(message.mensajeId, colorAnim); final JSONObject data = new JSONObject(); try { data.put("message_id", message.mensajeId); data.put("source", message.emisor); data.put("source_email", message.emisorEmail); data.put("target_email", message.receptorEmail); data.put("target", message.receptor); data.put("type", message.tipo); if (!message.fileUploaded) { progressLayout.setVisibility(View.VISIBLE); new Thread(new Runnable() { @Override public void run() { activity.runOnUiThread(new Runnable() { @Override public void run() { uploadAudioToServer(message.audioName, message, data, progressBar, progressLayout, progressText); } }); } }).start(); } else { data.put("videos", message.fileName); if (SpeakSocket.mSocket != null) if (SpeakSocket.mSocket.connected()) { message.status = 1; SpeakSocket.mSocket.emit("message", data); } else { message.status = -1; } message.save(); changeStatus(message.mensajeId, message.status); } } catch (JSONException e) { e.printStackTrace(); } } if (message.status == -1) { messageStatus.setTextSize(11); mensajeLayout.setBackgroundResource(R.drawable.message_out_background); GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground(); drawable.setCornerRadius(radius); drawable.setColor(BalloonFragment.getBackgroundColor(activity)); icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity)); messageStatus.setText(Finder.STRING.ICN_MSJ_ERROR.toString()); } if (message.status == 3) { messageStatus.setTextSize(11); mensajeLayout.setBackgroundResource(R.drawable.message_out_background); GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground(); drawable.setCornerRadius(radius); drawable.setColor(BalloonFragment.getBackgroundColor(activity)); icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity)); messageStatus.setText(Finder.STRING.ICN_MSJ_CLOSED.toString()); } if (message.status == 2) { messageStatus.setTextSize(16); mensajeLayout.setBackgroundResource(R.drawable.message_out_background); GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground(); drawable.setCornerRadius(radius); drawable.setColor(BalloonFragment.getBackgroundColor(activity)); icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity)); messageStatus.setText(Finder.STRING.ICN_MSJ_SEND.toString()); } if (message.status == 4) { messageStatus.setTextSize(11); mensajeLayout.setBackgroundResource(R.drawable.message_out_background); GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground(); drawable.setCornerRadius(radius); drawable.setColor(BalloonFragment.getBackgroundColor(activity)); icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity)); messageStatus.setText(Finder.STRING.ICN_MSJ_OPENED.toString()); icnMensajeTempoDivider.setVisibility(View.GONE); icnMesajeTempo.setVisibility(View.GONE); } else { icnMensajeTempoDivider.setVisibility(View.INVISIBLE); icnMesajeTempo.setVisibility(View.INVISIBLE); } icnMesajeTempo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { JSONObject notifyMessage = new JSONObject(); try { Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId) .executeSingle(); Log.w("mensaje detail", mensaje.status + " : " + mensaje.receptorEmail + " : " + mensaje.tipo); if (mensaje.status != 4) { notifyMessage.put("type", mensaje.tipo); notifyMessage.put("message_id", mensaje.mensajeId); notifyMessage.put("source", mensaje.emisor); notifyMessage.put("target", mensaje.receptor); notifyMessage.put("status", 5); if (SpeakSocket.mSocket != null) if (SpeakSocket.mSocket.connected()) SpeakSocket.mSocket.emit("message-status", notifyMessage); } } catch (JSONException e) { e.printStackTrace(); } } }); } else { mensajeLayout.setBackgroundResource(R.drawable.message_out_background); GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground(); drawable.setCornerRadius(radius); drawable.setColor(BalloonFragment.getFriendBalloon(activity)); if (message.tipo == Integer.parseInt(getString(R.string.MSG_TYPE_BROADCAST_AUDIO))) { messageStatus.setTextSize(15); messageStatus.setText(Finder.STRING.ICN_BROADCAST_FILL.toString()); } rowView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (messageSelected != null) { View vista = messagesList.findViewWithTag(messageSelected); vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE); messageSelected = message.mensajeId; ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) { @Override public void doBack() { View vista = messagesList.findViewWithTag(messageSelected); vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE); ((MainActivity) activity).setOnBackPressedListener(null); messageSelected = null; } }); } else { messageSelected = message.mensajeId; ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) { @Override public void doBack() { View vista = messagesList.findViewWithTag(messageSelected); vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE); ((MainActivity) activity).setOnBackPressedListener(null); messageSelected = null; } }); } Vibrator x = (Vibrator) activity.getApplicationContext() .getSystemService(Context.VIBRATOR_SERVICE); x.vibrate(20); icnMesajeTempo.setVisibility(View.GONE); icnMensajeTempoDivider.setVisibility(View.GONE); icnMesajeCopy.setVisibility(View.VISIBLE); icnMesajeBack.setVisibility(View.VISIBLE); messageMenu.setVisibility(View.VISIBLE); AnimatorSet set = new AnimatorSet(); set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1), ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1), ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1), ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", -100, 0), ObjectAnimator.ofFloat(icnMesajeBack, "translationX", -150, 0)); set.setDuration(200).start(); return false; } }); } /*icnMesajeCopy.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ClipData clip = ClipData.newPlainText("text", messageContent.getText().toString()); ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setPrimaryClip(clip); Toast.makeText(activity, "Copiado", Toast.LENGTH_SHORT).show(); } });*/ icnMesajeBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (message.emisor.equals(u.id)) { getFragmentManager().beginTransaction() .replace(R.id.container2, ForwarForFragment.newInstance(message.mensaje)) .addToBackStack(null).commit(); ((MainActivity) activity).setOnBackPressedListener(null); } else { getFragmentManager().beginTransaction() .replace(R.id.container2, ForwarForFragment.newInstance(message.mensajeTrad)) .addToBackStack(null).commit(); ((MainActivity) activity).setOnBackPressedListener(null); } } }); rowView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (messageSelected != null) { View vista = messagesList.findViewWithTag(messageSelected); if (!messageSelected.equals(message.mensajeId)) { vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE); ((MainActivity) activity).setOnBackPressedListener(null); messageSelected = null; } } final Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId) .executeSingle(); if (mensaje.status == -1) { final JSONObject data = new JSONObject(); try { data.put("message_id", mensaje.mensajeId); data.put("source", mensaje.emisor); data.put("source_email", mensaje.emisorEmail); data.put("target_email", mensaje.receptorEmail); data.put("target", mensaje.receptor); data.put("type", mensaje.tipo); if (!mensaje.fileUploaded) { progressLayout.setVisibility(View.VISIBLE); new Thread(new Runnable() { @Override public void run() { activity.runOnUiThread(new Runnable() { @Override public void run() { uploadAudioToServer(mensaje.audioName, mensaje, data, progressBar, progressLayout, progressText); } }); } }).start(); } else { data.put("audios", mensaje.fileName); if (SpeakSocket.mSocket != null) if (SpeakSocket.mSocket.connected()) { mensaje.status = 1; SpeakSocket.mSocket.emit("message", data); } else { mensaje.status = -1; } mensaje.save(); changeStatus(mensaje.mensajeId, mensaje.status); } } catch (JSONException e) { e.printStackTrace(); } } } }); File audioFile = null; final MediaPlayer mediaPlayer1 = new MediaPlayer(); audioFile = new File(message.audioName); try { mediaPlayer1.setDataSource(audioFile.getAbsolutePath()); mediaPlayer1.prepare(); long timePlayer = mediaPlayer1.getDuration(); long days, hours, minutes, seconds; long secondsTotal = timePlayer / 1000; days = (Math.round(secondsTotal) / 86400); hours = (Math.round(secondsTotal) / 3600) - (days * 24); minutes = (Math.round(secondsTotal) / 60) - (days * 1440) - (hours * 60); seconds = Math.round(secondsTotal) % 60; audioTime.setText(String.format("%02d", minutes) + " : " + String.format("%02d", seconds)); audioSeekBar.setMax(mediaPlayer1.getDuration()); audioSeekBar.setTag(message.mensajeId); mediaPlayer1.release(); } catch (IOException e) { e.printStackTrace(); } final File finalAudioFile = audioFile; playAudio.setOnClickListener(new View.OnClickListener() { boolean isplayAudio = false; @Override public void onClick(View v) { if (activeAudioSeekBarr != null) { if (!activeAudioSeekBarr.getTag().equals(audioSeekBar.getTag())) { isplayAudio = false; } } if (!isplayAudio) { try { if (activeAudioSeekBarr != null) { if (activeAudioSeekBarr.getTag().equals(audioSeekBar.getTag())) { seekHandler.postDelayed(runAudio, 1000); playAudio.setText(Finder.STRING.ICN_PAUSE.toString()); mediaPlayer.start(); } else { if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.release(); } if (activeAudioSeekBarr != null) { activeAudioSeekBarr.setProgress(0); activeAudioSeekBarr.setOnSeekBarChangeListener(null); } if (activeAudioTime != null) { activeAudioTime.setText(activeAudioDuration); } if (!activeAudioDuration.equals("")) { activeAudioDuration = ""; } if (activePlayer != null) { activePlayer.setText(Finder.STRING.ICN_PLAY.toString()); } seekHandler.removeCallbacks(runAudio); mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(finalAudioFile.getAbsolutePath()); mediaPlayer.prepare(); activeAudioDuration = audioTime.getText().toString(); audioSeekBar.setProgress(mediaPlayer.getCurrentPosition()); audioSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { mediaPlayer.seekTo(progress); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); activeAudioSeekBarr = audioSeekBar; activePlayer = playAudio; activeAudioTime = audioTime; seekHandler.postDelayed(runAudio, 1000); mediaPlayer.start(); playAudio.setText(Finder.STRING.ICN_PAUSE.toString()); } } else { if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.release(); } if (activeAudioSeekBarr != null) { activeAudioSeekBarr.setProgress(0); activeAudioSeekBarr.setOnSeekBarChangeListener(null); } if (activeAudioTime != null) { activeAudioTime.setText(activeAudioDuration); } if (!activeAudioDuration.equals("")) { activeAudioDuration = ""; } seekHandler.removeCallbacks(runAudio); mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(finalAudioFile.getAbsolutePath()); mediaPlayer.prepare(); activeAudioDuration = audioTime.getText().toString(); audioSeekBar.setProgress(mediaPlayer.getCurrentPosition()); audioSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { mediaPlayer.seekTo(progress); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); activeAudioSeekBarr = audioSeekBar; activePlayer = playAudio; activeAudioTime = audioTime; seekHandler.postDelayed(runAudio, 1000); mediaPlayer.start(); playAudio.setText(Finder.STRING.ICN_PAUSE.toString()); } //file2.delete(); } catch (IOException e) { e.printStackTrace(); } isplayAudio = true; } else { playAudio.setText(Finder.STRING.ICN_PLAY.toString()); mediaPlayer.pause(); seekHandler.removeCallbacks(runAudio); isplayAudio = false; } } }); }
From source file:me.ububble.speakall.fragment.ConversationGroupFragment.java
public void showMensajeAudio(int position, Context context, final MsgGroups message, View rowView, TextView icnMessageArrow) {//from w w w . j a v a2 s . co m final TextView prevMessages = (TextView) rowView.findViewById(R.id.showprev_messages); TextView messageTime = (TextView) rowView.findViewById(R.id.message_time); final TextView icnMesajeTempo = (TextView) rowView.findViewById(R.id.icn_message_tempo); final View icnMensajeTempoDivider = (View) rowView.findViewById(R.id.icn_message_tempo_divider); final TextView icnMesajeCopy = (TextView) rowView.findViewById(R.id.icn_message_copy); final TextView icnMesajeBack = (TextView) rowView.findViewById(R.id.icn_message_back); TextView messageStatus = (TextView) rowView.findViewById(R.id.message_status); final LinearLayout messageMenu = (LinearLayout) rowView.findViewById(R.id.messages_menu_layout); final LinearLayout mensajeLayout = (LinearLayout) rowView.findViewById(R.id.mensaje_layout); TextView messageDate = (TextView) rowView.findViewById(R.id.message_date); final TextView audioTime = (TextView) rowView.findViewById(R.id.message_audio_time); final SeekBar audioSeekBar = (SeekBar) rowView.findViewById(R.id.audio_seekbar); final TextView playAudio = (TextView) rowView.findViewById(R.id.play_audio); final ProgressBar progressBar = (ProgressBar) rowView.findViewById(R.id.progress_bar); final RelativeLayout progressLayout = (RelativeLayout) rowView.findViewById(R.id.progress_layout); final TextView progressText = (TextView) rowView.findViewById(R.id.progress_message); final CircleImageView imageUser = (CircleImageView) rowView.findViewById(R.id.chat_row_user_pic); final TextView userName = (TextView) rowView.findViewById(R.id.username_text); TFCache.apply(context, messageTime, TFCache.TF_WHITNEY_MEDIUM); TFCache.apply(context, icnMesajeTempo, TFCache.TF_SPEAKALL); TFCache.apply(context, icnMesajeCopy, TFCache.TF_SPEAKALL); TFCache.apply(context, icnMesajeBack, TFCache.TF_SPEAKALL); TFCache.apply(context, messageStatus, TFCache.TF_SPEAKALL); TFCache.apply(context, prevMessages, TFCache.TF_WHITNEY_MEDIUM); TFCache.apply(context, messageDate, TFCache.TF_WHITNEY_MEDIUM); TFCache.apply(context, audioTime, TFCache.TF_WHITNEY_MEDIUM); TFCache.apply(context, userName, TFCache.TF_WHITNEY_MEDIUM); TFCache.apply(context, playAudio, TFCache.TF_SPEAKON); if (position == 0) { if (mensajesTotal > mensajesOffset) { prevMessages.setVisibility(View.VISIBLE); prevMessages.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { prevMessages.setVisibility(View.GONE); if (mensajesTotal - mensajesOffset >= 10) { mensajesLimit = 10; mensajesOffset += mensajesLimit; showPreviousMessages(mensajesOffset); } else { mensajesLimit = mensajesTotal - mensajesOffset; mensajesOffset += mensajesLimit; showPreviousMessages(mensajesOffset); } } }); } } DateFormat dateDay = new SimpleDateFormat("d"); DateFormat dateDayText = new SimpleDateFormat("EEEE"); DateFormat dateMonth = new SimpleDateFormat("MMMM"); DateFormat dateYear = new SimpleDateFormat("yyyy"); DateFormat timeFormat = new SimpleDateFormat("h:mm a"); Calendar fechamsj = Calendar.getInstance(); fechamsj.setTimeInMillis(message.emitedAt); String time = timeFormat.format(fechamsj.getTime()); String dayMessage = dateDay.format(fechamsj.getTime()); String monthMessage = dateMonth.format(fechamsj.getTime()); String yearMessage = dateYear.format(fechamsj.getTime()); String dayMessageText = dateDayText.format(fechamsj.getTime()); char[] caracteres = dayMessageText.toCharArray(); caracteres[0] = Character.toUpperCase(caracteres[0]); dayMessageText = new String(caracteres); Calendar fechaActual = Calendar.getInstance(); String dayActual = dateDay.format(fechaActual.getTime()); String monthActual = dateMonth.format(fechaActual.getTime()); String yearActual = dateYear.format(fechaActual.getTime()); String fechaMostrar = ""; if (dayMessage.equals(dayActual) && monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) { fechaMostrar = getString(R.string.messages_today); } else if (monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) { int days = Integer.parseInt(dayActual) - Integer.parseInt(dayMessage); if (days < 7) { switch (days) { case 1: fechaMostrar = getString(R.string.messages_yesterday); break; default: fechaMostrar = dayMessageText; break; } } else { fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase(); } } else { fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase(); } messageDate.setText(fechaMostrar); if (position != -1) { if (itemAnterior != null) { if (!fechaMostrar.equals(fechaAnterior)) { itemAnterior.findViewById(R.id.message_date).setVisibility(View.VISIBLE); } else { itemAnterior.findViewById(R.id.message_date).setVisibility(View.GONE); } } itemAnterior = rowView; fechaAnterior = fechaMostrar; } else { View v = messagesList.getChildAt(messagesList.getChildCount() - 1); if (v != null) { TextView tv = (TextView) v.findViewById(R.id.message_date); if (tv.getText().toString().equals(fechaMostrar)) { messageDate.setVisibility(View.GONE); } else { messageDate.setVisibility(View.VISIBLE); } } } messageTime.setText(time); if (message.emisor.equals(u.id)) { progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.speak_all_red), PorterDuff.Mode.SRC_IN); int status = 0; try { JSONArray contactos = new JSONArray(message.receptores); for (int i = 0; i < contactos.length(); i++) { JSONObject contacto = contactos.getJSONObject(i); Log.w("STATUS", contacto.getInt("status") + contacto.getString("name")); if (status == 0 || contacto.getInt("status") <= status) { status = contacto.getInt("status"); } } } catch (JSONException e) { e.printStackTrace(); } if (status != -1) { rowView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (messageSelected != null) { View vista = messagesList.findViewWithTag(messageSelected); vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE); messageSelected = message.mensajeId; ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) { @Override public void doBack() { View vista = messagesList.findViewWithTag(messageSelected); vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE); ((MainActivity) activity).setOnBackPressedListener(null); messageSelected = null; } }); } else { messageSelected = message.mensajeId; ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) { @Override public void doBack() { if (messageSelected != null) { View vista = messagesList.findViewWithTag(messageSelected); vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE); ((MainActivity) activity).setOnBackPressedListener(null); messageSelected = null; } } }); } Vibrator x = (Vibrator) activity.getApplicationContext() .getSystemService(Context.VIBRATOR_SERVICE); x.vibrate(30); MsgGroups mensaje = new Select().from(MsgGroups.class) .where("mensajeId = ?", message.mensajeId).executeSingle(); int status = 0; try { JSONArray contactos = new JSONArray(mensaje.receptores); for (int i = 0; i < contactos.length(); i++) { JSONObject contacto = contactos.getJSONObject(i); if (status == 0 || contacto.getInt("status") <= status) { status = contacto.getInt("status"); } } } catch (JSONException e) { e.printStackTrace(); } if (status != 4) { icnMesajeCopy.setVisibility(View.VISIBLE); icnMesajeBack.setVisibility(View.VISIBLE); messageMenu.setVisibility(View.VISIBLE); AnimatorSet set = new AnimatorSet(); set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1), ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1), ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1), ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0), ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0)); set.setDuration(200).start(); } else { icnMesajeCopy.setVisibility(View.VISIBLE); icnMesajeBack.setVisibility(View.VISIBLE); messageMenu.setVisibility(View.VISIBLE); AnimatorSet set = new AnimatorSet(); set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1), ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1), ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1), ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0), ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0)); set.setDuration(200).start(); } return false; } }); } if (status == 1) { messageStatus.setTextSize(16); mensajeLayout.setBackgroundResource(R.drawable.message_out_background); icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity)); messageStatus.setTextColor(getResources().getColor(R.color.speak_all_ligh_gray)); messageStatus.setText(Finder.STRING.ICN_MSJ_SENDING.toString()); ValueAnimator colorAnim = ObjectAnimator.ofFloat(messageStatus, "alpha", 1, 0); colorAnim.setRepeatCount(ValueAnimator.INFINITE); colorAnim.setRepeatMode(ValueAnimator.REVERSE); colorAnim.setDuration(1000).start(); animaciones.put(message.mensajeId, colorAnim); final JSONObject data = new JSONObject(); try { data.put("type", message.tipo); data.put("group_id", message.grupoId); data.put("group_name", grupo.nombreGrupo); data.put("source", message.emisor); data.put("source_lang", message.emisorLang); data.put("source_email", message.emisorEmail); data.put("message", message.mensaje); data.put("translation_required", message.translation); data.put("message_id", message.mensajeId); data.put("targets", new JSONArray(message.receptores)); data.put("delay", message.delay); if (!message.fileUploaded) { progressLayout.setVisibility(View.VISIBLE); new Thread(new Runnable() { @Override public void run() { activity.runOnUiThread(new Runnable() { @Override public void run() { uploadAudioToServer(message.audioName, message, data, progressBar, progressLayout, progressText); } }); } }).start(); } else { data.put("audios", message.fileName); JSONArray targets = new JSONArray(); JSONArray contactos = new JSONArray(grupo.targets); if (SpeakSocket.mSocket != null) { if (SpeakSocket.mSocket.connected()) { for (int i = 0; i < contactos.length(); i++) { JSONObject contacto = contactos.getJSONObject(i); JSONObject newContact = new JSONObject(); Contact contact = new Select().from(Contact.class) .where("id_contact = ?", contacto.getString("name")).executeSingle(); if (contact != null) { if (!contact.idContacto.equals(u.id)) { if (message.translation) newContact.put("lang", contact.lang); else newContact.put("lang", u.lang); newContact.put("name", contact.idContacto); newContact.put("screen_name", contact.screenName); newContact.put("status", 1); targets.put(targets.length(), newContact); } } } data.put("targets", targets); message.receptores = targets.toString(); message.save(); SpeakSocket.mSocket.emit("message", data); } else { for (int i = 0; i < contactos.length(); i++) { JSONObject contacto = contactos.getJSONObject(i); JSONObject newContact = new JSONObject(); Contact contact = new Select().from(Contact.class) .where("id_contact = ?", contacto.getString("name")).executeSingle(); if (contact != null) { if (!contact.idContacto.equals(u.id)) { if (message.translation) newContact.put("lang", contact.lang); else newContact.put("lang", u.lang); newContact.put("name", contact.idContacto); newContact.put("screen_name", contact.screenName); newContact.put("status", -1); targets.put(targets.length(), newContact); } } } message.receptores = targets.toString(); message.save(); } } changeStatus(message.mensajeId); } } catch (JSONException e) { e.printStackTrace(); } } if (status == -1) { messageStatus.setTextSize(11); mensajeLayout.setBackgroundResource(R.drawable.message_errorout_background); icnMessageArrow.setTextColor(getResources().getColor(R.color.speak_all_disable_red)); messageStatus.setText(Finder.STRING.ICN_MSJ_ERROR.toString()); } if (status == 3) { messageStatus.setTextSize(11); mensajeLayout.setBackgroundResource(R.drawable.message_out_background); icnMessageArrow.setTextColor(getResources().getColor(R.color.speak_all_disable_red)); messageStatus.setText(Finder.STRING.ICN_MSJ_CLOSED.toString()); } if (status == 2) { messageStatus.setTextSize(16); mensajeLayout.setBackgroundResource(R.drawable.message_out_background); icnMessageArrow.setTextColor(getResources().getColor(R.color.speak_all_disable_red)); messageStatus.setText(Finder.STRING.ICN_MSJ_SEND.toString()); } if (status == 4) { messageStatus.setTextSize(11); mensajeLayout.setBackgroundResource(R.drawable.message_out_background); icnMessageArrow.setTextColor(getResources().getColor(R.color.speak_all_disable_red)); messageStatus.setText(Finder.STRING.ICN_MSJ_OPENED.toString()); } } else { final Contact contacto = new Select().from(Contact.class).where(" id_contact= ?", message.emisor) .executeSingle(); if (contacto != null) { new Thread(new Runnable() { @Override public void run() { activity.runOnUiThread(new Runnable() { @Override public void run() { if (contacto.photo != null) { Bitmap bmp = BitmapFactory.decodeByteArray(contacto.photo, 0, contacto.photo.length); imageUser.setImageBitmap(bmp); userName.setText(contacto.fullName); } } }); } }).start(); } rowView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (messageSelected != null) { View vista = messagesList.findViewWithTag(messageSelected); vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE); messageSelected = message.mensajeId; ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) { @Override public void doBack() { View vista = messagesList.findViewWithTag(messageSelected); vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE); ((MainActivity) activity).setOnBackPressedListener(null); messageSelected = null; } }); } else { messageSelected = message.mensajeId; ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) { @Override public void doBack() { View vista = messagesList.findViewWithTag(messageSelected); vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE); ((MainActivity) activity).setOnBackPressedListener(null); messageSelected = null; } }); } Vibrator x = (Vibrator) activity.getApplicationContext() .getSystemService(Context.VIBRATOR_SERVICE); x.vibrate(20); icnMesajeCopy.setVisibility(View.VISIBLE); icnMesajeBack.setVisibility(View.VISIBLE); messageMenu.setVisibility(View.VISIBLE); AnimatorSet set = new AnimatorSet(); set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1), ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1), ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1), ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", -100, 0), ObjectAnimator.ofFloat(icnMesajeBack, "translationX", -150, 0)); set.setDuration(200).start(); return false; } }); } icnMesajeBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (message.emisor.equals(u.id)) { getFragmentManager().beginTransaction() .replace(R.id.container2, ForwarForFragment.newInstance(message.mensaje)) .addToBackStack(null).commit(); ((MainActivity) activity).setOnBackPressedListener(null); } else { getFragmentManager().beginTransaction() .replace(R.id.container2, ForwarForFragment.newInstance(message.mensajeTrad)) .addToBackStack(null).commit(); ((MainActivity) activity).setOnBackPressedListener(null); } } }); rowView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (messageSelected != null) { View vista = messagesList.findViewWithTag(messageSelected); if (!messageSelected.equals(message.mensajeId)) { vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE); ((MainActivity) activity).setOnBackPressedListener(null); messageSelected = null; } } final MsgGroups mensaje = new Select().from(MsgGroups.class) .where("mensajeId = ?", message.mensajeId).executeSingle(); int status = 0; try { JSONArray contactos = new JSONArray(mensaje.receptores); for (int i = 0; i < contactos.length(); i++) { JSONObject contacto = contactos.getJSONObject(i); if (status == 0 || contacto.getInt("status") <= status) { status = contacto.getInt("status"); } } } catch (JSONException e) { e.printStackTrace(); } if (status == -1) { final JSONObject data = new JSONObject(); try { data.put("type", mensaje.tipo); data.put("group_id", mensaje.grupoId); data.put("group_name", grupo.nombreGrupo); data.put("source", mensaje.emisor); data.put("source_lang", mensaje.emisorLang); data.put("source_email", mensaje.emisorEmail); data.put("message", mensaje.mensaje); data.put("translation_required", mensaje.translation); data.put("message_id", mensaje.mensajeId); data.put("targets", new JSONArray(mensaje.receptores)); data.put("delay", mensaje.delay); if (!mensaje.fileUploaded) { progressLayout.setVisibility(View.VISIBLE); new Thread(new Runnable() { @Override public void run() { activity.runOnUiThread(new Runnable() { @Override public void run() { uploadAudioToServer(mensaje.audioName, mensaje, data, progressBar, progressLayout, progressText); } }); } }).start(); } else { data.put("audios", mensaje.fileName); JSONArray targets = new JSONArray(); JSONArray contactos = new JSONArray(grupo.targets); if (SpeakSocket.mSocket != null) { if (SpeakSocket.mSocket.connected()) { for (int i = 0; i < contactos.length(); i++) { JSONObject contacto = contactos.getJSONObject(i); JSONObject newContact = new JSONObject(); Contact contact = new Select().from(Contact.class) .where("id_contact = ?", contacto.getString("name")) .executeSingle(); if (contact != null) { if (!contact.idContacto.equals(u.id)) { if (mensaje.translation) newContact.put("lang", contact.lang); else newContact.put("lang", u.lang); newContact.put("name", contact.idContacto); newContact.put("screen_name", contact.screenName); newContact.put("status", 1); targets.put(targets.length(), newContact); } } } data.put("targets", targets); mensaje.receptores = targets.toString(); mensaje.save(); SpeakSocket.mSocket.emit("message", data); } else { for (int i = 0; i < contactos.length(); i++) { JSONObject contacto = contactos.getJSONObject(i); JSONObject newContact = new JSONObject(); Contact contact = new Select().from(Contact.class) .where("id_contact = ?", contacto.getString("name")) .executeSingle(); if (contact != null) { if (!contact.idContacto.equals(u.id)) { if (mensaje.translation) newContact.put("lang", contact.lang); else newContact.put("lang", u.lang); newContact.put("name", contact.idContacto); newContact.put("screen_name", contact.screenName); newContact.put("status", -1); targets.put(targets.length(), newContact); } } } mensaje.receptores = targets.toString(); mensaje.save(); } } changeStatus(mensaje.mensajeId); } } catch (JSONException e) { e.printStackTrace(); } } } }); File audioFile = null; final MediaPlayer mediaPlayer1 = new MediaPlayer(); audioFile = new File(message.audioName); try { mediaPlayer1.setDataSource(audioFile.getAbsolutePath()); mediaPlayer1.prepare(); long timePlayer = mediaPlayer1.getDuration(); long days, hours, minutes, seconds; long secondsTotal = timePlayer / 1000; days = (Math.round(secondsTotal) / 86400); hours = (Math.round(secondsTotal) / 3600) - (days * 24); minutes = (Math.round(secondsTotal) / 60) - (days * 1440) - (hours * 60); seconds = Math.round(secondsTotal) % 60; audioTime.setText(String.format("%02d", minutes) + " : " + String.format("%02d", seconds)); audioSeekBar.setMax(mediaPlayer1.getDuration()); audioSeekBar.setTag(message.mensajeId); mediaPlayer1.release(); } catch (IOException e) { e.printStackTrace(); } final File finalAudioFile = audioFile; playAudio.setOnClickListener(new View.OnClickListener() { boolean isplayAudio = false; @Override public void onClick(View v) { if (activeAudioSeekBarr != null) { if (!activeAudioSeekBarr.getTag().equals(audioSeekBar.getTag())) { isplayAudio = false; } } if (!isplayAudio) { try { if (activeAudioSeekBarr != null) { if (activeAudioSeekBarr.getTag().equals(audioSeekBar.getTag())) { seekHandler.postDelayed(runAudio, 1000); playAudio.setText(Finder.STRING.ICN_PAUSE.toString()); mediaPlayer.start(); } else { if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.release(); } if (activeAudioSeekBarr != null) { activeAudioSeekBarr.setProgress(0); activeAudioSeekBarr.setOnSeekBarChangeListener(null); } if (activeAudioTime != null) { activeAudioTime.setText(activeAudioDuration); } if (!activeAudioDuration.equals("")) { activeAudioDuration = ""; } if (activePlayer != null) { activePlayer.setText(Finder.STRING.ICN_PLAY.toString()); } seekHandler.removeCallbacks(runAudio); mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(finalAudioFile.getAbsolutePath()); mediaPlayer.prepare(); activeAudioDuration = audioTime.getText().toString(); audioSeekBar.setProgress(mediaPlayer.getCurrentPosition()); audioSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { mediaPlayer.seekTo(progress); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); activeAudioSeekBarr = audioSeekBar; activePlayer = playAudio; activeAudioTime = audioTime; seekHandler.postDelayed(runAudio, 1000); mediaPlayer.start(); playAudio.setText(Finder.STRING.ICN_PAUSE.toString()); } } else { if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.release(); } if (activeAudioSeekBarr != null) { activeAudioSeekBarr.setProgress(0); activeAudioSeekBarr.setOnSeekBarChangeListener(null); } if (activeAudioTime != null) { activeAudioTime.setText(activeAudioDuration); } if (!activeAudioDuration.equals("")) { activeAudioDuration = ""; } seekHandler.removeCallbacks(runAudio); mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(finalAudioFile.getAbsolutePath()); mediaPlayer.prepare(); activeAudioDuration = audioTime.getText().toString(); audioSeekBar.setProgress(mediaPlayer.getCurrentPosition()); audioSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { mediaPlayer.seekTo(progress); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); activeAudioSeekBarr = audioSeekBar; activePlayer = playAudio; activeAudioTime = audioTime; seekHandler.postDelayed(runAudio, 1000); mediaPlayer.start(); playAudio.setText(Finder.STRING.ICN_PAUSE.toString()); } //file2.delete(); } catch (IOException e) { e.printStackTrace(); } isplayAudio = true; } else { playAudio.setText(Finder.STRING.ICN_PLAY.toString()); mediaPlayer.pause(); seekHandler.removeCallbacks(runAudio); isplayAudio = false; } } }); }