Example usage for android.media MediaPlayer release

List of usage examples for android.media MediaPlayer release

Introduction

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

Prototype

public void release() 

Source Link

Document

Releases resources associated with this MediaPlayer object.

Usage

From source file:it.iziozi.iziozi.gui.IOBoardActivity.java

public void tapOnSpeakableButton(final IOSpeakableImageButton spkBtn, final Integer level) {
    if (IOGlobalConfiguration.isEditing) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();

        View layoutView = inflater.inflate(R.layout.editmode_alertview, null);

        builder.setTitle(getString(R.string.choose));

        builder.setView(layoutView);//from  w  w w. j a  v  a  2 s .  c o m

        final AlertDialog dialog = builder.create();

        final Switch matrioskaSwitch = (Switch) layoutView.findViewById(R.id.editModeAlertToggleBoard);
        Button editPictoButton = (Button) layoutView.findViewById(R.id.editModeAlertActionPicture);
        final Button editBoardButton = (Button) layoutView.findViewById(R.id.editModeAlertActionBoard);

        matrioskaSwitch.setChecked(spkBtn.getIsMatrioska());
        editBoardButton.setEnabled(spkBtn.getIsMatrioska());

        matrioskaSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                spkBtn.setIsMatrioska(isChecked);
                editBoardButton.setEnabled(isChecked);
            }
        });

        editPictoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //spkBtn.showInsertDialog();
                Intent cIntent = new Intent(getApplicationContext(), IOCreateButtonActivity.class);
                cIntent.putExtra(BUTTON_INDEX,
                        mActualLevel.getBoardAtIndex(mActualIndex).getButtons().indexOf(spkBtn));

                cIntent.putExtra(BUTTON_TEXT, spkBtn.getSentence());
                cIntent.putExtra(BUTTON_TITLE, spkBtn.getmTitle());
                cIntent.putExtra(BUTTON_IMAGE_FILE, spkBtn.getmImageFile());
                cIntent.putExtra(BUTTON_AUDIO_FILE, spkBtn.getAudioFile());

                startActivityForResult(cIntent, CREATE_BUTTON_CODE);

                matrioskaSwitch.setOnCheckedChangeListener(null);

                dialog.dismiss();
            }
        });

        editBoardButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                IOLevel nestedBoard = spkBtn.getLevel();

                pushLevel(nestedBoard);

                matrioskaSwitch.setOnCheckedChangeListener(null);

                dialog.dismiss();
            }
        });

        dialog.show();

    } else {

        if (IOGlobalConfiguration.isScanMode) {
            IOSpeakableImageButton scannedButton = mActualLevel.getBoardAtIndex(mActualIndex).getButtons()
                    .get(mActualScanIndex);
            if (scannedButton.getAudioFile() != null && scannedButton.getAudioFile().length() > 0) {

                final MediaPlayer mPlayer = new MediaPlayer();
                try {
                    mPlayer.setDataSource(scannedButton.getAudioFile());
                    mPlayer.prepare();

                    mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            mPlayer.release();

                        }
                    });

                    mPlayer.start();

                } catch (IOException e) {
                    Log.e("playback_debug", "prepare() failed");
                }
            } else if (mCanSpeak) {
                Log.d("speakable_debug", "should say: " + scannedButton.getSentence());
                if (scannedButton.getSentence() == "")
                    tts.speak(getResources().getString(R.string.tts_nosentence), TextToSpeech.QUEUE_FLUSH,
                            null);
                else
                    tts.speak(scannedButton.getSentence(), TextToSpeech.QUEUE_FLUSH, null);
            } else {
                Toast.makeText(this, getResources().getString(R.string.tts_notinitialized), Toast.LENGTH_LONG)
                        .show();
            }

            if (scannedButton.getIsMatrioska() && null != scannedButton.getLevel()) {
                pushLevel(scannedButton.getLevel());
            }
        } else {

            if (spkBtn.getAudioFile() != null && spkBtn.getAudioFile().length() > 0) {

                final MediaPlayer mPlayer = new MediaPlayer();
                try {
                    mPlayer.setDataSource(spkBtn.getAudioFile());
                    mPlayer.prepare();

                    mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            mPlayer.release();

                        }
                    });

                    mPlayer.start();

                } catch (IOException e) {
                    Log.e("playback_debug", "prepare() failed");
                }
            } else if (mCanSpeak) {
                Log.d("speakable_debug", "should say: " + spkBtn.getSentence());
                if (spkBtn.getSentence() == "")
                    tts.speak(getResources().getString(R.string.tts_nosentence), TextToSpeech.QUEUE_FLUSH,
                            null);
                else
                    tts.speak(spkBtn.getSentence(), TextToSpeech.QUEUE_FLUSH, null);
            } else {
                Toast.makeText(this, getResources().getString(R.string.tts_notinitialized), Toast.LENGTH_LONG)
                        .show();
            }

            if (spkBtn.getIsMatrioska() && null != spkBtn.getLevel()) {
                pushLevel(spkBtn.getLevel());
            }
        }
    }
}

