无法将片段绑定到服务

时间:2017-10-31 13:12:26

标签: android android-fragments service android-mediaplayer

我一直在网上搜索,但找不到解决方案。我有一个音乐播放器服务类,在后台播放歌曲即服务。问题是我无法将片段绑定到此服务。在logcat中没有显示错误,也没有应用程序崩溃。当我点击其中一首歌时没有任何反应。这是我的代码:

服务类:

public class MediaPlayerService extends Service implements MediaPlayer.OnCompletionListener,
    MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnSeekCompleteListener,
    MediaPlayer.OnInfoListener, MediaPlayer.OnBufferingUpdateListener,

    AudioManager.OnAudioFocusChangeListener {


private final IBinder iBinder = new LocalBinder();
private static MediaPlayer  mediaPlayer = new MediaPlayer();
private String mediaFile;
private int resumePosition;
private AudioManager audioManager;
//Handle incoming phone calls
private boolean ongoingCall = false;
private PhoneStateListener phoneStateListener;
private TelephonyManager telephonyManager;
private ArrayList<SongInfoModel> songsServiceList = new ArrayList<>();
private int songPosn;
private int currentIndex ;


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



private void initMediaPlayer() {

    //Set up MediaPlayer event listeners

    mediaPlayer.setOnCompletionListener(this);
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setOnPreparedListener(this);
    mediaPlayer.setOnBufferingUpdateListener(this);
    mediaPlayer.setOnSeekCompleteListener(this);
    mediaPlayer.setOnInfoListener(this);
    //Reset so that the MediaPlayer is not pointing to another data source
    mediaPlayer.reset();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

}

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

    songPosn=0;

    initMediaPlayer();


}

public void setList(ArrayList<SongInfoModel> theSongs){
    songsServiceList=theSongs;
}
public void setSong(int songIndex){
    songPosn=songIndex;
}

public void playSong(){
    //play a song

    mediaPlayer.reset();

    //get song
     SongInfoModel playSong = songsServiceList.get(songPosn);
    //get id
    long currSong = playSong.getSongID();
    //set uri
    Uri trackUri = ContentUris.withAppendedId(
            android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            currSong);

    try{
        mediaPlayer.setDataSource(getApplicationContext(), trackUri);
    }
    catch(Exception e){
        Log.e("MUSIC SERVICE", "Error setting data source", e);
    }

    mediaPlayer.prepareAsync();

    MainActivity.handleSeekbar(mediaPlayer);

}



@Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {

}

@Override
public void onCompletion(MediaPlayer mediaPlayer) {

        mediaPlayer.reset();

    songPosn++;
    if(songPosn>=songsServiceList.size()) songPosn=0;

       playSong();


}

@Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
    return false;
}

@Override
public boolean onInfo(MediaPlayer mediaPlayer, int i, int i1) {
    return false;
}

@Override
public void onPrepared(MediaPlayer mediaPlayer) {

    if (mediaPlayer.isPlaying()) {
        mediaPlayer.stop();
        mediaPlayer.reset();

    } else {

        mediaPlayer.start();
        MainActivity.Handler(mediaPlayer);

    }


}
 public class LocalBinder extends Binder {
    public MediaPlayerService getService() {
        return MediaPlayerService.this;
    }
}

FragmentClass:

public class Songs extends Fragment  {


public static final String TAG = "Songs";
RecyclerView recyclerView;
private ArrayList<SongInfoModel> SongList = new ArrayList<SongInfoModel>();
SongAdapter songAdapter;
ScaleInAnimationAdapter alphaAdapter;
private  MediaPlayerService player2;
boolean serviceBound2 = false;
private Intent playIntent2;



@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.songs_activity, container, false);




    recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
    recyclerView.setLayoutManager(linearLayoutManager);




    songAdapter = new SongAdapter(getContext(), SongList, new SongAdapter.RecyclerItemClickListener() {
        @Override
        public void onClickListener(SongInfoModel song, int position) {




            Toast.makeText(getContext(), song.getSongName(), Toast.LENGTH_SHORT).show();


            MainActivity.setsongText(song);
            MainActivity.ButtonPlay();
            MainActivity.PauseImage();

            if(serviceBound2 == true) {
                player2.setSong(position);
                player2.playSong();
            }


        }

        @Override
        public void onLongClickListener(SongInfoModel song, int position) {
            Toast.makeText(getContext(), "You long clicked me, thank you!", Toast.LENGTH_SHORT).show();
        }


    });

    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Audio.Media.IS_MUSIC + "!=0";
    Cursor cursor = getActivity().getContentResolver().query(uri, null, selection, null, null);
    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {
                long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
                String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                Long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
                String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                Long albumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
                Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
                Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri,  albumId);



                SongInfoModel s = new SongInfoModel(id, name, artist, null, null, null, duration, data,albumArtUri, albumId);
                SongList.add(s);

            } while (cursor.moveToNext());
        }


        cursor.close();

        Collections.sort(SongList, new Comparator<SongInfoModel>() {
            @Override
            public int compare(SongInfoModel lhs, SongInfoModel rhs) {
                return lhs.getSongName().compareTo(rhs.getSongName());
            }
        });



    }

    alphaAdapter = new ScaleInAnimationAdapter(songAdapter);
    alphaAdapter.setDuration(1000);
    alphaAdapter.setInterpolator(new OvershootInterpolator());
    alphaAdapter.setFirstOnly(false);
    recyclerView.setAdapter(alphaAdapter);
    songAdapter.notifyDataSetChanged();



    return view;
}



//Binding this Client to the AudioPlayer Service
private ServiceConnection serviceConnection2 = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        // We've bound to LocalService, cast the IBinder and get LocalService instance
        MediaPlayerService.LocalBinder binder = (MediaPlayerService.LocalBinder) service;
        player2 = binder.getService();
        player2.setList(SongList);
        serviceBound2 = true;
        Toast.makeText(getContext(), "Service Bound", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        serviceBound2 = false;
    }


};



@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if(playIntent2==null && serviceBound2==true){
        playIntent2 = new Intent(getActivity(), MediaPlayerService.class);
        getActivity().bindService(playIntent2, serviceConnection2, Context.BIND_AUTO_CREATE);
        getActivity().startService(playIntent2);

    }
}

0 个答案:

没有答案