Jump to content
carcleo

Adicionar MediaPlayer à área de notificação

Recommended Posts

carcleo

Bom, estou fazendo um app que tem um plugin MediaPlayer para tocar rádio web.

Gostaria de adicionar, quando o `player` fosse clicado, uma previa dele na área de notificações também como abaixo:

https://i.stack.imgur.com/rLtxK.png

 

O app da Rádio Gospel Mix também faz isso.

A ideia é que quando o App fosse minimizado, o usuário tenha a experiência  de visualizar o plugin quando exibir a área de notificação.

Mas não apareceu o player na área de notificação.

Segue o código.

   

package carcleo.com.player;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.session.MediaSession;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;

public class player extends AppCompatActivity {

    private MediaPlayer mPlayer;
    private String URL;
    private Button btnPlayPause;
    private Boolean conexao = false;
    private ProgressDialog progressDialog;
    private SeekBar sb;
    private TextView textView;
    private NotificationManager mNotificationManager;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.player);

        textView = findViewById(R.id.textView);

        progressDialog = new ProgressDialog(this);

        btnPlayPause = (Button) findViewById(R.id.btnPlayPause);

        btnPlayPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (mPlayer == null) mPlayer = new MediaPlayer();
                    tocaPausa();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void notificacao (){

        RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.player);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.home)
                        .setContentTitle("Rádio Capital")
                        //.setCustomContentView(remoteViews)
                        .setContentText("Agora deu");

        Intent resultIntent = new Intent(this, player.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(player.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1, mBuilder.build());

    }

    private void tocaPausa() throws IOException {
        if (conexao == true) {
            if (!mPlayer.isPlaying()) {
                mPlayer.start();
                btnPlayPause.setBackgroundResource(R.drawable.pause);
            } else {
                mPlayer.pause();
                btnPlayPause.setBackgroundResource(R.drawable.play);
            }
        } else {
            String url = "rtsp://cdn-the-2.musicradio.com:80/LiveAudio/Capital"; // your URL here
            new Play().execute(url);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mNotificationManager.cancelAll(); // <---- não esqueça de destruir o receiver junto com a activity
    }

    class Play extends AsyncTask<String, Boolean, Boolean> {

        @Override
        protected void onPreExecute() {

            progressDialog.setMessage("Carregando...");
            progressDialog.show();

        }

        @Override
        protected Boolean doInBackground(String... params) {

            try {
                mPlayer = new MediaPlayer();
                mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mPlayer.setDataSource(params[0]);
                mPlayer.prepare(); // might take long! (for buffering, etc)
                return true;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }

        }

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        @Override
        protected void onPostExecute(Boolean result) {

            if (progressDialog.isShowing()) {
                progressDialog.cancel();
            }

            if(result == true){
                conexao = true;
                mPlayer.start();
                btnPlayPause.setBackgroundResource(R.drawable.pause);
            } else {
                conexao = false;
                btnPlayPause.setBackgroundResource(R.drawable.play);
            }

            notificacao();

        }

    }

}

Outro problema é que quando chega em

    tocaPausa 

Ele dá erro.

Mas a função ocorre normalmente quando tocamos o player através do app

Edited by carcleo

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.