From source file:com.sentaroh.android.TaskAutomation.TaskExecutor.java

final static public void playBackRingtone(TaskManagerParms taskMgrParms, EnvironmentParms envParms,
        CommonUtilities util, TaskResponse taskResponse, ActionResponse ar, String dlg_id, String rt, String rn,
        String rp, String vol_left, String vol_right) {
    ar.action_resp = ActionResponse.ACTION_SUCCESS;
    if (!isRingerModeNormal(envParms)) {
        ar.action_resp = ActionResponse.ACTION_WARNING;
        ar.resp_msg_text = taskMgrParms.teMsgs.msgs_thread_task_exec_ignore_sound_ringer_not_normal;
        return;/*from   w  w w .  jav  a  2 s.  co m*/
    }
    MediaPlayer player = MediaPlayer.create(taskMgrParms.context, Uri.parse("content://media" + rp));
    //      taskResponse.active_action_name=action;
    if (player != null) {
        int duration = 0;
        if (!rt.equals(PROFILE_ACTION_RINGTONE_TYPE_NOTIFICATION))
            duration = RINGTONE_PLAYBACK_TIME;
        else
            duration = player.getDuration();

        if (duration >= 5000) {
            TaskManager.showMessageDialog(taskMgrParms, envParms, util, taskResponse.active_group_name,
                    taskResponse.active_task_name, taskResponse.active_action_name,
                    taskResponse.active_dialog_id, MESSAGE_DIALOG_MESSAGE_TYPE_SOUND, rt + " " + rn);

        }
        if (!vol_left.equals("-1") && !vol_left.equals(""))
            player.setVolume(Float.valueOf(vol_left) / 100, Float.valueOf(vol_right) / 100);
        player.start();
        waitTimeTc(taskResponse, duration + 10);
        if (!taskResponse.active_thread_ctrl.isEnable()) {
            ar.action_resp = ActionResponse.ACTION_CANCELLED;
            ar.resp_msg_text = "Action was cancelled";
        }
        player.stop();
        player.release();
        if (duration >= 5000) {
            TaskManager.closeMessageDialog(taskMgrParms, envParms, util, taskResponse);
        }
    } else {
        ar.action_resp = ActionResponse.ACTION_ERROR;
        ar.resp_msg_text = String.format(taskMgrParms.teMsgs.msgs_thread_task_play_sound_error, rp);
    }
}

From source file:org.moire.ultrasonic.service.DownloadServiceImpl.java

@SuppressLint("NewApi")
@Override/*from  www .  j a v  a 2  s  . c o m*/
public void onCreate() {
    super.onCreate();

    new Thread(new Runnable() {
        @Override
        public void run() {
            Thread.currentThread().setName("DownloadServiceImpl");

            Looper.prepare();

            if (mediaPlayer != null) {
                mediaPlayer.release();
            }

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

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

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

            mediaPlayerLooper = Looper.myLooper();
            mediaPlayerHandler = new Handler(mediaPlayerLooper);
            Looper.loop();
        }
    }).start();

    audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
    setUpRemoteControlClient();

    if (equalizerAvailable) {
        equalizerController = new EqualizerController(this, mediaPlayer);
        if (!equalizerController.isAvailable()) {
            equalizerController = null;
        } else {
            equalizerController.loadSettings();
        }
    }
    if (visualizerAvailable) {
        visualizerController = new VisualizerController(mediaPlayer);
        if (!visualizerController.isAvailable()) {
            visualizerController = null;
        }
    }

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

    instance = this;
    lifecycleSupport.onCreate();
}

From source file:org.botlibre.sdk.activity.ChatActivity.java

