0

Я создал приложение, которое воспроизводит музыку в сервисе. Услуга работает очень хорошо, и музыка воспроизводится так, как ожидалось. Проблема, с которой я сталкиваюсь, - это когда я снова нажимаю кнопку воспроизведения в уведомлении, прежде чем звук перестанет воспроизводить музыку снова в фоновом режиме, который в свою очередь воспроизводит звук параллельно. Если mediaplayer.isPlaying состояние не работает! Мой кодВоспроизведение мультимедиа несколько раз при нажатии кнопки воспроизведения на панели уведомлений

public class MediaPlayerService extends Service implements MediaPlayer.OnCompletionListener { 
    Notification status; 
    private final String LOG_TAG = "NotificationService"; 
    private MediaPlayer mediaPlayer;; 
    private MediaSessionManager mManager; 
    private MediaSession mSession; 
    private MediaController mController; 
    /** indicates how to behave if the service is killed */ 
    int mStartMode; 

    /** interface for clients that bind */ 
    IBinder mBinder; 

    /** indicates whether onRebind should be used */ 
    boolean mAllowRebind; 

    /** Called when the service is being created. */ 
    @Override 
    public void onCreate() { 
     mediaPlayer = new MediaPlayer(); 
     mediaPlayer.reset(); 
     mediaPlayer.setOnCompletionListener(this); 
    } 
    @Nullable 
    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     AssetFileDescriptor afd = null; 
     try { 
      afd = getAssets().openFd("mySound.mp3"); 
      mediaPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength()); 
      mediaPlayer.prepare(); 
      if(!mediaPlayer.isPlaying()) { 
       Toast.makeText(this, "Not Playing", Toast.LENGTH_SHORT).show(); 
       mediaPlayer.start(); 
      } 
      else{ 
       Toast.makeText(this, "Playing", Toast.LENGTH_SHORT).show(); 
       mediaPlayer.pause(); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) { 
      showNotification(); 
      Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show(); 

     } else if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) { 
      Toast.makeText(this, "Clicked Previous", Toast.LENGTH_SHORT).show(); 
      Log.i(LOG_TAG, "Clicked Previous"); 
     } else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) { 
      if(mediaPlayer.isPlaying()) { 
       Toast.makeText(this, "Playing", Toast.LENGTH_SHORT).show(); 
      } 
      else{ 
       Toast.makeText(this, "Not Playing", Toast.LENGTH_SHORT).show(); 

      } 
      Log.i(LOG_TAG, "Clicked Play"); 
     } else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) { 
      Toast.makeText(this, "Clicked Next", Toast.LENGTH_SHORT).show(); 
      Log.i(LOG_TAG, "Clicked Next"); 
     } else if (intent.getAction().equals(
       Constants.ACTION.STOPFOREGROUND_ACTION)) { 
      if(mediaPlayer.isPlaying()) { 
       mediaPlayer.stop(); 
      } 
      stopForeground(true); 
      stopSelf(); 
     } 
     return START_STICKY; 
    } 

    @Override 
    public void onCompletion(MediaPlayer mp) { 
     showNotificationClose(); 
     Toast.makeText(this, "OVER", Toast.LENGTH_SHORT).show(); 
    } 
    /** A client is binding to the service with bindService() */ 
    @Override 
    public IBinder onBind(Intent intent) { 
     return mBinder; 
    } 

    /** Called when all clients have unbound with unbindService() */ 
    @Override 
    public boolean onUnbind(Intent intent) { 
     return mAllowRebind; 
    } 

    /** Called when a client is binding to the service with bindService()*/ 
    @Override 
    public void onRebind(Intent intent) { 

    } 

    /** Called when The service is no longer used and is being destroyed */ 
    @Override 
    public void onDestroy() { 

    } 
    private void showNotification() { 
// Using RemoteViews to bind custom layouts into Notification 
     RemoteViews views = new RemoteViews(getPackageName(), 
       R.layout.status_bar); 
     RemoteViews bigViews = new RemoteViews(getPackageName(), 
       R.layout.status_bar_expanded); 

// showing default album image 
     views.setViewVisibility(R.id.status_bar_icon, View.VISIBLE); 
     views.setViewVisibility(R.id.status_bar_album_art, View.GONE); 
     bigViews.setImageViewBitmap(R.id.status_bar_album_art, 
       Constants.getDefaultAlbumArt(this)); 

     Intent notificationIntent = new Intent(this, myHome.class); 
     notificationIntent.setAction(Constants.ACTION.MAIN_ACTION); 
     notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK 
       | Intent.FLAG_ACTIVITY_CLEAR_TASK); 
     PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, 
       notificationIntent, 0); 

     Intent previousIntent = new Intent(this, MediaPlayerService.class); 
     previousIntent.setAction(Constants.ACTION.PREV_ACTION); 
     PendingIntent ppreviousIntent = PendingIntent.getService(this, 0, 
       previousIntent, 0); 

     Intent playIntent = new Intent(this, MediaPlayerService.class); 
     playIntent.setAction(Constants.ACTION.PLAY_ACTION); 
     PendingIntent pplayIntent = PendingIntent.getService(this, 0, 
       playIntent, 0); 

     Intent nextIntent = new Intent(this, MediaPlayerService.class); 
     nextIntent.setAction(Constants.ACTION.NEXT_ACTION); 
     PendingIntent pnextIntent = PendingIntent.getService(this, 0, 
       nextIntent, 0); 

     Intent closeIntent = new Intent(this, MediaPlayerService.class); 
     closeIntent.setAction(Constants.ACTION.STOPFOREGROUND_ACTION); 
     PendingIntent pcloseIntent = PendingIntent.getService(this, 0, 
       closeIntent, 0); 

     views.setOnClickPendingIntent(R.id.status_bar_play, pplayIntent); 
     bigViews.setOnClickPendingIntent(R.id.status_bar_play, pplayIntent); 

     views.setOnClickPendingIntent(R.id.status_bar_next, pnextIntent); 
     bigViews.setOnClickPendingIntent(R.id.status_bar_next, pnextIntent); 

     views.setOnClickPendingIntent(R.id.status_bar_prev, ppreviousIntent); 
     bigViews.setOnClickPendingIntent(R.id.status_bar_prev, ppreviousIntent); 

     views.setOnClickPendingIntent(R.id.status_bar_collapse, pcloseIntent); 
     bigViews.setOnClickPendingIntent(R.id.status_bar_collapse, pcloseIntent); 

     views.setImageViewResource(R.id.status_bar_play, 
       R.drawable.apollo_holo_dark_pause); 
     bigViews.setImageViewResource(R.id.status_bar_play, 
       R.drawable.apollo_holo_dark_pause); 

     views.setTextViewText(R.id.status_bar_track_name, "Cheap Thrills"); 
     bigViews.setTextViewText(R.id.status_bar_track_name, "Cheap Thrills"); 

     views.setTextViewText(R.id.status_bar_artist_name, "Sia"); 
     bigViews.setTextViewText(R.id.status_bar_artist_name, "Sia"); 

     bigViews.setTextViewText(R.id.status_bar_album_name, "Cheap Thrills"); 

     status = new Notification.Builder(this).build(); 
     status.contentView = views; 
     status.bigContentView = bigViews; 
     status.flags = Notification.FLAG_ONGOING_EVENT; 
     status.icon = R.drawable.icon; 
     status.contentIntent = pendingIntent; 
     startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE, status); 
    } 

    private void showNotificationClose() { 
// Using RemoteViews to bind custom layouts into Notification 
     RemoteViews views = new RemoteViews(getPackageName(), 
       R.layout.status_bar); 
     RemoteViews bigViews = new RemoteViews(getPackageName(), 
       R.layout.status_bar_expanded); 

// showing default album image 
     views.setViewVisibility(R.id.status_bar_icon, View.VISIBLE); 
     views.setViewVisibility(R.id.status_bar_album_art, View.GONE); 
     bigViews.setImageViewBitmap(R.id.status_bar_album_art, 
       Constants.getDefaultAlbumArt(this)); 

     Intent notificationIntent = new Intent(this, myHome.class); 
     notificationIntent.setAction(Constants.ACTION.MAIN_ACTION); 
     notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK 
       | Intent.FLAG_ACTIVITY_CLEAR_TASK); 
     PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, 
       notificationIntent, 0); 

     Intent previousIntent = new Intent(this, MediaPlayerService.class); 
     previousIntent.setAction(Constants.ACTION.PREV_ACTION); 
     PendingIntent ppreviousIntent = PendingIntent.getService(this, 0, 
       previousIntent, 0); 

     Intent playIntent = new Intent(this, MediaPlayerService.class); 
     playIntent.setAction(Constants.ACTION.PLAY_ACTION); 
     PendingIntent pplayIntent = PendingIntent.getService(this, 0, 
       playIntent, 0); 

     Intent nextIntent = new Intent(this, MediaPlayerService.class); 
     nextIntent.setAction(Constants.ACTION.NEXT_ACTION); 
     PendingIntent pnextIntent = PendingIntent.getService(this, 0, 
       nextIntent, 0); 

     Intent closeIntent = new Intent(this, MediaPlayerService.class); 
     closeIntent.setAction(Constants.ACTION.STOPFOREGROUND_ACTION); 
     PendingIntent pcloseIntent = PendingIntent.getService(this, 0, 
       closeIntent, 0); 

     views.setOnClickPendingIntent(R.id.status_bar_play, pplayIntent); 
     bigViews.setOnClickPendingIntent(R.id.status_bar_play, pplayIntent); 

     views.setOnClickPendingIntent(R.id.status_bar_next, pnextIntent); 
     bigViews.setOnClickPendingIntent(R.id.status_bar_next, pnextIntent); 

     views.setOnClickPendingIntent(R.id.status_bar_prev, ppreviousIntent); 
     bigViews.setOnClickPendingIntent(R.id.status_bar_prev, ppreviousIntent); 

     views.setOnClickPendingIntent(R.id.status_bar_collapse, pcloseIntent); 
     bigViews.setOnClickPendingIntent(R.id.status_bar_collapse, pcloseIntent); 

     views.setImageViewResource(R.id.status_bar_play, 
       R.drawable.apollo_holo_dark_play); 
     bigViews.setImageViewResource(R.id.status_bar_play, 
       R.drawable.apollo_holo_dark_play); 

     views.setTextViewText(R.id.status_bar_track_name, "Cheap Thrills"); 
     bigViews.setTextViewText(R.id.status_bar_track_name, "Cheap Thrills"); 

     views.setTextViewText(R.id.status_bar_artist_name, "Sia"); 
     bigViews.setTextViewText(R.id.status_bar_artist_name, "Sia"); 

     bigViews.setTextViewText(R.id.status_bar_album_name, "Cheap Thrills"); 

     status = new Notification.Builder(this).build(); 
     status.contentView = views; 
     status.bigContentView = bigViews; 
     status.flags = Notification.FLAG_ONGOING_EVENT; 
     status.icon = R.drawable.icon; 
     status.contentIntent = pendingIntent; 
     startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE, status); 
    } 

} 
+0

проверьте, играет ли он или нет на 'onResume()' – hrskrs

+2

@hrskrs Я нажимаю кнопку воспроизведения из уведомления. Затем он вызовет функцию onResume? Также будет ли служба иметь функцию onResume? –

ответ

1

При создании Intent в уведомлении создается новый экземпляр службы и, следовательно, новый медиаплеер экземпляр и так далее .. из-за чего песня начинает играть снова.

Необходимо связать услугу, если вы хотите установить соединение с ней.

+3

Я решил проблему .. Просто инициализированный медиаплеер и источник в onCreate и играет, проверяя соответствующие действия –