Как сделать прогресс-бар для показа буферизации в онлайн аудио плеере

365
17 июня 2017, 12:18

Класс, в котором происходит выбор трека (url-канала) для проигрывания:

public class TrackListActivity extends BaseActivity  {

    public static final String TAG = TrackListActivity.class.getName();
    SubApplication application;
    String FONT_REVICONS = "FONT_REVICONS";
    String FONT_NARROW_BOLD = "FONT_NARROW_BOLD";
    String FONT_SANS_BOLD = "FONT_SANS_BOLD";
    String FONT_SANS = "FONT_SANS";
    LocalSharedStorage sharedPref;
    ConnectionDetector connDetector;
    ProgressBar progressbar_tracklist;
    CustomDialog customDialog;
    TextView textView_title, tv_track_title;
    RecyclerView listView_trackList;
    RelativeLayout rl_musiccontorl;
    AdView mAdView_tracklist;
    Button button_tracklist_chat;
    CardView card_view_musiccontorl;
    ImageView  iv_player_control;
    NetworkImageView iv_track_image,main_image;
    ArrayList<TrackDetails> mArrAllTrackDetails, mArrTrackList;
    Track mObjTrack;
    String mTitle = "Track List";
    String mIcon= "Track List";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tracklist);
        mAdView_tracklist = (AdView) findViewById(R.id.adView_track);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView_tracklist.loadAd(adRequest);
        button_tracklist_chat = (Button)findViewById(R.id.button_tracklist_chat);
        button_tracklist_chat.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                    Intent intObJ = new Intent (TrackListActivity.this,MainActivityChat.class);
                    startActivity(intObJ);
                }
        });
        Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
        setSupportActionBar(toolbar);
        ActionBar ab = getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(false);
        ab.setHomeButtonEnabled(true);
        progressbar_tracklist = (ProgressBar) findViewById(R.id.progressbar_tracklist);
        progressbar_tracklist.setVisibility(View.GONE);
        application = new SubApplication();
        initializeWidget();
        Intent intent = getIntent();
        mTitle = intent.getStringExtra(getString(R.string.key_title));
        mIcon = intent.getStringExtra(getString(R.string.key_artwork_url));
        mObjTrack = (Track) intent.getSerializableExtra(getString(R.string.key_download_url));
        if (mObjTrack != null) {
            mArrAllTrackDetails = mObjTrack.getTrackDetails();
        }
        ImageLoader mImageLoader;
        if(mIcon!=null)
        {
            mImageLoader = AppController.getInstance().getImageLoader();
            mImageLoader.get(mIcon, ImageLoader.getImageListener(main_image,
                    R.drawable.loaders, R.drawable.loaders));
            main_image.setImageUrl(mIcon, mImageLoader);
        }
        SpannableStringBuilder spannableString = application.getSpannableMessage(getApplicationContext(), FONT_REVICONS,
                mTitle);
        ab.setTitle(spannableString);
        setUpTrackList();
        // setController();
        iv_player_control.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (connDetector.checkInternetConnection()) {
                    resetplayer();
                }else {
                    showCustomToast(getResources().getString(R.string.network_error));
                    finish();
                }
            }
        });
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
        case android.R.id.home:
            actionBackPressed();
            break;
        /*
         * case R.id.action_end: stopService(playIntent); musicSrv = null;
         * System.exit(0); break;
         *
         * case R.id.action_shuffle: musicSrv.setShuffle(); break;
         */
        }
        return true;
    }
    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        if (connDetector.checkInternetConnection()) {
        }else {
            showCustomToast(getString(R.string.network_error));
            return;
        }
        super.onResume();
    }
    @Override
    public void onBackPressed() {
        actionBackPressed();
    }
    void actionBackPressed() {
        super.onBackPressed();
    }

    private void initializeWidget() {
        // TODO Auto-generated method stub
        //buffer
        connDetector = new ConnectionDetector(this);
        customDialog = new CustomDialog(TrackListActivity.this);
        sharedPref = new LocalSharedStorage(this);
        textView_title = (TextView) findViewById(R.id.textView_title);
        application.setTypeface(textView_title, FONT_REVICONS, getApplicationContext());
        tv_track_title = (TextView) findViewById(R.id.tv_track_title);
        application.setTypeface(tv_track_title, FONT_REVICONS, getApplicationContext());
        listView_trackList = (RecyclerView) findViewById(R.id.listView_trackList);
        rl_musiccontorl = (RelativeLayout) findViewById(R.id.rl_musiccontorl);
        card_view_musiccontorl =(CardView)findViewById(R.id.card_view_musiccontorl);
        iv_player_control = (ImageView) findViewById(R.id.iv_player_control);
        iv_track_image = (NetworkImageView) findViewById(R.id.tv_track_image);
        main_image = (NetworkImageView) findViewById(R.id.main_image);
        mObjTrack = new Track();
        mArrAllTrackDetails = new ArrayList<TrackDetails>();
        mArrTrackList = new ArrayList<TrackDetails>();
    }
    private void setUpTrackList() {
        // TODO Auto-generated method stub
        if (mArrAllTrackDetails != null) {
            if (mArrAllTrackDetails.size() > 0) {
                mArrTrackList = new ArrayList<TrackDetails>();
                for (int i = 0; i < mArrAllTrackDetails.size(); i++) {
                    if (mArrAllTrackDetails.get(i).getGenre().equalsIgnoreCase(mTitle)) {
                        mArrTrackList.add(mArrAllTrackDetails.get(i));
                    }
                }
                if (mArrTrackList != null) {
                    if (mArrTrackList.size() == 1 || mArrTrackList.size() == 0) {
                        textView_title.setText(mArrTrackList.size() + " " + getString(R.string.track));
                    } else {
                        textView_title.setText(getString(R.string.tracks)+"Всего станций: " + mArrTrackList.size());
                    }
                    displayMusicPlayerControl();
                    if (mArrTrackList.size() > 0) {
                        LinearLayoutManager  mLayoutManager = new LinearLayoutManager(getApplicationContext());
                        listView_trackList.setHasFixedSize(true);
                        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                        listView_trackList.setLayoutManager(mLayoutManager);
                        listView_trackList.setItemAnimator(new DefaultItemAnimator());
                        listView_trackList.setAdapter(new TrackListAdapter(mArrTrackList));
                    }
                }
            }
        }
        card_view_musiccontorl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TrackListActivity.this,AudioPlayerActivity.class);
                intent.putExtra(getString(R.string.key_title), mTitle);
                intent.putExtra(getString(R.string.key_label_name), mTitle);
                intent.putExtra(getString(R.string.key_artwork_url), mIcon);
                startActivity(intent);
            }
        });
    }
    public void displayMusicPlayerControl() {
        // TODO Auto-generated method stub
        if (musicSrv != null) {
            rl_musiccontorl.setVisibility(View.VISIBLE);
            card_view_musiccontorl.setVisibility(View.VISIBLE);
            if (sharedPref.getTrackTitle() != null) {
                tv_track_title.setText(sharedPref.getTrackTitle());
            } else {
                rl_musiccontorl.setVisibility(View.GONE);
                card_view_musiccontorl.setVisibility(View.GONE);
            }
            ImageLoader mImageLoader;
            if (sharedPref.getTrackImageUrl() != null) {
                mImageLoader = AppController.getInstance().getImageLoader();
                mImageLoader.get(sharedPref.getTrackImageUrl(), ImageLoader.getImageListener(iv_track_image,
                        R.drawable.ic_audiotrack_black, R.drawable.ic_audiotrack_black));
                iv_track_image.setImageUrl(sharedPref.getTrackImageUrl(), mImageLoader);
            }
            if (musicSrv.isPng()) {
                iv_player_control.setImageResource(R.drawable.pause_button);
            } else {
                iv_player_control.setImageResource(R.drawable.play_button);
            }
        } else {
            rl_musiccontorl.setVisibility(View.GONE);
            card_view_musiccontorl.setVisibility(View.GONE);
        }
    }
    private void resetplayer() {
        // TODO Auto-generated method stub
        if (musicSrv != null) {
            if (musicSrv.isPng()) {
                musicSrv.pausePlayer();
                iv_player_control.setImageResource(R.drawable.play_button);
            } else {
                musicSrv.go();
                iv_player_control.setImageResource(R.drawable.pause_button);
            }
            if (sharedPref.getTrackTitle() != null) {
                tv_track_title.setText(sharedPref.getTrackTitle());
            }
            ImageLoader mImageLoader;
            if (sharedPref.getTrackImageUrl() != null) {
                mImageLoader = AppController.getInstance().getImageLoader();
                mImageLoader.get(sharedPref.getTrackImageUrl(), ImageLoader.getImageListener(iv_track_image,
                        R.drawable.ic_audiotrack_black, R.drawable.ic_audiotrack_black));
                iv_track_image.setImageUrl(sharedPref.getTrackImageUrl(), mImageLoader);
            }
            rl_musiccontorl.setVisibility(View.VISIBLE);
            card_view_musiccontorl.setVisibility(View.VISIBLE);
        } else {
            rl_musiccontorl.setVisibility(View.GONE);
            card_view_musiccontorl.setVisibility(View.GONE);
        }
    }
    @Override
    protected void onStart() {
        super.onStart();
    }
    private void showMessage(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!isFinishing()) {
                    customDialog.showCustomDialog(msg);
                }
            }
        });
    }
    public void showCustomToast(String msg) {       
        SpannableStringBuilder spannableString = application.getSpannableMessage(mContext, FONT_REVICONS, msg);
        Toast.makeText(mContext, spannableString, Toast.LENGTH_SHORT).show();
    }
    public class TrackListAdapter extends RecyclerView.Adapter<TrackListAdapter.ViewHolder> {
        private final ArrayList<TrackDetails> arrTracklist;
        private int pos;
        public TrackListAdapter(ArrayList<TrackDetails> items) {
            arrTracklist = items;
        }
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.tracklist_listitem, parent, false);
            return new ViewHolder(view);
        }
        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {
            if (arrTracklist != null) {
                holder.mItem = arrTracklist.get(position);
                if (holder.mItem != null) {
                    holder.tv_title.setText(holder.mItem.getTitle());
//                  if (holder.mItem.getDuration() != null) {
//                      String duration = getDuraction(holder.mItem.getDuration());
//                      if (duration != null) {
//                          holder.tv_duration.setText(duration);
//                      }
//                  }
                    ImageLoader mImageLoader;
                    if (holder.mItem.getArtwork_url() != null) {
                        mImageLoader = AppController.getInstance().getImageLoader();
                        mImageLoader.get(holder.mItem.getArtwork_url(), ImageLoader.getImageListener(holder.imageView,
                                R.drawable.ic_audiotrack_black, R.drawable.ic_audiotrack_black));
                        holder.imageView.setImageUrl(holder.mItem.getArtwork_url(), mImageLoader);
                    }
                }
            }
        }
        @Override
        public int getItemCount() {
            return arrTracklist.size();
        }
        public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            public final View mView;
            public final NetworkImageView imageView;
            public final TextView tv_title;
            public final TextView tv_duration;
            public TrackDetails mItem;
            public ViewHolder(View view) {
                super(view);
                mView = view;
                imageView = (NetworkImageView) view.findViewById(R.id.iv_icon);
                tv_title = (TextView) view.findViewById(R.id.tv_title);
                application.setTypeface(tv_title, FONT_REVICONS, context);
                tv_duration = (TextView) view.findViewById(R.id.tv_duration);
                application.setTypeface(tv_duration, FONT_REVICONS, context);
                mView.setOnClickListener(this);
            }
            @Override
            public String toString() {
                return super.toString() + " '" + tv_title.getText() + "'";
            }
            @Override
            public void onClick(View v) {
                pos =getPosition();
                Log.d(TAG, "onClick " + getPosition());
                progressbar_tracklist.setVisibility(View.VISIBLE);

                if (connDetector.checkInternetConnection()) {
                    String trackId = null;
                    String trackTitle = null;
                    String trackImageUrl = null;
                    if (mArrTrackList != null) {
                        rl_musiccontorl.setVisibility(View.VISIBLE);
                        card_view_musiccontorl.setVisibility(View.VISIBLE);
                        trackId = mArrTrackList.get(pos).getId();
                        trackTitle = mArrTrackList.get(pos).getTitle();
                        trackImageUrl = mArrTrackList.get(pos).getArtwork_url();
                        sharedPref.saveTrackId(trackId);
                        sharedPref.saveTrackTitle(trackTitle);
                        sharedPref.saveTrackImageUrl(trackImageUrl);
                        musicSrv.setSongDetails(mArrTrackList, pos);
                        musicSrv.playSong();
                        PlayerConstants.SONG_PAUSED = false;
                        PlayerConstants.SONG_NUMBER = pos;
                        //PlayerConstants.SONG_ID = trackId;
//                      boolean isServiceRunning = UtilFunctions.isServiceRunning(SongService.class.getName(), getApplicationContext());
//                      if (!isServiceRunning) {
//                          Intent i = new Intent(getApplicationContext(),SongService.class);
//                          startService(i);
//                      } else {
//                          PlayerConstants.SONG_CHANGE_HANDLER.sendMessage(PlayerConstants.SONG_CHANGE_HANDLER.obtainMessage());
//                      }
                    }
                    resetplayer();
                } else {
                    showCustomToast(getResources().getString(R.string.network_error));
                    finish();
                }
            }
        }
    }        }