public MediaPlayer playAudio(String audio, boolean loop, boolean cache, boolean start) {
    try {/* w ww  . ja  va 2 s . c  o m*/
        Uri audioUri = null;
        if (cache) {
            audioUri = HttpGetVideoAction.fetchVideo(this, audio);
        }
        if (audioUri == null) {
            audioUri = Uri.parse(MainActivity.connection.fetchImage(audio).toURI().toString());
        }
        final MediaPlayer audioPlayer = new MediaPlayer();
        audioPlayer.setDataSource(getApplicationContext(), audioUri);
        audioPlayer.setOnErrorListener(new OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Log.wtf("Audio error", "what:" + what + " extra:" + extra);
                audioPlayer.stop();
                audioPlayer.release();
                return true;
            }
        });
        audioPlayer.setOnCompletionListener(new OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                audioPlayer.release();
                runOnUiThread(new Runnable() {
                    public void run() {
                        try {
                            beginListening();
                        } catch (Exception e) {
                            Log.e("ChatActivity", "MediaPlayer: " + e.getMessage());
                        }
                    }
                });
            }
        });
        audioPlayer.prepare();
        audioPlayer.setLooping(loop);
        if (start) {
            audioPlayer.start();
        }
        return audioPlayer;
    } catch (Exception exception) {
        Log.wtf(exception.toString(), exception);
        return null;
    }
}

From source file:dk.bearware.gui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String serverName = getIntent().getStringExtra(ServerEntry.KEY_SERVERNAME);
    if ((serverName != null) && !serverName.isEmpty())
        setTitle(serverName);/*  ww  w.  j ava2 s . co  m*/
    getActionBar().setDisplayHomeAsUpEnabled(true);

    restarting = (savedInstanceState != null);
    accessibilityAssistant = new AccessibilityAssistant(this);
    audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mediaButtonEventReceiver = new ComponentName(getPackageName(), MediaButtonEventReceiver.class.getName());
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    wakeLock.setReferenceCounted(false);

    channelsAdapter = new ChannelListAdapter(this.getBaseContext());
    filesAdapter = new FileListAdapter(this, this, accessibilityAssistant);
    textmsgAdapter = new TextMessageAdapter(this.getBaseContext(), accessibilityAssistant);
    mediaAdapter = new MediaAdapter(this.getBaseContext());

    // Create the adapter that will return a fragment for each of the five
    // primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager.setOnPageChangeListener(mSectionsPagerAdapter);

    setupButtons();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        final MediaPlayer mMediaPlayer;
        mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.silence);
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mMediaPlayer.release();
            }
        });
        mMediaPlayer.start();
    }
}

From source file:org.botlibre.sdk.activity.ChatActivity.java

