如何使用MediaSession在后台控制音乐播放

时间:2019-03-26 10:43:34

标签: java android

您好,我正在创建mp3播放器,我想从中控制音乐  使用通知服务的后台通知工作正常,但我  不知道如何使用通知服务控制媒体播放器  请帮助我,我是新手,不知道如何从后台进行控制请帮助如何解决此问题,我想摆脱这个问题?

MainActivity.java

package music.playerforandroid;

import android.Manifest;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.sip.SipSession;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v4.media.session.MediaSessionCompat;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import android.net.Uri;
import android.content.ContentResolver;
import android.database.Cursor;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RemoteViews;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.cleveroad.audiovisualization.AudioVisualization;
import com.cleveroad.audiovisualization.DbmHandler;
import com.cleveroad.audiovisualization.GLAudioVisualizationView;
import com.cleveroad.audiovisualization.VisualizerDbmHandler;
import com.gc.materialdesign.utils.Utils;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import static music.playerforandroid.App.CHANNEL_2_ID;

public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {
    private ArrayList<Song> songList;
    private ListView songView;
    MediaPlayer mediaPlayer;

    private int currentSongIndex = 0;
    Song song;
    private SlidingUpPanelLayout slidingLayout;
    Context mContext;
    private Utilities utils;
    private int seekForwardTime = 5000; // 5000 milliseconds
    private int seekBackwardTime = 5000;
    private AudioVisualization audioVisualization;
    private VisualizerDbmHandler handler;
    int postion;
    int totalduration;
    int totalTime;
    SeekBar seekBar;
    private Handler mHandler = new Handler();
private NotificationManagerCompat notificationManager;
    Uri uri;
    ImageView rotate;
    private long currentsongLength;
    TextView elapsedTimeLabel, remainingTimeLabel;
    TextView title, artist;
    ImageView playchange;
    ImageButton like, notlike, dislike, notdislike, next, pervious, repeat, reaptenable;
    ImageButton play, pause, play_main, pause_main, shuffle, shufflenable;
    private SlidingUpPanelLayout mLayout;
    private boolean isShuffle;
    private boolean checked;

    private static final String CHANNEL_ID = "channel_id01";
    public static final int NOTIFICATION_ID = 1;


    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        runtimpermession();
        songView = findViewById(R.id.song_list);
        songList = new ArrayList<Song>();

        artist = findViewById(R.id.artist);
        title = findViewById(R.id.songname);







        elapsedTimeLabel = findViewById(R.id.songtime);
        remainingTimeLabel = findViewById(R.id.endTime);
        seekBar = findViewById(R.id.seekBar3);
        next = findViewById(R.id.next);
        pervious = findViewById(R.id.pervious);
        like = findViewById(R.id.imageButton2);
        notlike = findViewById(R.id.imageButton2new);
        dislike = findViewById(R.id.button);
        notdislike = findViewById(R.id.buttontwo);
        play = findViewById(R.id.play_button);
        repeat = findViewById(R.id.repeat);
        reaptenable = findViewById(R.id.repeatenable);
        pause = findViewById(R.id.pause_button);
        play_main = findViewById(R.id.play_button_main);
        pause_main = findViewById(R.id.pause_button_main);
        like = findViewById(R.id.imageButton2);
        notlike = findViewById(R.id.imageButton2new);
        dislike = findViewById(R.id.button);
        notdislike = findViewById(R.id.buttontwo);
        play = findViewById(R.id.play_button);

        pause = findViewById(R.id.pause_button);
        shuffle = findViewById(R.id.shuffle);
        shufflenable = findViewById(R.id.shufflenable);
        elapsedTimeLabel = findViewById(R.id.endTime);
        remainingTimeLabel = findViewById(R.id.songtime);
        play_main = findViewById(R.id.play_button_main);
        pause_main = findViewById(R.id.pause_button_main);
        mLayout = findViewById(R.id.activity_main);
        rotate = findViewById(R.id.rotate);

        audioVisualization = findViewById(R.id.visualizer_view);
        seekBar.setOnSeekBarChangeListener(this);
        utils = new Utilities();

        notificationManager = NotificationManagerCompat.from(this);
        getSongList();
        Collections.sort(songList, new Comparator<Song>() {
            public int compare(Song a, Song b) {
                return a.getTitle().compareTo(b.getTitle());
            }
        });

        SongAdapter songAdt = new SongAdapter(this, songList);
        songView.setAdapter(songAdt);


        songView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, final long id) {

                play(position);


            }
        });



        repeat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                repeat.setVisibility(View.GONE);
                reaptenable.setVisibility(View.VISIBLE);
                shuffle.setVisibility(View.VISIBLE);
                shufflenable.setVisibility(View.GONE);
                isShuffle = false;
                checked = true;
                Toast.makeText(getApplicationContext(), "Repeat ON", Toast.LENGTH_SHORT).show();
            }

        });

        reaptenable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                repeat.setVisibility(View.VISIBLE);
                reaptenable.setVisibility(View.GONE);
                checked = false;
                Toast.makeText(getApplicationContext(), "Repeat OFF", Toast.LENGTH_SHORT).show();

            }


        });

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

                reaptenable.setVisibility(View.GONE);
                repeat.setVisibility(View.VISIBLE);
                checked = false;
                isShuffle = true;

                shuffle.setVisibility(View.GONE);
                shufflenable.setVisibility(View.VISIBLE);
                isShuffle = true;
                Toast.makeText(getApplicationContext(), "Shuffle ON", Toast.LENGTH_SHORT).show();
            }

        });
        shufflenable.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shuffle.setVisibility(View.VISIBLE);
                shufflenable.setVisibility(View.GONE);
                isShuffle = false;
                Toast.makeText(getApplicationContext(), "Shuffle OFF", Toast.LENGTH_SHORT).show();
            }
        });
        like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                notlike.setVisibility(View.VISIBLE);
                Toast.makeText(MainActivity.this, "You Like the Song", Toast.LENGTH_SHORT).show();
                if (notdislike.getVisibility() == View.VISIBLE) {
                    notdislike.setVisibility(View.GONE);
                }
            }
        });


        notlike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                notlike.setVisibility(View.GONE);
            }
        });


        dislike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                notdislike.setVisibility(View.VISIBLE);
                Toast.makeText(MainActivity.this, "You DisLike the Song", Toast.LENGTH_SHORT).show();
                if (notlike.getVisibility() == View.VISIBLE) {
                    notlike.setVisibility(View.GONE);
                }
            }
        });


        notdislike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                notdislike.setVisibility(View.GONE);
            }
        });


        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (mediaPlayer == null) {
                    play(0);
                } else {
                    mediaPlayer.start();
                }

                play.setVisibility(View.GONE);
                pause.setVisibility(View.VISIBLE);
                Toast.makeText(MainActivity.this, "Song Is now Playing", Toast.LENGTH_SHORT).show();
                if (play_main.getVisibility() == View.VISIBLE) {
                    play_main.setVisibility(View.GONE);
                    pause_main.setVisibility(View.VISIBLE);
                    Animation aniRotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
                    rotate.startAnimation(aniRotate);
                }

            }
        });

        pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (mediaPlayer != null && mediaPlayer.isPlaying()) {

                    mediaPlayer.pause();

                    rotate.clearAnimation();
                }
                pause.setVisibility(View.GONE);
                play.setVisibility(View.VISIBLE);
                Toast.makeText(MainActivity.this, "Song is Pause", Toast.LENGTH_SHORT).show();
                if (pause_main.getVisibility() == View.VISIBLE) {
                    pause_main.setVisibility(View.GONE);
                    play_main.setVisibility(View.VISIBLE);
                }
            }
        });


        play_main.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mediaPlayer == null) {
                    play(0);
                } else {
                    mediaPlayer.start();
                }

                play_main.setVisibility(View.GONE);
                pause_main.setVisibility(View.VISIBLE);
                Toast.makeText(MainActivity.this, "Song Is now Playing", Toast.LENGTH_SHORT).show();
                if (play.getVisibility() == View.VISIBLE) {
                    play.setVisibility(View.GONE);
                    pause.setVisibility(View.VISIBLE);
                    Animation aniRotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
                    rotate.startAnimation(aniRotate);
                }
            }
        });


        pervious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentSongIndex > 0) {
                    play(currentSongIndex - 1);
                    currentSongIndex = currentSongIndex - 1;
                } else {
                    // play last song
                    play(songList.size() - 1);
                    currentSongIndex = songList.size() - 1;
                }
                next.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        if (currentSongIndex < (songList.size() - 1)) {
                            play(currentSongIndex + 1);
                            currentSongIndex = currentSongIndex + 1;
                        } else {
                            // play first song
                            play(0);
                            currentSongIndex = 0;
                        }
                    }
                });


            }
        });

        pause_main.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                if (mediaPlayer != null && mediaPlayer.isPlaying()) {

                    mediaPlayer.pause();
                }
                pause_main.setVisibility(View.GONE);
                play_main.setVisibility(View.VISIBLE);
                Toast.makeText(MainActivity.this, "Song is Pause", Toast.LENGTH_SHORT).show();
                if (pause.getVisibility() == View.VISIBLE) {
                    pause.setVisibility(View.GONE);
                    play.setVisibility(View.VISIBLE);
                    rotate.clearAnimation();
                }
            }
        });
    }


    @Override
    public void onBackPressed() {
        if (mLayout != null &&
                (mLayout.getPanelState() == SlidingUpPanelLayout.PanelState.EXPANDED || mLayout.getPanelState() == SlidingUpPanelLayout.PanelState.ANCHORED)) {
            mLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);


        } else {
            super.onBackPressed();
        }
    }

    public void runtimpermession() {
        Dexter.withActivity(this)
                .withPermissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.MODIFY_AUDIO_SETTINGS,Manifest.permission.MEDIA_CONTENT_CONTROL
                ).withListener(new MultiplePermissionsListener() {
            @Override
            public void onPermissionsChecked(MultiplePermissionsReport report) {
                if (report.areAllPermissionsGranted()) {
                    Toast.makeText(MainActivity.this, "All Permission is Access Now", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {


            }
        }).check();


    }

    public void getSongList() {
        //retrieve song info
        ContentResolver musicResolver = getContentResolver();
        Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
        if (musicCursor != null && musicCursor.moveToFirst()) {
            //get columns
            int titleColumn = musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
            int idColumn = musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
            int artistColumn = musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
            int dataColumn = musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media.DATA);


            //add songs to list
            do {
                long thisId = musicCursor.getLong(idColumn);
                String thisTitle = musicCursor.getString(titleColumn);
                String thisArtist = musicCursor.getString(artistColumn);
                String thisPath = musicCursor.getString(dataColumn);

                songList.add(new Song(thisId, thisTitle, thisArtist, thisPath));
            }
            while (musicCursor.moveToNext());
        }


    }


    public void play(int songindex) {
        song = songList.get(songindex);

        try {

            if (mediaPlayer != null) {
                mediaPlayer.release();
                mediaPlayer = null;
            }
            Uri uri = Uri.parse("file:///" + song.getGetpath());
            mediaPlayer = MediaPlayer.create(mContext, uri);
             title.setText(song.getTitle());
             artist.setText(song.getArtist());






            handler = VisualizerDbmHandler.Factory.newVisualizerHandler(getApplicationContext(), mediaPlayer);
            audioVisualization.linkTo(handler);
            mediaPlayer.start();
            seekBar.setProgress(0);
            seekBar.setMax(100);
            updateProgressBar();

            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                play.setVisibility(View.GONE);
                pause.setVisibility(View.VISIBLE);
                play_main.setVisibility(View.GONE);
                pause_main.setVisibility(View.VISIBLE);
                Animation aniRotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
                rotate.startAnimation(aniRotate);

                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {


                        if (checked) {
                            mediaPlayer.setLooping(true);
                            mediaPlayer.start();
                        } else if (isShuffle) {
                            // shuffle is on - play a random song
                            Random rand = new Random();
                            currentSongIndex = rand.nextInt((songList.size() - 1) - 0 + 1) + 0;
                            play(currentSongIndex);
                        } else {
                            // no repeat or shuffle ON - play next song
                            if (currentSongIndex < (songList.size() - 1)) {
                                play(currentSongIndex + 1);
                                currentSongIndex = currentSongIndex + 1;
                            } else {
                                // play first song
                                play(0);
                                currentSongIndex = 0;
                            }
                        }
                    }
                });
            }


        } catch (Exception e) {

            Toast.makeText(getApplicationContext(), "" + e, Toast.LENGTH_SHORT).show();


        }

    }


    public void forward() {

        int currentPosition = mediaPlayer.getCurrentPosition();
        // check if seekForward time is lesser than song duration
        if (currentPosition + seekForwardTime <= mediaPlayer.getDuration()) {
            // forward song
            mediaPlayer.seekTo(currentPosition + seekForwardTime);
        } else {
            // forward to end position
            mediaPlayer.seekTo(mediaPlayer.getDuration());
        }
    }

    public void backword() {

        int currentPosition = mediaPlayer.getCurrentPosition();
        // check if seekBackward time is greater than 0 sec
        if (currentPosition - seekBackwardTime >= 0) {
            // forward song
            mediaPlayer.seekTo(currentPosition - seekBackwardTime);
        } else {
            // backward to starting position
            mediaPlayer.seekTo(0);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        shownotification();






    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
      try {
          mediaPlayer.release();
      }
      catch (Exception e){
          Toast.makeText(getApplicationContext(), ""+e, Toast.LENGTH_SHORT).show();
      }
    }

    public void updateProgressBar() {
        mHandler.postDelayed(mUpdateTimeTask, 100);
    }

    private Runnable mUpdateTimeTask = new Runnable() {
        public void run() {
            long totalDuration = mediaPlayer.getDuration();
            long currentDuration = mediaPlayer.getCurrentPosition();

            // Displaying Total Duration time
            remainingTimeLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
            // Displaying time completed playing
            elapsedTimeLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

            // Updating progress bar
            int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
            //Log.d("Progress", ""+progress);
            seekBar.setProgress(progress);

            // Running this thread after 100 milliseconds
            mHandler.postDelayed(this, 100);
        }
    };


        @Override
        public void onProgressChanged (SeekBar seekBar,int progress, boolean fromUser){

        }

        @Override
        public void onStartTrackingTouch (SeekBar seekBar){
            mHandler.removeCallbacks(mUpdateTimeTask);
        }

        @Override
        public void onStopTrackingTouch (SeekBar seekBar){
            mHandler.removeCallbacks(mUpdateTimeTask);
            int totalDuration = mediaPlayer.getDuration();
            int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

            // forward or backward to certain seconds
            mediaPlayer.seekTo(currentPosition);

            // update timer progress again
            updateProgressBar();
        }




        /**
         * Background Runnable thread
         * */

public  void  shownotification(){

    Intent intent = new Intent( getApplicationContext(), MediaPlayerService.class );
    intent.setAction( MediaPlayerService.ACTION_PLAY );
    startService( intent );
}
}

0 个答案:

没有答案