Сервис в котором обрабатываются все действия с проигрыванием аудио:

public class MusicService extends Service
        implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, OnCompletionListener {
    public static final String TAG = MusicService.class.getName();
    private static final int NOTIFY_ID = 1;
    public static final String NOTIFY_PREVIOUS = null;
    public static final String NOTIFY_DELETE = null;
    public static final String NOTIFY_PAUSE = null;
    public static final String NOTIFY_PLAY = null;
    public static final String NOTIFY_NEXT = null;
    private ComponentName remoteComponentName;
    private RemoteControlClient remoteControlClient;
    AudioManager audioManager;
    // media mMediaPlayer
    private MediaPlayer mMediaPlayer;
    // mTrack list
    private ArrayList<TrackDetails> mTrackList;
    // current position
    private int mTrackIndex;
    private String mTrackTitle = "";
    private double startTime = 0;
    private double finalTime = 0;
    private final IBinder musicBind = new MusicBinder();
    private boolean shuffle = false;
    private Random rand;
    private static boolean currentVersionSupportBigNotification = false;
    private static boolean currentVersionSupportLockScreenControls = false;
    int NOTIFICATION_ID = 1111;
    public void onCreate() {
        // create the service
        super.onCreate();
        currentVersionSupportBigNotification = UtilFunctions.currentVersionSupportBigNotification();
        currentVersionSupportLockScreenControls = UtilFunctions.currentVersionSupportLockScreenControls();
        rand = new Random();
        // initialize position
        mTrackIndex = 0;
        // create mMediaPlayer
        mMediaPlayer = new MediaPlayer();
        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        initMusicPlayer();
        mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                // TODO Auto-generated method stub
                Log.d(TAG, "setOnCompletionListener");
                playNext();
            }
        });
    }
    public void initMusicPlayer() {
        // set mMediaPlayer properties
        mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnErrorListener(this);
    }
    public class MusicBinder extends Binder {
        public MusicService getService() {
            return MusicService.this;
        }
    }
    public void setList(ArrayList<TrackDetails> theSongs) {
        mTrackList = theSongs;
    }
    @Override
    public IBinder onBind(Intent intent) {
        return musicBind;
    }
    @SuppressLint("NewApi")
    public void playSong() {
        // play a mTrack
        mMediaPlayer.reset();
        // get mTrack
        if (mTrackList != null) {
            TrackDetails playSong = mTrackList.get(mTrackIndex);
            // get id
            // long currSong = Double.parseDouble(playSong.getId());
            // set uri
            Uri trackUri = Uri.parse(playSong.getStream_url());
            try {
                mMediaPlayer = new MediaPlayer();
                Log.d(TAG, "playSong.getStream_url() : " +
                playSong.getStream_url());
                mMediaPlayer.setDataSource(playSong.getStream_url()); // + "?client_id=" + Config.CLIENT_ID);
                mMediaPlayer.setOnPreparedListener(this);
                mMediaPlayer.prepareAsync();
                if(currentVersionSupportLockScreenControls){
                    RegisterRemoteClient();
                }
                if(currentVersionSupportLockScreenControls){
                    remoteControlClient.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING);
                }
            newNotification();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.e("MUSIC SERVICE", "Error setting data source", e);
            }
        }
    }
    @Override
    public boolean onUnbind(Intent intent) {
        mMediaPlayer.stop();
        mMediaPlayer.release();
        return false;
    }
    @Override
    public void onCompletion(MediaPlayer mp){
        // TODO Auto-generated method stub
        Log.d(TAG, "onCompletion");
        playNext();
        /*if (mp.getCurrentPosition() < 0) {
            Log.d(TAG, "mp.getCurrentPosition()");
            mTrackIndex++;
            Log.d(TAG, "mTrackIndex : " +mTrackIndex);
            Log.d(TAG, "mTrackList.size() : " +mTrackList.size());
            if(mTrackIndex<=mTrackList.size())
            {
                mp.reset();
                //playNext();
                playSong();
            }
        }*/
    }
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        // TODO Auto-generated method stub
        mp.reset();
        return false;
    }
    @SuppressLint("NewApi")
    @Override
    public void onPrepared(MediaPlayer mp) {
        // TODO Auto-generated method stub
        // start playback
        mp.start();
    }
    public void setSongDetails(ArrayList<TrackDetails> trackDetails, int mTrack) {
        initMusicPlayer();
        onPrepared(mMediaPlayer);
        mTrackList = trackDetails;
        mTrackIndex = mTrack;
        mTrackTitle = mTrackList.get(mTrackIndex).getTitle();
        playSong();
    }
    public int getPosn() {
        return mMediaPlayer.getCurrentPosition();
    }
    public int getDur() {
        return mMediaPlayer.getDuration();
    }
    public boolean isPng() {
        return mMediaPlayer.isPlaying();
    }
    public void pausePlayer() {
        mMediaPlayer.pause();
    }
    @SuppressLint("NewApi")
    private void showNotification() {
        // TODO Auto-generated method stub
        Intent notIntent = new Intent(this, HomeActivity.class);
        notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendInt = PendingIntent.getActivity(this, 0, notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        Notification.Builder builder = new Notification.Builder(this);
        builder.setContentIntent(pendInt).setSmallIcon(R.drawable.ic_music_video_black).setTicker(mTrackTitle)
                .setOngoing(true).setContentTitle("Playing").setContentText(mTrackTitle);
        Notification not = builder.build();
        startForeground(NOTIFY_ID, not);
    }
    @SuppressLint("NewApi")
    private void RegisterRemoteClient(){
        remoteComponentName = new ComponentName(getApplicationContext(), new NotificationBroadcast().ComponentName());
        try {
            if(remoteControlClient == null) {
                audioManager.registerMediaButtonEventReceiver(remoteComponentName);
                Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
                mediaButtonIntent.setComponent(remoteComponentName);
                PendingIntent mediaPendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0);
                remoteControlClient = new RemoteControlClient(mediaPendingIntent);
                audioManager.registerRemoteControlClient(remoteControlClient);
            }
            remoteControlClient.setTransportControlFlags(
                    RemoteControlClient.FLAG_KEY_MEDIA_PLAY |
                            RemoteControlClient.FLAG_KEY_MEDIA_PAUSE |
                            RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE |
                            RemoteControlClient.FLAG_KEY_MEDIA_STOP |
                            RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS |
                            RemoteControlClient.FLAG_KEY_MEDIA_NEXT);
        }catch(Exception ex) {
        }
    }
    /**
     * Notification
     * Custom Bignotification is available from API 16
     */
    @SuppressLint("NewApi")
    private void newNotification() {
        String songName = mTrackList.get(mTrackIndex).getTitle();
        String albumName = mTrackList.get(mTrackIndex).getGenre();
        RemoteViews simpleContentView = new RemoteViews(getApplicationContext().getPackageName(),R.layout.custom_notification);
        RemoteViews expandedView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.big_notification);
        Notification notification = new NotificationCompat.Builder(getApplicationContext())
        .setSmallIcon(R.drawable.ic_audiotrack_gray)
        .setContentTitle(songName).build();
        setListeners(simpleContentView);
        setListeners(expandedView);
        notification.contentView = simpleContentView;
        if(currentVersionSupportBigNotification){
            notification.bigContentView = expandedView;
        }
        try{
            /*long albumId = Integer.parseInt(PlayerConstants.SONGS_LIST.get(PlayerConstants.SONG_NUMBER).getId());
            Bitmap albumArt = UtilFunctions.getAlbumart(getApplicationContext(), albumId);*/
            String albumUrl = mTrackList.get(mTrackIndex).getGenre();
            URL url = new URL(albumUrl);
            Bitmap albumArt = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            if(albumArt != null){
                notification.contentView.setImageViewBitmap(R.id.imageViewAlbumArt, albumArt);
                if(currentVersionSupportBigNotification){
                    notification.bigContentView.setImageViewBitmap(R.id.imageViewAlbumArt, albumArt);
                }
            }else{
                notification.contentView.setImageViewResource(R.id.imageViewAlbumArt, R.drawable.ic_audiotrack_gray);
                if(currentVersionSupportBigNotification){
                    notification.bigContentView.setImageViewResource(R.id.imageViewAlbumArt, R.drawable.ic_audiotrack_gray);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        if(PlayerConstants.SONG_PAUSED){
            notification.contentView.setViewVisibility(R.id.btnPause, View.GONE);
            notification.contentView.setViewVisibility(R.id.btnPlay, View.VISIBLE);
            if(currentVersionSupportBigNotification){
                notification.bigContentView.setViewVisibility(R.id.btnPause, View.GONE);
                notification.bigContentView.setViewVisibility(R.id.btnPlay, View.VISIBLE);
            }
        }else{
            notification.contentView.setViewVisibility(R.id.btnPause, View.VISIBLE);
            notification.contentView.setViewVisibility(R.id.btnPlay, View.GONE);
            if(currentVersionSupportBigNotification){
                notification.bigContentView.setViewVisibility(R.id.btnPause, View.VISIBLE);
                notification.bigContentView.setViewVisibility(R.id.btnPlay, View.GONE);
            }
        }
        notification.contentView.setTextViewText(R.id.textSongName, songName);
        notification.contentView.setTextViewText(R.id.textAlbumName, albumName);
        if(currentVersionSupportBigNotification){
            notification.bigContentView.setTextViewText(R.id.textSongName, songName);
            notification.bigContentView.setTextViewText(R.id.textAlbumName, albumName);
        }
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
        startForeground(NOTIFICATION_ID, notification);
    }
    public void seek(int posn) {
        mMediaPlayer.seekTo(posn);
    }
    public void go() {
        mMediaPlayer.start();
    }
    public void playPrev() {
        mTrackIndex--;
        if (mTrackIndex != 0)
            mTrackIndex = mTrackList.size() - 1;
        playSong();
    }
    @Override
    public void onDestroy() {
        if(mMediaPlayer != null){
            mMediaPlayer.stop();
            mMediaPlayer = null;
        }
        stopForeground(true);
    }
    public void setShuffle() {
        if (shuffle)
            shuffle = false;
        else
            shuffle = true;
    }
    public void playNext() {
        if (mTrackList!=null) {
            if (shuffle) {
                int newSong = mTrackIndex;
                while (newSong == mTrackIndex) {
                    newSong = rand.nextInt(mTrackList.size());
                }
                mTrackIndex = newSong;
            } else {
                mTrackIndex++;
                if (mTrackIndex <= mTrackList.size())
                    mTrackIndex = 0;
            }
            playSong();
        }
    }
}

это сервис, и прописать в теле метода и определить в нем:

ProgressBar progressBar; ... progressBar = (ProgressBar) fiendViewById (R.id.progressBar); ... progressBar.setVisibility(View.VISABLE);

невозможно.

READ ALSO
Проблема с подключением файла БД при сборке в Maven

Проблема с подключением файла БД при сборке в Maven

Доброго времени суток, собираю свой проект с помощью Maven и возникла проблема с получением файла БД как ресурсаСоздаю соединение таким вот...

371
Алгоритм поиска в тексте

Алгоритм поиска в тексте

Всем доброго времени сутокХотел бы выслушать идеи алгоритмов для следующего задания

402
При запуске Appium теста для Андроид - ошибка &#39;java -version&#39; failed

При запуске Appium теста для Андроид - ошибка 'java -version' failed

Запускаю Appium Test для Android из Intellij IdeaПроект делал по обучающему видео

222
Вызов передаваемого метода в методе Java

Вызов передаваемого метода в методе Java

Нужно сделать сортитовку JSONObjectПодскажите пожалуйста

213