public void response(final ChatResponse response) {
    if (speechPlayer != null || tts != null) {
        try {/*  w  w  w  . j  a v  a 2s.  c o m*/
            tts.stop();
            speechPlayer.pause();
        } catch (Exception ignore) {
            Log.e("RESPONSE", "Error: " + ignore.getMessage());
        }
    }
    //needs when calling "sleep" or the its not going to let the mic off
    //also to stop the mic until the bot finish the sentence
    try {
        stopListening();
        this.response = response;

        String status = "";
        if (response.emote != null && !response.emote.equals("NONE")) {
            status = status + response.emote.toLowerCase();
        }
        if (response.action != null) {
            if (!status.isEmpty()) {
                status = status + " ";
            }
            status = status + response.action;
        }
        if (response.pose != null) {
            if (!status.isEmpty()) {
                status = status + " ";
            }
            status = status + response.pose;
        }

        if (response.command != null) {
            JSONObject jsonObject = response.getCommand();
            Command command = new Command(this, jsonObject);
        }

        TextView statusView = (TextView) findViewById(R.id.statusText);
        statusView.setText(status);

        final String text = response.message;
        final ListView list = (ListView) findViewById(R.id.chatList);
        if (text == null) {
            list.post(new Runnable() {
                @Override
                public void run() {
                    ChatResponse ready = new ChatResponse();
                    ready.message = "ready";
                    messages.add(ready);
                    ((ChatListAdapter) list.getAdapter()).notifyDataSetChanged();
                    list.invalidateViews();
                    if (list.getCount() > 2) {
                        list.setSelection(list.getCount() - 2);
                    }
                    beginListening();
                }
            });
            return;
        }
        list.post(new Runnable() {
            @Override
            public void run() {
                messages.add(response);
                ((ChatListAdapter) list.getAdapter()).notifyDataSetChanged();
                list.invalidateViews();
                if (list.getCount() > 2) {
                    list.setSelection(list.getCount() - 2);
                }
            }
        });

        WebView responseView = (WebView) findViewById(R.id.responseText);
        String html = Utils.linkHTML(text);
        if (html.contains("<") && html.contains(">")) {
            html = linkPostbacks(html);
        }
        responseView.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);

        boolean talk = (text.trim().length() > 0) && (MainActivity.deviceVoice
                || (this.response.speech != null && this.response.speech.length() > 0));
        if (MainActivity.sound && talk) {
            if (!MainActivity.disableVideo && !videoError && this.response.isVideo()
                    && this.response.isVideoTalk()) {

                videoView.setOnPreparedListener(new OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        try {
                            mp.setLooping(true);
                            if (!MainActivity.deviceVoice) {
                                // Voice audio
                                speechPlayer = playAudio(response.speech, false, false, false);
                                speechPlayer.setOnCompletionListener(new OnCompletionListener() {
                                    @Override
                                    public void onCompletion(MediaPlayer mp) {
                                        mp.release();
                                        videoView.post(new Runnable() {
                                            public void run() {
                                                cycleVideo(response);
                                            }
                                        });
                                        runOnUiThread(new Runnable() {
                                            public void run() {
                                                if (!music) {
                                                    beginListening();
                                                }
                                            }
                                        });
                                    }
                                });

                                speechPlayer.start();
                            } else {
                                HashMap<String, String> params = new HashMap<String, String>();
                                params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "id");

                                tts.speak(Utils.stripTags(text), TextToSpeech.QUEUE_FLUSH, params);
                            }
                        } catch (Exception exception) {
                            Log.wtf(exception.getMessage(), exception);
                        }
                    }
                });
                playVideo(this.response.avatarTalk, false);
            } else if (talk) {
                if (!MainActivity.deviceVoice) {
                    // Voice audio
                    playAudio(this.response.speech, false, false, true);
                } else {
                    HashMap<String, String> params = new HashMap<String, String>();
                    params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "id");

                    this.tts.speak(Utils.stripTags(text), TextToSpeech.QUEUE_FLUSH, params);
                }
            }
        } else if (talk && (!MainActivity.disableVideo && !videoError && this.response.isVideo()
                && this.response.avatarTalk != null)) {
            videoView.setOnPreparedListener(new OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.setLooping(false);
                }
            });
            videoView.setOnCompletionListener(new OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    videoView.setOnCompletionListener(null);
                    cycleVideo(response);
                }
            });
            playVideo(this.response.avatarTalk, false);
            runOnUiThread(new Runnable() {
                public void run() {
                    beginListening();
                }
            });
        } else {
            runOnUiThread(new Runnable() {
                public void run() {
                    beginListening();
                }
            });
        }
    } catch (Exception exception) {
        Log.wtf(exception.getMessage(), exception);
    }
    if (micLastStat) {
        MainActivity.listenInBackground = true;
    }
}

From source file:org.catrobat.catroid.ui.controller.SoundController.java

private void handleSoundInfo(SoundViewHolder holder, SoundInfo soundInfo, SoundBaseAdapter soundAdapter,
        int position, Context context) {
    try {//from   w  w w .  ja va2s.  c  o  m
        MediaPlayer tempPlayer = new MediaPlayer();
        tempPlayer.setDataSource(soundInfo.getAbsolutePath());
        tempPlayer.prepare();

        long milliseconds = tempPlayer.getDuration();
        long seconds = milliseconds / 1000;
        if (seconds == 0) {
            seconds = 1;
        }
        String timeDisplayed = DateUtils.formatElapsedTime(seconds);

        holder.timePlayedChronometer.setText(timeDisplayed);
        holder.timePlayedChronometer.setVisibility(Chronometer.VISIBLE);

        if (soundAdapter.getCurrentPlayingPosition() == Constants.NO_POSITION) {
            SoundBaseAdapter.setElapsedMilliSeconds(0);
        } else {
            SoundBaseAdapter.setElapsedMilliSeconds(
                    SystemClock.elapsedRealtime() - SoundBaseAdapter.getCurrentPlayingBase());
        }

        if (soundInfo.isPlaying) {
            holder.playAndStopButton.setImageResource(R.drawable.ic_media_stop);
            holder.playAndStopButton.setContentDescription(context.getString(R.string.sound_stop));

            if (soundAdapter.getCurrentPlayingPosition() == Constants.NO_POSITION) {
                startPlayingSound(holder.timePlayedChronometer, position, soundAdapter);
            } else if ((position == soundAdapter.getCurrentPlayingPosition())
                    && (SoundBaseAdapter.getElapsedMilliSeconds() > (milliseconds - 1000))) {
                stopPlayingSound(soundInfo, holder.timePlayedChronometer, soundAdapter);
            } else {
                continuePlayingSound(holder.timePlayedChronometer, SystemClock.elapsedRealtime());
            }
        } else {
            holder.playAndStopButton.setImageResource(R.drawable.ic_media_play);
            holder.playAndStopButton.setContentDescription(context.getString(R.string.sound_play));
            stopPlayingSound(soundInfo, holder.timePlayedChronometer, soundAdapter);
        }

        tempPlayer.reset();
        tempPlayer.release();
    } catch (IOException ioException) {
        Log.e(TAG, "Cannot get view.", ioException);
    }
}

