1

Meu problema é o seguinte: Tenho uma aplicação Android que roda um Player, contendo um botão "play", após o click aparece "stop" e executa o som.

Trabalha em um Navigation Drawer, até aí tudo bem e executa direito, quando abro outra tela através do menu lateral e volto a abrir o player, o botão aparece novamente "play", e se eu clicar novamente no "play" começa a tocar mais um som simultâneo, que na verdade era pra o botão "stop" está visível e assim poder parar de tocar. Alguém já passou por esta situação e tem a solução?`

MainActivity.java

package com.teste.com.myapplication;

import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.design.widget.NavigationView;
import android.support.v4.app.NavUtils;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, FragmentoRadio.OnFragmentInteractionListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);


    }

    @Override
    public void onBackPressed() {
        //Configuração do botão Voltar
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        boolean FragmentTransaction = false;
        Fragment fragment = null;


        if (id == R.id.nav_radio) {
            // Handle the camera action
            Intent upIntent = NavUtils.getParentActivityIntent(this);
            fragment = new FragmentoRadio();
            FragmentTransaction = true;
        } else if (id == R.id.nav_gallery) {


        } else if (id == R.id.nav_slideshow) {


        } else if (id == R.id.nav_manage) {


        } else if (id == R.id.nav_share) {


        } else if (id == R.id.nav_send) {


        }

        if(FragmentTransaction) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.content_main, fragment)
                    .commit();

            item.setChecked(true);
            getSupportActionBar().setTitle(item.getTitle());
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

}

FragmentoRadio

package com.teste.com.myapplication;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ToggleButton;

import java.io.IOException;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link FragmentoRadio.OnFragmentInteractionListener} interface
 * to handle interaction events.
 */
public class FragmentoRadio extends Fragment {

    private ToggleButton playPauseButton;
    private String STREAM_URL = "http://173.236.30.162:8119";
    private OnFragmentInteractionListener mListener;
    private MediaPlayer mp;
    private View view;

    public FragmentoRadio() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mp = new MediaPlayer();
        view = inflater.inflate(R.layout.fragmento_radio, container, false);

        playPauseButton = (ToggleButton) view.findViewById(R.id.playPauseButton);

        playPauseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Perform action on clicks
                if (playPauseButton.isChecked()) { // Checked - Pause icon visible
                    playPauseButton.setBackgroundResource(R.drawable.layout_button_stop);
                    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    try {
                        mp.reset();
                        mp.setDataSource(STREAM_URL);
                        mp.prepareAsync();
                        mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                            @Override
                            public void onPrepared(MediaPlayer mp) {
                                mp.start();

                            }
                        });
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                } if (mp.isPlaying() == true){ // Unchecked - Play icon visible
                    playPauseButton.setBackgroundResource(R.drawable.layout_button_play);
                    if (playPauseButton.isChecked()){

                    }else{
                        mp.stop();
                    }
                }
            }
        });
        return view;
    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

Layout
fragmento_radio

<!-- TODO: Update blank fragment layout -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    android:id="@+id/content_main"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.teste.myapplication.MainActivity"
    tools:showIn="@layout/app_bar_main">
    <ToggleButton
        android:layout_width="210dp"
        android:layout_height="210dp"
        android:background="@drawable/layout_button_play"
        android:layout_weight="0.42"
        android:layout_alignWithParentIfMissing="false"
        android:id="@+id/playPauseButton"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="47dp"
        android:textOff=" "
        android:textOn=" "/>
</RelativeLayout>

1 Resposta 1

0

Bom dia, isto está ocorrendo porque você está criando mais de uma instância do MediaPlayer. Neste caso o ideal é você criar um Service para manter apenas uma instâcia do MediaPlayer que vai ficar executando em Background na sua aplicação e então 'fazer Bind' com a View que está sendo mostrada ao usuário.

Na documentação do Android mostra como fazer isto: http://developer.android.com/intl/pt-br/guide/topics/media/mediaplayer.html, Aqui tem um exemplo simples: http://www.java2s.com/Code/Android/Media/UsingServicetoplaymediafile.htm

2
  • Caro amigo, agradeço muito a atenção dispensada, irei realizar estes procedimentos e retornarei com o resultado. Commented 17/03/2016 às 15:34
  • 1
    Implementei o Media Player via Serviço e ocorreu tudo bem. Commented 20/03/2016 às 23:06

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .