Android从MusicService通知返回主活动

Android从MusicService通知返回主活动,android,android-fragments,android-music-player,Android,Android Fragments,Android Music Player,我正在为android开发一个音乐播放器,我被这个问题困住了 现在我可以用musicservice播放一首歌曲并将其发送到后台,我还可以显示当前播放歌曲的通知 我需要的是从歌曲通知重新打开主活动并继续播放歌曲,它实际上启动了所需的活动,但音乐服务被重新创建,并停止当前播放的歌曲 这是我的密码 MusicService.java public class MusicService extends Service implements MediaPlayer.OnPreparedListen

我正在为android开发一个音乐播放器,我被这个问题困住了

现在我可以用musicservice播放一首歌曲并将其发送到后台,我还可以显示当前播放歌曲的通知

我需要的是从歌曲通知重新打开主活动并继续播放歌曲,它实际上启动了所需的活动,但音乐服务被重新创建,并停止当前播放的歌曲

这是我的密码

MusicService.java

public class MusicService extends Service implements
    MediaPlayer.OnPreparedListener,
    MediaPlayer.OnErrorListener,
    MediaPlayer.OnCompletionListener {

private final IBinder musicBind = new MusicBinder();

//media player
private MediaPlayer player;

//song list
private ArrayList<SongModel> songs;

//current position
private int songPosition;

public MusicService() {
}

public void onCreate() {
    //create the service
    super.onCreate();

    //initialize position
    songPosition = 0;

    //create player
    player = new MediaPlayer();

    initMusicPlayer();
}

public void initMusicPlayer() {
    //set player properties
    player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
    player.setAudioStreamType(AudioManager.STREAM_MUSIC);
    player.setOnPreparedListener(this);
    player.setOnCompletionListener(this);
    player.setOnErrorListener(this);

}

public void setList(ArrayList<SongModel> theSongs) {
    songs = theSongs;
}

public class MusicBinder extends Binder {
    public MusicService getService() {
        return MusicService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return musicBind;
}

@Override
public boolean onUnbind(Intent intent) {
    player.stop();
    player.release();
    return false;
}

public int getPosition() {
    return player.getCurrentPosition();
}

public int getCurrenListPosition() {
    return songPosition;
}

public int getDuration() {
    return player.getDuration();
}

public boolean isPlaying() {
    return player.isPlaying();
}

public void pausePlayer() {
    player.pause();
}

public void stopPlayer() {
    player.stop();
}

public void seekToPosition(int posn) {
    player.seekTo(posn);
}

public void start() {
    player.start();
}

public void playSong() {
    try {
        //play a song
        player.reset();

        SongModel playSong = songs.get(songPosition);
        String trackUrl = playSong.getFileUrl();

        player.setDataSource(trackUrl);
        player.prepareAsync();

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

@Override
public void onCompletion(MediaPlayer mp) {
    if (mp.getCurrentPosition() == 0) {
        mp.reset();
    }
}

@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
    mp.reset();
    return false;
}

@Override
public void onPrepared(MediaPlayer mp) {
    //start playback
    mp.start();

    SongModel playingSong = songs.get(songPosition);

    Intent intent = new Intent(this, NavDrawerMainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    Notification.Builder builder = new Notification.Builder(this);

    builder.setContentIntent(pendingIntent)
            .setSmallIcon(R.drawable.ic_action_playing)
            .setTicker(playingSong.getTitle())
            .setOngoing(true)
            .setContentTitle(playingSong.getTitle())
            .setContentText(playingSong.getArtistName());

    Notification notification = builder.build();
    startForeground((int) playingSong.getSongId(), notification);
}

@Override
public void onDestroy() {
    stopForeground(true);
}

public void setSong(int songIndex) {
    songPosition = songIndex;
}
公共类MusicService扩展服务实现
MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener{
私有最终IBinder musicBind=新的MusicBinder();
//媒体播放器
私人媒体播放器;
//歌曲列表
私人雅乐歌曲;
//当前位置
私人职位;
公共音乐服务{
}
public void onCreate(){
//创建服务
super.onCreate();
//初始化位置
位置=0;
//创建玩家
player=新媒体播放器();
initMusicLayer();
}
public void initMusicPlayer(){
//设置玩家属性
setWakeMode(getApplicationContext(),PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(此);
player.setOnCompletionListener(此);
player.setOneErrorListener(此);
}
公共无效集合列表(数组列表歌曲){
歌曲=歌曲;
}
公共类MusicBinder扩展活页夹{
公共音乐服务getService(){
返回MusicService.this;
}
}
@凌驾
公共IBinder onBind(意向){
返回音乐绑定;
}
@凌驾
公共布尔onUnbind(意图){
player.stop();
player.release();
返回false;
}
public int getPosition(){
返回player.getCurrentPosition();
}
public int getCurrEnglistPosition(){
返回位置;
}
public int getDuration(){
返回player.getDuration();
}
公共布尔值显示(){
返回player.isPlaying();
}
public void pausePlayer(){
player.pause();
}
公共图层(){
player.stop();
}
公共无效搜索位置(int posn){
player.seekTo(posn);
}
公开作废开始(){
player.start();
}
公开播放歌曲(){
试一试{
//放首歌
player.reset();
SongModel playSong=songs.get(songPosition);
String trackUrl=playSong.getFileUrl();
player.setDataSource(trackUrl);
player.prepareAsync();
}捕获(例外e){
e、 printStackTrace();
}
}
@凌驾
完成时的公共作废(MediaPlayer mp){
if(mp.getCurrentPosition()==0){
mp.reset();
}
}
@凌驾
公共布尔onError(MediaPlayer mp,int what,int extra){
mp.reset();
返回false;
}
@凌驾
已准备好公开作废(MediaPlayer mp){
//开始播放
mp.start();
SongModel playingSong=songs.get(songPosition);
Intent Intent=新的Intent(这是navactivity.class);
intent.addFlags(intent.FLAG\u ACTIVITY\u CLEAR\u TOP);
PendingEvent PendingEvent=PendingEvent.getActivity(this,0,intent,
PendingEvent.FLAG_UPDATE_CURRENT);
Notification.Builder=new Notification.Builder(此);
builder.setContentIntent(pendingIntent)
.setSmallIcon(右可绘制的ic动作播放)
.setTicker(playingSong.getTitle())
.正在进行(正确)
.setContentTitle(playingSong.getTitle())
.setContentText(playingSong.getArtistName());
通知通知=builder.build();
startForeground((int)playingSong.getSongId(),通知);
}
@凌驾
公共空间{
停止前景(真);
}
公共空间集松(国际歌曲索引){
songPosition=songIndex;
}
}

DiscoverSongsFragment.java

public class DiscoverSongsFragment extends Fragment
    implements MediaController.MediaPlayerControl {

JazzyGridView songsContainer;
SongsHelper songsHelper;
SongsAdapter songsAdapter;
ArrayList<SongModel> songsArrayList;
ConnectionState connectionState;

Context mContext;
private static View rootView;

SongModel currentSong;
SeekBar nowPlayingSeekBar;
final Handler handler = new Handler();

// this value contains the song duration in milliseconds.
// Look at getDuration() method in MediaPlayer class
int mediaFileLengthInMilliseconds;

View nowPlayingLayout;
boolean nowPlayingLayoutVisible;

TextView nowPlayingTitle;
TextView nowPlayingArtist;
ImageButton nowPlayingCover;
ImageButton nowPlayingStop;

private MusicService musicService;
private Intent playIntent;
private boolean musicBound = false;
private boolean playbackPaused = false;

private int mCurrentTransitionEffect = JazzyHelper.SLIDE_IN;

public static DiscoverSongsFragment newInstance() {
    return new DiscoverSongsFragment();
}

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.fragment_discover_songs, container, false);
    mContext = rootView.getContext();
    setupViews(rootView);

    return rootView;
}

@Override
public void onStart() {
    super.onStart();

    if (playIntent == null) {
        playIntent = new Intent(mContext, MusicService.class);
        mContext.bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
        mContext.startService(playIntent);
    }
}

@Override
public void onResume() {
    super.onResume();

    if (isPlaying()) {
        showNowPlayingLayout();
        primarySeekBarProgressUpdater();
    }
}

@Override
public void onDestroy() {
    mContext.stopService(playIntent);
    musicService = null;
    super.onDestroy();
}

private void hideNowPlayingLayout() {
    nowPlayingLayoutVisible = false;
    nowPlayingLayout.setVisibility(View.GONE);

    Animation animationFadeIn = AnimationUtils.loadAnimation(mContext, R.anim.fade_out);
    nowPlayingLayout.startAnimation(animationFadeIn);
}

private void showNowPlayingLayout() {
    nowPlayingLayoutVisible = true;
    nowPlayingLayout.setVisibility(View.VISIBLE);

    Animation animationFadeIn = AnimationUtils.loadAnimation(mContext, R.anim.fade_in);
    nowPlayingLayout.startAnimation(animationFadeIn);
}

private void setupViews(View rootView) {
    songsHelper = new SongsHelper();
    songsArrayList = new ArrayList<SongModel>();
    connectionState = new ConnectionState(mContext);
    songsAdapter = new SongsAdapter(mContext, songsArrayList);

    nowPlayingLayout = rootView.findViewById(R.id.nowPlayingLayout);
    nowPlayingLayout.setVisibility(View.GONE);
    nowPlayingLayoutVisible = false;

    songsContainer = (JazzyGridView) rootView.findViewById(R.id.songsContainerView);
    songsContainer.setTransitionEffect(mCurrentTransitionEffect);
    songsContainer.setAdapter(songsAdapter);
    songsContainer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            musicService.setSong(position);
            musicService.playSong();

            if (playbackPaused) {
                playbackPaused = false;
            }

            currentSong = songsArrayList.get(position);

            // gets the song length in milliseconds from URL
            mediaFileLengthInMilliseconds = getDuration();

            if (currentSong != null) {
                nowPlayingTitle.setText(currentSong.getTitle());
                nowPlayingArtist.setText(currentSong.getArtistName());
                nowPlayingCover.setImageBitmap(currentSong.getCoverArt());
            }

            primarySeekBarProgressUpdater();

            if (!nowPlayingLayoutVisible) {
                showNowPlayingLayout();
            }
        }
    });

    nowPlayingSeekBar = (SeekBar) rootView.findViewById(R.id.nowPlayingSeekbar);
    nowPlayingSeekBar.setMax(99);

    nowPlayingTitle = (TextView) rootView.findViewById(R.id.nowPlayingTitle);
    nowPlayingArtist = (TextView) rootView.findViewById(R.id.nowPlayingArtist);
    nowPlayingStop = (ImageButton) rootView.findViewById(R.id.nowPlayingStop);
    nowPlayingStop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isPlaying()) {

                currentSong = null;
                playbackPaused = false;
                musicService.stopPlayer();
                mediaFileLengthInMilliseconds = 0;
                nowPlayingSeekBar.setProgress(0);
                hideNowPlayingLayout();

            }
        }
    });

    nowPlayingCover = (ImageButton) rootView.findViewById(R.id.nowPlayingCover);
    nowPlayingCover.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                Intent intent = new Intent(mContext, SongDetailsActivity.class);
                intent.putExtra("Title", currentSong.getTitle());
                intent.putExtra("Artist", currentSong.getArtistName());
                intent.putExtra("Album", currentSong.getAlbumName());
                intent.putExtra("Genre", currentSong.getGenre());
                intent.putExtra("CoverUrl", currentSong.getCoverArtUrl());

                startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    getSongs();
    hideNowPlayingLayout();
}

private void getSongs() {

    if (!connectionState.isConnectedToInternet()) {

    }

    songsAdapter.clear();

    String songsUrl = Constants.getAPI_SONGS_URL();
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(songsUrl, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray jsonArray) {

            if (jsonArray != null) {

                for (int i = 0; i < jsonArray.length(); i++) {
                    try {

                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        SongModel song = songsHelper.getSongFromJson(jsonObject);
                        songsAdapter.add(song);

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

                }
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
        }
    });

    AppController.getInstance().addToRequestQueue(jsonArrayRequest);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
}

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

/**
 * Method which updates the SeekBar primary progress by current song playing position
 */
private void primarySeekBarProgressUpdater() {
    nowPlayingSeekBar.setProgress((int) (((float) getCurrentPosition() / getDuration()) * 100));

    //if (isPlaying()) {
    Runnable runnable = new Runnable() {
        public void run() {
            primarySeekBarProgressUpdater();
        }
    };
    handler.postDelayed(runnable, 1000);
    //}
}

@Override
public void start() {
    musicService.start();
}

@Override
public void pause() {
    playbackPaused = true;
    musicService.pausePlayer();
}

@Override
public int getDuration() {
    if (musicService != null && musicBound && musicService.isPlaying()) {
        return musicService.getDuration();
    }
    return 0;
}

@Override
public int getCurrentPosition() {
    if (musicService != null && musicBound && musicService.isPlaying()) {
        return musicService.getPosition();
    }
    return 0;
}

public int getCurrentListPosition() {
    if (musicService != null && musicBound && musicService.isPlaying()) {
        return musicService.getCurrenListPosition();
    }
    return 0;
}

@Override
public void seekTo(int pos) {
    musicService.seekToPosition(pos);
}

@Override
public boolean isPlaying() {
    if (musicService != null && musicBound && musicService.isPlaying()) {
        return musicService.isPlaying();
    }
    return false;
}

@Override
public int getBufferPercentage() {
    return 0;
}

@Override
public boolean canPause() {
    return true;
}

@Override
public boolean canSeekBackward() {
    return true;
}

@Override
public boolean canSeekForward() {
    return true;
}

@Override
public int getAudioSessionId() {
    return 0;
}

//connect to the service
private ServiceConnection musicConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        MusicService.MusicBinder binder = (MusicService.MusicBinder) service;
        //get service
        musicService = binder.getService();
        //pass list
        musicService.setList(songsArrayList);
        musicBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        musicBound = false;
    }
};
公共类DiscoverSongsFragment扩展片段
实现MediaController.MediaPlayerControl{
JazzyGridView歌曲容器;
松谢尔帕松谢尔帕;
宋萨达普特宋萨达普特;
ArrayList songsArrayList;
连接状态连接状态;
语境;
私有静态视图rootView;
歌曲模型;
SeekBar Now播放SeekBar;
最终处理程序=新处理程序();
//此值包含以毫秒为单位的歌曲持续时间。
//查看MediaPlayer类中的getDuration()方法
int MediaFileLengthinmMills;
查看当前播放布局;
布尔值nowPlayingLayoutVisible;
TextView nowPlayingTitle;
TextView Now PlayingArtist;
图像按钮现在播放封面;
图像按钮现在播放停止;
私人音乐服务;
私人意图;
私有布尔值musicBound=false;
私有布尔播放暂停=false;
private int mCurrentTransitionEffect=JazzyHelper.SLIDE_IN;
公共静态DiscoverSongsFragment newInstance(){
返回新的DiscoverSongsFragment();
}
公共DiscoverSongsFragment(){
//必需的空公共构造函数
}
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
rootView=充气机。充气(R.layout.fragment\u discover\u歌曲,容器,false);
mContext=rootView.getContext();
setupview(rootView);
返回rootView;
}
@凌驾
public void onStart(){
super.onStart();
如果(playIntent==null){
playIntent=新意图(mContext,MusicService.class);
绑定服务(playIntent、musicConnection、Context.BIND\u AUTO\u CREATE);
mContext.startService(playIntent);
}
}
@凌驾
恢复时公开作废(){
super.onResume();
if(isPlaying()){
showNowPlayingLayout();
primarySeekBarProgressUpdater();
}
}
@凌驾
公共空间{
mContext.stopService(playIntent);
musicService=null;
super.ondestory();
}
私有void hideNowPlayingLayout(){
nowPlayingLayoutVisible=false;
诺普莱伊
        // link the notifications to the recorder activity
        Intent resultIntent = new Intent(context, KmlReader.class);
        resultIntent
                .setAction(ServiceLocationRecorder.INTENT_COM_GOSYLVESTER_BESTRIDES_LOCATION_RECORDER);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent resultPendingIntent = PendingIntent
                .getActivity(context, 0, resultIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);

        return mBuilder.build();
    }
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intent = getIntent();

    String intentaction = intent.getAction();

    // First Run checks
    if (savedInstanceState == null) {
        // first run init
    } else {
        // get the saved_Instance state
        // always get the default when key doesn't exist
        // default is null for this example
        currentCameraPosition = savedInstanceState
                .containsKey(SAVED_INSTANCE_CAMERA_POSITION) ? (CameraPosition) savedInstanceState
                .getParcelable(SAVED_INSTANCE_CAMERA_POSITION) : null;