From source file:com.andrew.apollo.MusicPlaybackService.java

private static void mediaPlayerAction(MediaPlayer mediaPlayer, MediaPlayerAction action) {
    try {//from   w w  w  .  ja  v  a2s .c  o m
        switch (action) {
        case START:
            mediaPlayer.start();
            return;
        case RELEASE:
            mediaPlayer.release();
            return;
        case RESET:
            mediaPlayer.reset();
        }
    } catch (Throwable ignored) {
    }
}

From source file:hku.fyp14017.blencode.ui.controller.SoundController.java

private void handleSoundInfo(SoundViewHolder holder, SoundInfo soundInfo, SoundBaseAdapter soundAdapter,
        int position, Context context) {
    try {//from  w ww.  ja  v a  2  s.c om
        MediaPlayer tempPlayer = new MediaPlayer();
        tempPlayer.setDataSource(soundInfo.getAbsolutePath());
        tempPlayer.prepare();

        long milliseconds = tempPlayer.getDuration();
        long seconds = milliseconds / 1000;
        if (seconds == 0) {
            seconds = 1;
        }
        String timeDisplayed = DateUtils.formatElapsedTime(seconds);

        holder.timePlayedChronometer.setText(timeDisplayed);
        holder.timePlayedChronometer.setVisibility(Chronometer.VISIBLE);

        if (soundAdapter.getCurrentPlayingPosition() == Constants.NO_POSITION) {
            SoundBaseAdapter.setElapsedMilliSeconds(0);
        } else {
            SoundBaseAdapter.setElapsedMilliSeconds(
                    SystemClock.elapsedRealtime() - SoundBaseAdapter.getCurrentPlayingBase());
        }

        if (soundInfo.isPlaying) {
            holder.playAndStopButton.setImageResource(hku.fyp14017.blencode.R.drawable.ic_media_stop);
            holder.playAndStopButton
                    .setContentDescription(context.getString(hku.fyp14017.blencode.R.string.sound_stop));

            if (soundAdapter.getCurrentPlayingPosition() == Constants.NO_POSITION) {
                startPlayingSound(holder.timePlayedChronometer, position, soundAdapter);
            } else if ((position == soundAdapter.getCurrentPlayingPosition())
                    && (SoundBaseAdapter.getElapsedMilliSeconds() > (milliseconds - 1000))) {
                stopPlayingSound(soundInfo, holder.timePlayedChronometer, soundAdapter);
            } else {
                continuePlayingSound(holder.timePlayedChronometer, SystemClock.elapsedRealtime());
            }
        } else {
            holder.playAndStopButton.setImageResource(hku.fyp14017.blencode.R.drawable.ic_media_play);
            holder.playAndStopButton
                    .setContentDescription(context.getString(hku.fyp14017.blencode.R.string.sound_play));
            stopPlayingSound(soundInfo, holder.timePlayedChronometer, soundAdapter);
        }

        tempPlayer.reset();
        tempPlayer.release();
    } catch (IOException ioException) {
        Log.e(TAG, "Cannot get view.", ioException);
    }
}

From source file:com.stikyhive.stikyhive.ChattingActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    getWindow().setBackgroundDrawableResource(R.drawable.chat_bg);
    // this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    recipientStkid = getIntent().getExtras().getString("recipientStkid");
    chatRecipient = getIntent().getExtras().getString("chatRecipient");
    chatRecipientUrl = getIntent().getExtras().getString("chatRecipientUrl");
    senderToken = getIntent().getExtras().getString("senderToken");
    recipientToken = getIntent().getExtras().getString("recipientToken");
    noti = getIntent().getExtras().getBoolean("noti");
    message = getIntent().getExtras().getString("message");
    rows = getIntent().getExtras().getInt("rows");
    flagChatting = true;//  ww  w. jav  a2  s  .  com
    pref = PreferenceManager.getDefaultSharedPreferences(this);
    offerId = 0;
    offerStatus = 0;
    ws = new JsonWebService();
    dbHelper = new DBHelper(this);
    dialog = new ProgressDialog(this);
    listChatContact = new ArrayList<>();
    listChatContact = dbHelper.getChatContact();
    Log.i(" Chat Contact ", " " + listChatContact.size());
    metrics = this.getResources().getDisplayMetrics();
    //to change font
    faceSemi_bold = Typeface.createFromAsset(getAssets(), fontOSSemi_bold);
    Typeface faceLight = Typeface.createFromAsset(getAssets(), fontOSLight);
    faceRegular = Typeface.createFromAsset(getAssets(), fontOSRegular);

    imageLoader = ImageLoader.getInstance();
    if (!imageLoader.isInited()) {
        imageLoader.init(ImageLoaderConfiguration.createDefault(this));
    }

    start = new Date();
    SimpleDateFormat oFormat = new SimpleDateFormat("dd MMM HH:mm");
    timeSend = oFormat.format(start);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.chat);

    layoutTalk = (LinearLayout) findViewById(R.id.layoutTalk);
    txtUserName = (TextView) findViewById(R.id.txtChatName);
    edTxtMsg = (EditText) findViewById(R.id.edTxtMsg);
    imgViewProfile = (ImageView) findViewById(R.id.imgViewChat);
    imgViewAddCon = (ImageView) findViewById(R.id.imgAddContact);
    lv = (ListView) findViewById(R.id.listView1);
    layoutLabel = (LinearLayout) findViewById(R.id.layoutLabel);
    txtLabel1 = (TextView) findViewById(R.id.txtLabel1);
    txtLabel2 = (TextView) findViewById(R.id.txtLabel2);
    txtLabel3 = (TextView) findViewById(R.id.txtLabel3);
    txtLabel2.setText(" " + chatRecipient + " ");
    txtLabel1.setTypeface(faceLight);
    txtLabel2.setTypeface(faceRegular);
    txtLabel3.setTypeface(faceLight);

    for (ChatContact contact : listChatContact) {
        if (contact.getContactId().equals(recipientStkid)) {
            imgViewAddCon.setVisibility(View.INVISIBLE);
            layoutLabel.setVisibility(View.GONE);
            break;
        }
    }
    Log.i(TAG, " come back again");
    adapter = new ChatArrayAdapter(this, R.layout.chatting_listview, faceSemi_bold, faceRegular, recipientStkid,
            senderToken, recipientToken);
    lv.setAdapter(adapter);
    // adapter.add(new StikyChat(chatRecipientUrl, "Hello", false, "12.10.2015", "12.1.2014"));

    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
    // BEGIN_INCLUDE (change_colors)
    // Set the color scheme of the SwipeRefreshLayout by providing 4 color resource ids
    swipeRefreshLayout.setColorScheme(R.color.swipe_color_1, R.color.swipe_color_2, R.color.swipe_color_3,
            R.color.swipe_color_4);
    limitMsg = 7;
    // END_INCLUDE (change_colors)
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            Log.i(" Refresh Layout ", "onRefresh called from SwipeRefreshLayout");
            if (limitMsg < rows) {
                Log.i("Limit Message ", " " + limitMsg);
                limitMsg *= 2;
                fetchRecords();
            } else if ((!(rows <= 7)) && limitMsg > rows && (limitMsg - rows < 7)) {
                fetchRecords();
            } else {
                Log.i("No data ", "to refresh");
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(getApplicationContext(), "No data to refresh!", Toast.LENGTH_SHORT).show();
            }
            // initiateRefresh();
        }
    });

    LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LinearLayout headerLayout = (LinearLayout) findViewById(R.id.header);
    View header = inflator.inflate(R.layout.header, null);

    TextView textView = (TextView) header.findViewById(R.id.textView1);
    textView.setText("StikyChat");
    textView.setTypeface(faceSemi_bold);
    textView.setVisibility(View.VISIBLE);
    headerLayout.addView(header);
    LinearLayout layoutRight = (LinearLayout) header.findViewById(R.id.layoutRight);
    layoutRight.setVisibility(View.GONE);

    txtUserName.setText(chatRecipient);
    Log.i(TAG, "Activity Name " + txtUserName.getText().toString());
    txtUserName.setTypeface(faceSemi_bold);

    String url = "";

    Log.i(TAG, " ^^^ " + chatRecipientUrl + " ");
    if (chatRecipientUrl != null) {
        if (chatRecipientUrl.contains("http")) {
            url = chatRecipientUrl;
        } else if (chatRecipientUrl != "null") {
            url = this.getResources().getString(R.string.url) + "/" + chatRecipientUrl;
        }
    }
    addAndroidUniversalImageLoader(imgViewProfile, url);
    //        if (noti && (!message.equals(""))) {
    //            adapter.add(new StikyChat(chatRecipientUrl, message, true, timeSend, ""));
    //            lv.smoothScrollToPosition(adapter.getCount() - 1);
    //        }

    //to show history chats between two users(sender & recipient)
    dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateFormat2 = new SimpleDateFormat("dd MMM HH:mm");
    listHistory = dbHelper.getStikyChat();
    if (listHistory.size() > 0) {
        Collections.reverse(listHistory);
        for (final StikyChatTb chatTb : listHistory) {
            String getDate = chatTb.getSendDate();
            String durationStr = null;
            String fromStikyBee = chatTb.getSender();
            try {
                final String createDate = dateFormat2.format(dateFormat.parse(getDate));
                if (chatTb.getFileName().contains("voice")) {
                    MediaPlayer mPlayer = new MediaPlayer();
                    String voiceFileName = getResources().getString(R.string.url) + "/" + chatTb.getFileName();
                    try {
                        mPlayer.setDataSource(voiceFileName);
                        mPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    //mPlayer.start();
                    int duration = mPlayer.getDuration();
                    mPlayer.release();
                    duration = (int) Math.ceil(duration / 1024);

                    if (duration < 10) {
                        durationStr = "00:0" + duration;
                    } else {
                        durationStr = "00:" + duration;
                    }
                    // Log.i(TAG, "Duration Srt " + durationStr);
                }
                if (fromStikyBee.equals(pref.getString("stkid", ""))) {
                    //String url1 = getResources().getString(R.string.url) + "/" + chatTb.getFileName();
                    // Log.i(TAG, " Offer Id " + chatTb.getOfferId() + " Price " + chatTb.getPrice() + " Name " + chatTb.getName());
                    //first false = right, second false = Offer
                    //  Log.i(TAG, " Duration " + chatTb.getRate() + " File Name " + chatTb.getFileName());
                    if (!chatTb.getFileName().contains("voice")) {
                        Log.i(TAG, " Voice is not ");
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), false, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), chatTb.getName(), null,
                                chatTb.getOriFName()));
                    } else {
                        Log.i(TAG, " Voice is ");
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), false, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), durationStr, null, chatTb.getOriFName()));
                    }
                } else {
                    /* Bitmap bmImg = BitmapFactory.decodeFile(getResources().getString(R.string.url) + "/" + chatTb.getFileName());
                     Bitmap resBm = getResizedBitmap(bmImg, 500);*/
                    // String url1 = getResources().getString(R.string.url) + "/" + chatTb.getFileName();
                    if (!chatTb.getFileName().contains("voice")) {
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), true, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), chatTb.getName(), null,
                                chatTb.getOriFName()));
                    } else {
                        adapter.add(new StikyChat(chatRecipientUrl, chatTb.getMessage(), true, createDate,
                                chatTb.getFileName(), chatTb.getOfferId(), chatTb.getOfferStatus(),
                                chatTb.getPrice(), chatTb.getRate(), durationStr, null, chatTb.getOriFName()));
                    }
                }
                lv.smoothScrollToPosition(adapter.getCount() - 1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    mRegistrationBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            fileNameGCM = sharedPreferences.getString("fileName", "");
            messageGCM = sharedPreferences.getString("message", "");
            offerIdGCM = sharedPreferences.getInt("offerId", 0);
            offerStatusGCM = sharedPreferences.getInt("offerStatus", 0);
            priceGCM = sharedPreferences.getString("price", "");
            rateGCM = sharedPreferences.getString("rate", "");
            nameGCM = sharedPreferences.getString("name", "");
            recipientProfileGCM = sharedPreferences.getString("chatRecipientUrl", "");
            recipientNameGCM = sharedPreferences.getString("chatRecipientName", "");
            recipientStkidGCM = sharedPreferences.getString("recipientStkid", "");
            recipientTokenGCM = sharedPreferences.getString("recipientToken", "");
            senderTokenGCM = sharedPreferences.getString("senderToken", "");

            Log.i(TAG, " FileName GCM " + fileNameGCM + " " + " Name Rate Price &&&&& *** " + messageGCM + " "
                    + priceGCM + " " + rateGCM);
            if (firstConnect) {
                if (recipientStkidGCM.trim() == recipientStkid.trim()
                        || recipientStkidGCM.equals(recipientStkid)) {
                    MyGcmListenerService.flagSendNoti = false;
                    Log.i(TAG, " " + message);
                    // (1) get today's date
                    start = new Date();
                    SimpleDateFormat oFormat = new SimpleDateFormat("dd MMM HH:mm");
                    timeSend = oFormat.format(start);

                    Log.i(TAG, "First connect " + firstConnect);
                    Log.i(TAG, " File Name GCMMMMMM " + fileNameGCM);
                    /*if (!fileNameGCM.equals("") && !fileNameGCM.equals("null") && !fileNameGCM.equals(null)) {
                    oriFName = saveFileAndImage(fileNameGCM);
                    }*/
                    /*if (fileNameGCM.contains("voice")) {
                    String durationStr;
                    MediaPlayer mPlayer = new MediaPlayer();
                    String voiceFileName = getResources().getString(R.string.url) + "/" + fileNameGCM;
                    try {
                        mPlayer.setDataSource(voiceFileName);
                        mPlayer.prepare();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                            
                    //mPlayer.start();
                    int duration = mPlayer.getDuration();
                    mPlayer.release();
                    duration = (int) Math.ceil(duration / 1024);
                            
                    if (duration < 10) {
                        durationStr = "00:0" + duration;
                    } else {
                        durationStr = "00:" + duration;
                    }
                    StikyChat stikyChat = new StikyChat(recipientProfileGCM, messageGCM, true, timeSend, fileNameGCM.trim(), offerIdGCM, offerStatusGCM, priceGCM, rateGCM, durationStr, null, oriFName);
                    adapter.add(stikyChat);
                    } else {*/
                    StikyChat stikyChat = new StikyChat(recipientProfileGCM, messageGCM, true, timeSend,
                            fileNameGCM.trim(), offerIdGCM, offerStatusGCM, priceGCM, rateGCM, nameGCM, null,
                            oriFName);
                    adapter.add(stikyChat);
                    //  }
                    Log.i(TAG, " First " + message + " " + recipientProfileGCM + " " + timeSend);
                    Log.i(TAG, "User " + txtUserName.getText().toString());

                    adapter.notifyDataSetChanged();
                    lv.setSelection(adapter.getCount() - 1);
                    new regTask2().execute("Obj ");
                } else {
                    /* if (!fileNameGCM.equals("") && !fileNameGCM.equals("null") && !fileNameGCM.equals(null)) {
                    saveFileAndImage(fileNameGCM);
                     }*/
                    Log.i(TAG, "..." + recipientStkidGCM.trim());
                    Log.i(TAG, "&&&" + recipientStkid.trim());
                    Log.i(TAG, "else casee");
                    //notificaton send
                    flagNotifi = true;
                    new regTask2().execute("Notification");
                }
                firstConnect = false;
            }
            lv.setSelection(adapter.getCount() - 1);
        }
    };

    /*edTxtMsg.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        layoutTalk.setLayoutParams(params);
        layoutTalk.setGravity(Gravity.CENTER);
      Toast.makeText(getBaseContext(),
                ((EditText) v).getId() + " has focus - " + hasFocus,
                Toast.LENGTH_LONG).show();
    }
    });*/
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    edTxtMsg.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, 0);
            params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            layoutTalk.setLayoutParams(params);
            layoutTalk.setGravity(Gravity.CENTER);
            flagRecord = false;
            /*getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE
            );*/
            Toast.makeText(getBaseContext(), "Touch ...", Toast.LENGTH_LONG).show();
            return false;
        }
    });
}