revamp podcast playback / drop youtube support

This commit is contained in:
David Luhmer 2019-05-06 19:33:06 +02:00
parent e49d5d25b0
commit 47fa9df253
13 changed files with 467 additions and 597 deletions

View file

@ -184,7 +184,7 @@ dependencies {
implementation 'com.nbsp:library:1.02' // MaterialFilePicker
extraImplementation 'com.github.tommus:youtube-android-player-api:1.2.2'
//extraImplementation 'com.github.tommus:youtube-android-player-api:1.2.2'
testImplementation 'junit:junit:4.12'

View file

@ -1,26 +1,14 @@
package de.luhmer.owncloudnewsreader;
import android.animation.Animator;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.os.ResultReceiver;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.util.Log;
import android.util.TypedValue;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.nextcloud.android.sso.helper.VersionCheckHelper;
@ -38,19 +26,17 @@ import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import butterknife.BindView;
import butterknife.ButterKnife;
import de.luhmer.owncloudnewsreader.ListView.SubscriptionExpandableListAdapter;
import de.luhmer.owncloudnewsreader.database.DatabaseConnectionOrm;
import de.luhmer.owncloudnewsreader.database.model.RssItem;
import de.luhmer.owncloudnewsreader.di.ApiProvider;
import de.luhmer.owncloudnewsreader.events.podcast.CollapsePodcastView;
import de.luhmer.owncloudnewsreader.events.podcast.ExpandPodcastView;
import de.luhmer.owncloudnewsreader.events.podcast.PodcastCompletedEvent;
import de.luhmer.owncloudnewsreader.events.podcast.RegisterVideoOutput;
import de.luhmer.owncloudnewsreader.events.podcast.UpdatePodcastStatusEvent;
import de.luhmer.owncloudnewsreader.events.podcast.VideoDoubleClicked;
import de.luhmer.owncloudnewsreader.helper.PostDelayHandler;
import de.luhmer.owncloudnewsreader.helper.SizeAnimator;
import de.luhmer.owncloudnewsreader.helper.ThemeChooser;
import de.luhmer.owncloudnewsreader.interfaces.IPlayPausePodcastClicked;
import de.luhmer.owncloudnewsreader.model.MediaItem;
@ -58,15 +44,12 @@ import de.luhmer.owncloudnewsreader.model.PodcastItem;
import de.luhmer.owncloudnewsreader.notification.NextcloudNotificationManager;
import de.luhmer.owncloudnewsreader.services.PodcastDownloadService;
import de.luhmer.owncloudnewsreader.services.PodcastPlaybackService;
import de.luhmer.owncloudnewsreader.services.podcast.PlaybackService;
import de.luhmer.owncloudnewsreader.ssl.MemorizingTrustManager;
import de.luhmer.owncloudnewsreader.view.PodcastSlidingUpPanelLayout;
import de.luhmer.owncloudnewsreader.view.ZoomableRelativeLayout;
import de.luhmer.owncloudnewsreader.widget.WidgetProvider;
import static de.luhmer.owncloudnewsreader.Constants.MIN_NEXTCLOUD_FILES_APP_VERSION_CODE;
import static de.luhmer.owncloudnewsreader.services.PodcastPlaybackService.CURRENT_PODCAST_ITEM_MEDIA_ITEM;
import static de.luhmer.owncloudnewsreader.services.PodcastPlaybackService.PLAYBACK_SPEED_FLOAT;
public class PodcastFragmentActivity extends AppCompatActivity implements IPlayPausePodcastClicked {
@ -77,26 +60,14 @@ public class PodcastFragmentActivity extends AppCompatActivity implements IPlayP
@Inject protected MemorizingTrustManager mMTM;
@Inject protected PostDelayHandler mPostDelayHandler;
private MediaBrowserCompat mMediaBrowser;
private EventBus eventBus;
private PodcastFragment mPodcastFragment;
private int appHeight;
private int appWidth;
@BindView(R.id.videoPodcastSurfaceWrapper)
protected ZoomableRelativeLayout rlVideoPodcastSurfaceWrapper;
@BindView(R.id.sliding_layout)
protected PodcastSlidingUpPanelLayout sliding_layout;
private boolean currentlyPlaying = false;
private boolean videoViewInitialized = false;
private boolean isVideoViewVisible = true;
private static final int animationTime = 300; //Milliseconds
private boolean isFullScreen = false;
private float scaleFactor = 1;
private boolean useAnimation = false;
@Override
@ -114,15 +85,10 @@ public class PodcastFragmentActivity extends AppCompatActivity implements IPlayP
mPostDelayHandler.stopRunningPostDelayHandler();
}
@Override
protected void onStart() {
super.onStart();
mMTM.bindDisplayActivity(this);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
eventBus = EventBus.getDefault();
ButterKnife.bind(this);
@ -150,12 +116,13 @@ public class PodcastFragmentActivity extends AppCompatActivity implements IPlayP
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
*/
mMediaBrowser = new MediaBrowserCompat(this,
new ComponentName(this, PodcastPlaybackService.class),
mConnectionCallbacks,
null); // optional Bundle
}
super.onPostCreate(savedInstanceState);
@Override
protected void onStart() {
super.onStart();
mMTM.bindDisplayActivity(this);
}
@Override
@ -163,8 +130,6 @@ public class PodcastFragmentActivity extends AppCompatActivity implements IPlayP
mMTM.unbindDisplayActivity(this);
super.onStop();
mMediaBrowser.disconnect();
}
@ -194,11 +159,6 @@ public class PodcastFragmentActivity extends AppCompatActivity implements IPlayP
protected void onResume() {
eventBus.register(this);
if (mMediaBrowser != null && !mMediaBrowser.isConnected()) {
sliding_layout.setPanelHeight(0);
sliding_layout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
}
super.onResume();
}
@ -207,8 +167,7 @@ public class PodcastFragmentActivity extends AppCompatActivity implements IPlayP
Log.d(TAG, "onPause");
eventBus.unregister(this);
//TODO THIS IS NEVER REACHED!
/*
isVideoViewVisible = false;
videoViewInitialized = false;
@ -216,10 +175,10 @@ public class PodcastFragmentActivity extends AppCompatActivity implements IPlayP
rlVideoPodcastSurfaceWrapper.setVisibility(View.GONE);
rlVideoPodcastSurfaceWrapper.removeAllViews();
*/
WidgetProvider.UpdateWidget(this);
if (NextcloudNotificationManager.isUnreadRssCountNotificationVisible(this)) {
DatabaseConnectionOrm dbConn = new DatabaseConnectionOrm(this);
int count = Integer.parseInt(dbConn.getUnreadItemsCountForSpecificFolder(SubscriptionExpandableListAdapter.SPECIAL_FOLDERS.ALL_UNREAD_ITEMS));
@ -247,41 +206,7 @@ public class PodcastFragmentActivity extends AppCompatActivity implements IPlayP
}
*/
private final MediaBrowserCompat.ConnectionCallback mConnectionCallbacks =
new MediaBrowserCompat.ConnectionCallback() {
@Override
public void onConnected() {
Log.d(TAG, "onConnected() called");
// Get the token for the MediaSession
MediaSessionCompat.Token token = mMediaBrowser.getSessionToken();
try {
// Create a MediaControllerCompat
MediaControllerCompat mediaController = new MediaControllerCompat(PodcastFragmentActivity.this, token);
// Save the controller
MediaControllerCompat.setMediaController(PodcastFragmentActivity.this, mediaController);
// Finish building the UI
//buildTransportControls();
} catch (RemoteException e) {
Log.e(TAG, "Connecting to podcast service failed!", e);
}
}
@Override
public void onConnectionSuspended() {
Log.d(TAG, "onConnectionSuspended() called");
// The Service has crashed. Disable transport controls until it automatically reconnects
}
@Override
public void onConnectionFailed() {
Log.e(TAG, "onConnectionFailed() called");
// The Service has refused our connection
}
};
/*
private void buildTransportControls() {
@ -302,15 +227,6 @@ public class PodcastFragmentActivity extends AppCompatActivity implements IPlayP
// Register a Callback to stay in sync
mediaController.registerCallback(controllerCallback);
}
MediaControllerCompat.Callback controllerCallback =
new MediaControllerCompat.Callback() {
@Override
public void onMetadataChanged(MediaMetadataCompat metadata) {}
@Override
public void onPlaybackStateChanged(PlaybackStateCompat state) {}
};
*/
public PodcastSlidingUpPanelLayout getSlidingLayout() {
@ -319,268 +235,62 @@ public class PodcastFragmentActivity extends AppCompatActivity implements IPlayP
public boolean handlePodcastBackPressed() {
if(mPodcastFragment != null && sliding_layout.getPanelState().equals(SlidingUpPanelLayout.PanelState.EXPANDED)) {
if (!mPodcastFragment.onBackPressed())
sliding_layout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
sliding_layout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
return true;
}
return false;
}
protected void updatePodcastView() {
if(mPodcastFragment == null) {
mPodcastFragment = PodcastFragment.newInstance();
}
/*
if(mPodcastFragment != null) {
getSupportFragmentManager().beginTransaction().remove(mPodcastFragment).commitAllowingStateLoss();
}
*/
mPodcastFragment = PodcastFragment.newInstance();
getSupportFragmentManager().beginTransaction()
.replace(R.id.podcast_frame, mPodcastFragment)
.commitAllowingStateLoss();
if(!currentlyPlaying)
sliding_layout.setPanelHeight(0);
collapsePodcastView();
}
@Subscribe
public void onEvent(CollapsePodcastView event) {
Log.v(TAG, "onEvent(CollapsePodcastView) called with: event = [" + event + "]");
collapsePodcastView();
}
@Subscribe
public void onEvent(UpdatePodcastStatusEvent podcast) {
boolean playStateChanged = currentlyPlaying;
//If file is loaded or preparing and podcast is paused/not running expand the view
currentlyPlaying = podcast.getStatus() == PlaybackService.Status.PLAYING
|| podcast.getStatus() == PlaybackService.Status.PAUSED;
//Check if state was changed
playStateChanged = playStateChanged != currentlyPlaying;
// If preparing or state changed and is now playing or paused
if(podcast.getStatus() == PlaybackService.Status.PREPARING
|| (playStateChanged
&& (podcast.getStatus() == PlaybackService.Status.PLAYING
|| podcast.getStatus() == PlaybackService.Status.PAUSED
|| podcast.getStatus() == PlaybackService.Status.STOPPED))) {
//Expand view
sliding_layout.setPanelHeight((int) dipToPx(68));
Log.v(TAG, "expanding podcast view!");
} else if(playStateChanged) {
//Hide view
sliding_layout.setPanelHeight(0);
currentlyPlaying = false;
Log.v(TAG, "collapsing podcast view!");
}
if (podcast.isVideoFile() && podcast.getVideoType() == PlaybackService.VideoType.Video) {
if ((!isVideoViewVisible || !videoViewInitialized) && rlVideoPodcastSurfaceWrapper.isPositionReady()) {
rlVideoPodcastSurfaceWrapper.removeAllViews();
videoViewInitialized = true;
isVideoViewVisible = true;
rlVideoPodcastSurfaceWrapper.setVisibility(View.VISIBLE);
//AlphaAnimator.AnimateVisibilityChange(rlVideoPodcastSurfaceWrapper, View.VISIBLE);
public void onEvent(ExpandPodcastView event) {
Log.v(TAG, "onEvent(ExpandPodcastView) called with: event = [" + event + "]");
expandPodcastView();
}
SurfaceView surfaceView = new SurfaceView(this);
surfaceView.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT));
rlVideoPodcastSurfaceWrapper.addView(surfaceView);
eventBus.post(new RegisterVideoOutput(surfaceView, rlVideoPodcastSurfaceWrapper));
togglePodcastVideoViewAnimation();
}
} else if(podcast.getVideoType() == PlaybackService.VideoType.YouTube) {
} else {
isVideoViewVisible = false;
videoViewInitialized = false;
eventBus.post(new RegisterVideoOutput(null, null));
rlVideoPodcastSurfaceWrapper.setVisibility(View.GONE);
//AlphaAnimator.AnimateVisibilityChange(rlVideoPodcastSurfaceWrapper, View.GONE);
rlVideoPodcastSurfaceWrapper.removeAllViews();
}
private void collapsePodcastView() {
sliding_layout.setPanelHeight(0);
}
private void expandPodcastView() {
sliding_layout.setPanelHeight((int) dipToPx(68));
}
@Subscribe
public void onEvent(PodcastCompletedEvent podcastCompletedEvent) {
sliding_layout.setPanelHeight(0);
collapsePodcastView();
sliding_layout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
currentlyPlaying = false;
//currentlyPlaying = false;
}
@Subscribe
public void onEvent(VideoDoubleClicked videoDoubleClicked) {
appHeight = getWindow().getDecorView().findViewById(android.R.id.content).getHeight();
appWidth = getWindow().getDecorView().findViewById(android.R.id.content).getWidth();
if(isFullScreen) {
rlVideoPodcastSurfaceWrapper.setDisableScale(false);
togglePodcastVideoViewAnimation();
//showSystemUI();
} else {
//hideSystemUI();
rlVideoPodcastSurfaceWrapper.setDisableScale(true);
//oldScaleFactor = rlVideoPodcastSurfaceWrapper.getScaleFactor();
final View view = rlVideoPodcastSurfaceWrapper;
final float oldHeight = view.getLayoutParams().height;
final float oldWidth = view.getLayoutParams().width;
//view.setPivotX(oldWidth/2);
//view.setPivotY(oldHeight/2);
/*
Display display = getWindowManager().getDefaultDisplay();
float width = display.getWidth(); // deprecated
float height = display.getHeight(); // deprecated
*/
scaleFactor = appWidth / (float) view.getWidth();
float newHeightTemp = oldHeight * scaleFactor;
float newWidthTemp = oldWidth * scaleFactor;
//view.animate().scaleX(scaleFactor).scaleY(scaleFactor).setDuration(100);
//scaleView(view, 1f, scaleFactor, 1f, scaleFactor);
if(newHeightTemp > appHeight) { //Could happen on Tablets or in Landscape Mode
scaleFactor = appHeight / (float) view.getHeight();
newHeightTemp = oldHeight * scaleFactor;
newWidthTemp = oldWidth * scaleFactor;
}
final float newHeight = newHeightTemp;
final float newWidth = newWidthTemp;
float newXPosition = rlVideoPodcastSurfaceWrapper.getVideoXPosition() + (int) getResources().getDimension(R.dimen.activity_vertical_margin);// (appWidth / 2) + dipToPx(10);
float newYPosition = (appHeight/2) + ((newHeight/2) - oldHeight);
useAnimation = true;
view.animate().x(newXPosition).y(newYPosition).setDuration(animationTime).setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
}
@Override
public void onAnimationEnd(Animator animator) {
if(useAnimation) {
view.startAnimation(new SizeAnimator(view, newWidth, newHeight, oldWidth, oldHeight, animationTime).sizeAnimator);
}
useAnimation = false;
}
@Override
public void onAnimationCancel(Animator animator) {
}
@Override
public void onAnimationRepeat(Animator animator) {
}
});
//rlVideoPodcastSurfaceWrapper.animate().scaleX(scaleFactor).scaleY(scaleFactor).x(newXPosition).y(newYPosition).setDuration(500).setListener(onResizeListener);
//surfaceView.animate().scaleX(scaleFactor).scaleY(scaleFactor).setDuration(500);
//oldScaleFactor
//scaleFactor = dipToPx(oldWidth) / newWidth;
//scaleFactor = (1/oldScaleFactor) * dipToPx(oldWidth) / newWidth;
//scaleFactor = oldWidth / newWidth;
scaleFactor = 1/scaleFactor;
}
isFullScreen = !isFullScreen;
}
public void togglePodcastVideoViewAnimation() {
boolean isLeftSliderOpen = false;
if(this instanceof NewsReaderListActivity && ((NewsReaderListActivity) this).drawerLayout != null) {
isLeftSliderOpen = ((NewsReaderListActivity) this).drawerLayout.isDrawerOpen(GravityCompat.START);
}
int podcastMediaControlHeightDp = pxToDp((int) getResources().getDimension(R.dimen.podcast_media_control_height));
if(sliding_layout.getPanelState().equals(SlidingUpPanelLayout.PanelState.EXPANDED)) { //On Tablets
animateToPosition(podcastMediaControlHeightDp);
} else if(isLeftSliderOpen) {
animateToPosition(0);
} else {
animateToPosition(64);
}
}
public static int pxToDp(int px)
{
public static int pxToDp(int px) {
return (int) (px / Resources.getSystem().getDisplayMetrics().density);
}
public void animateToPosition(final int yPosition) {
appHeight = getWindow().getDecorView().findViewById(android.R.id.content).getHeight();
appWidth = getWindow().getDecorView().findViewById(android.R.id.content).getWidth();
final View view = rlVideoPodcastSurfaceWrapper; //surfaceView
if(scaleFactor != 1) {
int oldHeight = view.getLayoutParams().height;
int oldWidth = view.getLayoutParams().width;
int newHeight = view.getLayoutParams().height *= scaleFactor;
int newWidth = view.getLayoutParams().width *= scaleFactor;
scaleFactor = 1;
Animation animator = new SizeAnimator(view, newWidth, newHeight, oldWidth, oldHeight, animationTime).sizeAnimator;
animator.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
animateToPosition(yPosition);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
view.startAnimation(animator);
} else {
int absoluteYPosition = appHeight - view.getHeight() - (int) getResources().getDimension(R.dimen.activity_vertical_margin) - (int) dipToPx(yPosition);
float xPosition = rlVideoPodcastSurfaceWrapper.getVideoXPosition();
//TODO podcast video is only working for newer android versions
view.animate().x(xPosition).y(absoluteYPosition).setDuration(animationTime);
}
/*
int height = (int)(view.getHeight() * scaleFactor);
int width = (int)(view.getWidth() * scaleFactor);
view.setScaleX(oldScaleFactor);
view.setScaleY(oldScaleFactor);
view.getLayoutParams().height = height;
view.getLayoutParams().width = width;
*/
}
private float dipToPx(float dip) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, getResources().getDisplayMetrics());
}
@ -591,9 +301,13 @@ public class PodcastFragmentActivity extends AppCompatActivity implements IPlayP
intent.putExtra(PodcastPlaybackService.MEDIA_ITEM, mediaItem);
startService(intent);
/*
if(!mMediaBrowser.isConnected()) {
mMediaBrowser.connect();
}
*/
//bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@ -605,76 +319,26 @@ public class PodcastFragmentActivity extends AppCompatActivity implements IPlayP
File file = new File(PodcastDownloadService.getUrlToPodcastFile(this, podcastItem.link, false));
if(file.exists()) {
podcastItem.link = file.getAbsolutePath();
openMediaItem(podcastItem);
} else if(!podcastItem.offlineCached) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this)
.setNegativeButton("Abort", null)
.setNeutralButton("Download", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
PodcastDownloadService.startPodcastDownload(PodcastFragmentActivity.this, podcastItem);
Toast.makeText(PodcastFragmentActivity.this, "Starting download of podcast. Please wait..", Toast.LENGTH_SHORT).show();
}
.setNeutralButton("Download", (dialogInterface, i) -> {
PodcastDownloadService.startPodcastDownload(PodcastFragmentActivity.this, podcastItem);
Toast.makeText(PodcastFragmentActivity.this, "Starting download of podcast. Please wait..", Toast.LENGTH_SHORT).show();
})
.setTitle("Podcast")
.setMessage("Choose if you want to download or stream the selected podcast");
alertDialog.setPositiveButton("Stream", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
openMediaItem(podcastItem);
}
});
alertDialog.setPositiveButton("Stream", (dialogInterface, i) -> openMediaItem(podcastItem));
alertDialog.show();
}
}
@Override
public void pausePodcast() {
MediaControllerCompat.getMediaController(PodcastFragmentActivity.this).getTransportControls().pause();
}
public void getCurrentPlaybackSpeed(final OnPlaybackSpeedCallback callback) {
MediaControllerCompat.getMediaController(PodcastFragmentActivity.this)
.sendCommand(PLAYBACK_SPEED_FLOAT,
null,
new ResultReceiver(new Handler()) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
callback.currentPlaybackReceived(resultData.getFloat(PLAYBACK_SPEED_FLOAT));
}
});
}
public boolean getCurrentPlayingPodcast(final OnCurrentPlayingPodcastCallback callback) {
if(mMediaBrowser != null && mMediaBrowser.isConnected()) {
MediaControllerCompat.getMediaController(PodcastFragmentActivity.this)
.sendCommand(CURRENT_PODCAST_ITEM_MEDIA_ITEM,
null,
new ResultReceiver(new Handler()) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
callback.currentPlayingPodcastReceived((MediaItem) resultData.getSerializable(CURRENT_PODCAST_ITEM_MEDIA_ITEM));
}
});
return true;
} else {
return false;
}
}
public interface OnPlaybackSpeedCallback {
void currentPlaybackReceived(float playbackSpeed);
}
public interface OnCurrentPlayingPodcastCallback {
void currentPlayingPodcastReceived(MediaItem mediaItem);
}
}

View file

@ -56,7 +56,8 @@ public class DatabaseConnectionOrm {
};
private final String TAG = getClass().getCanonicalName();
private static final String[] VIDEO_FORMATS = { "youtube", "video/mp4" };
//private static final String[] VIDEO_FORMATS = { "youtube", "video/mp4" };
private static final String[] VIDEO_FORMATS = { "video/mp4" };
public enum SORT_DIRECTION { asc, desc }
private DaoSession daoSession;
@ -472,14 +473,15 @@ public class DatabaseConnectionOrm {
public static PodcastItem ParsePodcastItemFromRssItem(Context context, RssItem rssItem) {
PodcastItem podcastItem = new PodcastItem();
Feed feed = rssItem.getFeed();
podcastItem.author = feed.getFeedTitle();// rssItem.getAuthor();
podcastItem.itemId = rssItem.getId();
podcastItem.title = rssItem.getTitle();
podcastItem.link = rssItem.getEnclosureLink();
podcastItem.mimeType = rssItem.getEnclosureMime();
podcastItem.favIcon = rssItem.getFeed().getFaviconUrl();
podcastItem.favIcon = feed.getFaviconUrl();
boolean isVideo = Arrays.asList(DatabaseConnectionOrm.VIDEO_FORMATS).contains(podcastItem.mimeType);
podcastItem.isVideoPodcast = isVideo;
podcastItem.isVideoPodcast = Arrays.asList(DatabaseConnectionOrm.VIDEO_FORMATS).contains(podcastItem.mimeType);
File file = new File(PodcastDownloadService.getUrlToPodcastFile(context, podcastItem.link, false));
podcastItem.offlineCached = file.exists();

View file

@ -0,0 +1,4 @@
package de.luhmer.owncloudnewsreader.events.podcast;
public class CollapsePodcastView {
}

View file

@ -0,0 +1,4 @@
package de.luhmer.owncloudnewsreader.events.podcast;
public class ExpandPodcastView {
}

View file

@ -1,5 +1,7 @@
package de.luhmer.owncloudnewsreader.events.podcast;
import android.support.v4.media.session.PlaybackStateCompat;
import de.luhmer.owncloudnewsreader.services.podcast.PlaybackService;
public class UpdatePodcastStatusEvent {
@ -8,10 +10,10 @@ public class UpdatePodcastStatusEvent {
private long max;
private String author;
private String title;
private PlaybackService.Status status;
private @PlaybackStateCompat.State int status;
private PlaybackService.VideoType videoType;
private long rssItemId;
private float speed = -1;
private float speed;
public long getRssItemId() {
return rssItemId;
@ -25,12 +27,12 @@ public class UpdatePodcastStatusEvent {
return title;
}
public PlaybackService.Status getStatus() {
public @PlaybackStateCompat.State int getStatus() {
return status;
}
public boolean isPlaying() {
return status == PlaybackService.Status.PLAYING;
return status == PlaybackStateCompat.STATE_PLAYING;
}
public long getCurrent() {
@ -47,7 +49,7 @@ public class UpdatePodcastStatusEvent {
public boolean isVideoFile() { return !(videoType == PlaybackService.VideoType.None); }
public UpdatePodcastStatusEvent(long current, long max, PlaybackService.Status status, String author, String title, PlaybackService.VideoType videoType, long rssItemId, float speed) {
public UpdatePodcastStatusEvent(long current, long max, @PlaybackStateCompat.State int status, String author, String title, PlaybackService.VideoType videoType, long rssItemId, float speed) {
this.current = current;
this.max = max;
this.status = status;

View file

@ -2,6 +2,10 @@ package de.luhmer.owncloudnewsreader.events.podcast;
public class WindPodcast {
public double toPositionInPercent;
public double milliSeconds;
public WindPodcast(double milliSeconds) {
this.milliSeconds = milliSeconds;
}
}

View file

@ -187,6 +187,8 @@ public class NextcloudNotificationManager {
*/
//.setUsesChronometer(true)
.setContentTitle(description.getTitle())
.setContentText(description.getSubtitle())
.setSubText(description.getDescription())
.setSmallIcon(R.drawable.ic_notification)
//.setContentText(description.getSubtitle())
//.setContentText(mediaMetadata.getText(MediaMetadataCompat.METADATA_KEY_ARTIST))
@ -195,15 +197,18 @@ public class NextcloudNotificationManager {
.setLargeIcon(bitmapIcon)
.setContentIntent(controller.getSessionActivity())
.setDeleteIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(context, PlaybackStateCompat.ACTION_STOP))
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOnlyAlertOnce(true);
boolean isPlaying = controller.getPlaybackState().getState() == PlaybackStateCompat.STATE_PLAYING;
builder.addAction(getPlayPauseAction(context, isPlaying));
// Make the transport controls visible on the lockscreen
builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
builder.setStyle(new MediaStyle()
//.setShowActionsInCompactView(0) // show only play/pause in compact view
.setMediaSession(mediaSession.getSessionToken())
.setShowActionsInCompactView(0)
.setShowCancelButton(true)
.setCancelButtonIntent(
MediaButtonReceiver.buildMediaButtonPendingIntent(

View file

@ -5,6 +5,7 @@ import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
@ -26,16 +27,18 @@ import org.greenrobot.eventbus.Subscribe;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import de.luhmer.owncloudnewsreader.NewsReaderListActivity;
import de.luhmer.owncloudnewsreader.R;
import de.luhmer.owncloudnewsreader.events.podcast.NewPodcastPlaybackListener;
import de.luhmer.owncloudnewsreader.events.podcast.PodcastCompletedEvent;
import de.luhmer.owncloudnewsreader.events.podcast.RegisterVideoOutput;
import de.luhmer.owncloudnewsreader.events.podcast.RegisterYoutubeOutput;
import de.luhmer.owncloudnewsreader.events.podcast.SpeedPodcast;
import de.luhmer.owncloudnewsreader.events.podcast.TogglePlayerStateEvent;
import de.luhmer.owncloudnewsreader.events.podcast.UpdatePodcastStatusEvent;
import de.luhmer.owncloudnewsreader.events.podcast.WindPodcast;
import de.luhmer.owncloudnewsreader.model.MediaItem;
import de.luhmer.owncloudnewsreader.model.PodcastItem;
@ -43,7 +46,6 @@ import de.luhmer.owncloudnewsreader.model.TTSItem;
import de.luhmer.owncloudnewsreader.services.podcast.MediaPlayerPlaybackService;
import de.luhmer.owncloudnewsreader.services.podcast.PlaybackService;
import de.luhmer.owncloudnewsreader.services.podcast.TTSPlaybackService;
import de.luhmer.owncloudnewsreader.services.podcast.YoutubePlaybackService;
import de.luhmer.owncloudnewsreader.view.PodcastNotification;
import static android.view.KeyEvent.KEYCODE_MEDIA_STOP;
@ -55,7 +57,13 @@ public class PodcastPlaybackService extends MediaBrowserServiceCompat {
private static final String TAG = "PodcastPlaybackService";
public static final String PLAYBACK_SPEED_FLOAT = "PLAYBACK_SPEED";
public static final String CURRENT_PODCAST_ITEM_MEDIA_ITEM= "CURRENT_PODCAST_ITEM";
public static final String CURRENT_PODCAST_ITEM_MEDIA_ITEM = "CURRENT_PODCAST_ITEM";
public static final String CURRENT_PODCAST_MEDIA_TYPE = "CURRENT_PODCAST_MEDIA_TYPE";
private static final long PROGRESS_UPDATE_INTERNAL = 1000;
private static final long PROGRESS_UPDATE_INITIAL_INTERVAL = 100;
private PodcastNotification podcastNotification;
private EventBus eventBus;
@ -68,6 +76,57 @@ public class PodcastPlaybackService extends MediaBrowserServiceCompat {
private float currentPlaybackSpeed = 1;
/**
* Android Auto
*/
/** Bundle extra indicating that a song is explicit. */
String EXTRA_IS_EXPLICIT = "android.media.IS_EXPLICIT";
/**
* Bundle extra indicating that a media item is available offline.
* Same as MediaDescriptionCompat.EXTRA_DOWNLOAD_STATUS.
*/
String EXTRA_IS_DOWNLOADED = "android.media.extra.DOWNLOAD_STATUS";
/**
* Bundle extra value indicating that an item should show the corresponding
* metadata.
*/
long EXTRA_METADATA_ENABLED_VALUE = 1;
/**
* Bundle extra indicating the played state of long-form content (such as podcast
* episodes or audiobooks).
*/
String EXTRA_PLAY_COMPLETION_STATE = "android.media.extra.PLAYBACK_STATUS";
/**
* Value for EXTRA_PLAY_COMPLETION_STATE that indicates the media item has
* not been played at all.
*/
int STATUS_NOT_PLAYED = 0;
/**
* Value for EXTRA_PLAY_COMPLETION_STATE that indicates the media item has
* been partially played (i.e. the current position is somewhere in the middle).
*/
int STATUS_PARTIALLY_PLAYED = 1;
/**
* Value for EXTRA_PLAY_COMPLETION_STATE that indicates the media item has
* been completed.
*/
int STATUS_FULLY_PLAYED = 2;
public static final int delay = 500; //In milliseconds
private final ScheduledExecutorService mExecutorService =
Executors.newSingleThreadScheduledExecutor();
private ScheduledFuture<?> mScheduleFuture;
public MediaItem getCurrentlyPlayingPodcast() {
if(mPlaybackService != null) {
return mPlaybackService.getMediaItem();
@ -90,20 +149,20 @@ public class PodcastPlaybackService extends MediaBrowserServiceCompat {
@Override
public void onLoadChildren(@NonNull String s, @NonNull Result<List<MediaBrowserCompat.MediaItem>> result) {
Log.d(TAG, "onLoadChildren() called with: s = [" + s + "], result = [" + result + "]");
result.sendResult(new ArrayList<MediaBrowserCompat.MediaItem>());
result.sendResult(new ArrayList<>());
}
@Override
public boolean onUnbind(Intent intent) {
Log.d(TAG, "onUnbind() called with: intent = [" + intent + "]");
if (!isActive()) {
Log.v(TAG, "Stopping PodcastPlaybackService because of inactivity");
stopSelf();
}
if(podcastNotification != null) {
podcastNotification.unbind();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && mSession != null) {
mSession.release();
}
}
return super.onUnbind(intent);
}
@ -125,9 +184,6 @@ public class PodcastPlaybackService extends MediaBrowserServiceCompat {
eventBus.register(this);
//eventBus.post(new PodcastPlaybackServiceStarted());
mHandler.postDelayed(mUpdateTimeTask, 0);
setSessionToken(mSession.getSessionToken());
Intent intent = new Intent(this, NewsReaderListActivity.class);
@ -153,7 +209,7 @@ public class PodcastPlaybackService extends MediaBrowserServiceCompat {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
mHandler.removeCallbacks(mUpdateTimeTask);
mExecutorService.shutdown();
podcastNotification.cancel();
super.onDestroy();
@ -169,62 +225,109 @@ public class PodcastPlaybackService extends MediaBrowserServiceCompat {
mPlaybackService.destroy();
mPlaybackService = null;
}
mHandler.removeCallbacks(mUpdateTimeTask);
stopProgressUpdates();
if(intent.hasExtra(MEDIA_ITEM)) {
MediaItem mediaItem = (MediaItem) intent.getSerializableExtra(MEDIA_ITEM);
if (mediaItem instanceof PodcastItem) {
if (((PodcastItem) mediaItem).isYoutubeVideo()) {
mPlaybackService = new YoutubePlaybackService(this, podcastStatusListener, mediaItem);
} else {
//if (((PodcastItem) mediaItem).isYoutubeVideo()) {
// mPlaybackService = new YoutubePlaybackService(this, podcastStatusListener, mediaItem);
//} else {
mPlaybackService = new MediaPlayerPlaybackService(this, podcastStatusListener, mediaItem);
}
//}
} else if (mediaItem instanceof TTSItem) {
mPlaybackService = new TTSPlaybackService(this, podcastStatusListener, mediaItem);
}
podcastNotification.podcastChanged();
sendMediaStatus();
updateMetadata(mediaItem);
// Update notification after setting metadata (notification uses metadata information)
podcastNotification.createPodcastNotification();
mPlaybackService.playbackSpeedChanged(currentPlaybackSpeed);
startProgressUpdates();
requestAudioFocus();
}
}
return super.onStartCommand(intent, flags, startId);
}
private void updateMetadata(MediaItem mediaItem) {
if(mediaItem == null) {
mediaItem = new PodcastItem(-1, "", "", "", "", false, null, false);
}
int totalDuration = 0;
if(mPlaybackService != null) {
totalDuration = mPlaybackService.getTotalDuration();
}
mSession.setMetadata(new MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, mediaItem.author)
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, mediaItem.title)
//.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_SUBTITLE, mediaItem.author) // Android Auto
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, mediaItem.favIcon)
.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, String.valueOf(mediaItem.itemId))
.putString(CURRENT_PODCAST_MEDIA_TYPE, getCurrentlyPlayedMediaType().toString())
.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, totalDuration)
//.putLong(EXTRA_IS_EXPLICIT, EXTRA_METADATA_ENABLED_VALUE) // Android Auto
//.putLong(EXTRA_IS_DOWNLOADED, EXTRA_METADATA_ENABLED_VALUE) // Android Auto
.build());
}
/*
private Long getVideoWidth() {
if(mPlaybackService instanceof MediaPlayerPlaybackService) {
return ((MediaPlayerPlaybackService)mPlaybackService).getVideoWidth();
}
return null;
}
*/
private PlaybackService.PodcastStatusListener podcastStatusListener = new PlaybackService.PodcastStatusListener() {
@Override
public void podcastStatusUpdated() {
sendMediaStatus();
syncMediaAndPlaybackStatus();
if(mPlaybackService != null) {
updateMetadata(mPlaybackService.getMediaItem());
}
}
@Override
public void podcastCompleted() {
Log.d(TAG, "Podcast completed, cleaning up");
mHandler.removeCallbacks(mUpdateTimeTask);
podcastNotification.cancel();
mPlaybackService.destroy();
mPlaybackService = null;
endCurrentMediaPlayback();
EventBus.getDefault().post(new PodcastCompletedEvent());
}
};
public static final int delay = 500; //In milliseconds
private void endCurrentMediaPlayback() {
Log.d(TAG, "endCurrentMediaPlayback() called");
stopProgressUpdates();
// Set metadata
updateMetadata(null);
/**
* Background Runnable thread
* */
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
sendMediaStatus();
mHandler.postDelayed(this, delay);
if(mPlaybackService != null) {
mPlaybackService.destroy();
mPlaybackService = null;
}
};
syncMediaAndPlaybackStatus();
Log.d(TAG, "cancel notification");
podcastNotification.cancel();
abandonAudioFocus();
}
@Subscribe
public void onEvent(TogglePlayerStateEvent event) {
@ -247,13 +350,17 @@ public class PodcastPlaybackService extends MediaBrowserServiceCompat {
}
private boolean isPlaying() {
return (mPlaybackService != null && mPlaybackService.getStatus() == PlaybackService.Status.PLAYING);
return (mPlaybackService != null && mPlaybackService.getStatus() == PlaybackStateCompat.STATE_PLAYING);
}
@Subscribe
public void onEvent(WindPodcast event) {
if(mPlaybackService != null) {
mPlaybackService.seekTo(event.toPositionInPercent);
int seekTo = (int) (mPlaybackService.getCurrentPosition() + event.milliSeconds);
if(seekTo < 0) {
seekTo = 0;
}
mPlaybackService.seekTo(seekTo);
}
}
@ -264,20 +371,9 @@ public class PodcastPlaybackService extends MediaBrowserServiceCompat {
}
}
@Subscribe
public void onEvent(RegisterYoutubeOutput videoOutput) {
if(mPlaybackService != null && mPlaybackService instanceof YoutubePlaybackService) {
if(videoOutput.youTubePlayer == null) {
mPlaybackService.destroy();
} else {
((YoutubePlaybackService) mPlaybackService).setYoutubePlayer(videoOutput.youTubePlayer, videoOutput.wasRestored);
}
}
}
@Subscribe
public void onEvent(NewPodcastPlaybackListener newListener) {
sendMediaStatus();
syncMediaAndPlaybackStatus();
}
@Subscribe
@ -291,20 +387,73 @@ public class PodcastPlaybackService extends MediaBrowserServiceCompat {
public void play() {
if(mPlaybackService != null) {
// Start playback
mPlaybackService.play();
}
startProgressUpdates();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 0);
requestAudioFocus();
}
}
public void pause() {
if(mPlaybackService != null) {
mPlaybackService.pause();
}
stopProgressUpdates();
mHandler.removeCallbacks(mUpdateTimeTask);
sendMediaStatus();
abandonAudioFocus();
}
private void requestAudioFocus() {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
int result = audioManager.requestAudioFocus(
audioFocusChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
Log.d(TAG, "AUDIOFOCUS_REQUEST_GRANTED");
}
}
private void abandonAudioFocus() {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// Abandon audio focus when playback complete
audioManager.abandonAudioFocus(audioFocusChangeListener);
}
private AudioManager.OnAudioFocusChangeListener audioFocusChangeListener = focusChange -> {
if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
// Permanent loss of audio focus
// Pause playback immediately
mSession.getController().getTransportControls().pause();
}
else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
// Pause playback
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
// Lower the volume, keep playing
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
// Your app has been granted audio focus again
// Raise volume to normal, restart playback if necessary
}
};
private void startProgressUpdates() {
mScheduleFuture = mExecutorService.scheduleAtFixedRate(
() -> mHandler.post(PodcastPlaybackService.this::syncMediaAndPlaybackStatus), PROGRESS_UPDATE_INITIAL_INTERVAL,
PROGRESS_UPDATE_INTERNAL, TimeUnit.MILLISECONDS);
}
private void stopProgressUpdates() {
if (mScheduleFuture != null) {
mScheduleFuture.cancel(false);
}
syncMediaAndPlaybackStatus(); // Send one last update
}
@ -312,22 +461,22 @@ public class PodcastPlaybackService extends MediaBrowserServiceCompat {
return currentPlaybackSpeed;
}
public void sendMediaStatus() {
UpdatePodcastStatusEvent audioPodcastEvent;
public void syncMediaAndPlaybackStatus() {
/*
if(mPlaybackService == null) {
audioPodcastEvent = new UpdatePodcastStatusEvent(0, 0, PlaybackService.Status.NOT_INITIALIZED, "", "", PlaybackService.VideoType.None, -1, -1);
} else {
audioPodcastEvent = new UpdatePodcastStatusEvent(
mPlaybackService.getCurrentDuration(),
mPlaybackService.getCurrentPosition(),
mPlaybackService.getTotalDuration(),
mPlaybackService.getStatus(),
mPlaybackService.getMediaItem().link,
mPlaybackService.getMediaItem().title,
"NOT SUPPORTED ANYMORE!!!",
mPlaybackService.getVideoType(),
mPlaybackService.getMediaItem().itemId,
getPlaybackSpeed());
}
eventBus.post(audioPodcastEvent);
if(audioPodcastEvent.isPlaying()) {
@ -335,10 +484,58 @@ public class PodcastPlaybackService extends MediaBrowserServiceCompat {
} else {
stopForeground(false);
}
*/
@PlaybackStateCompat.State int playbackState;
int currentPosition = 0;
int totalDuration = 0;
if(mPlaybackService == null || mPlaybackService.getMediaItem().itemId == -1) {
// When podcast is not initialized or playback is finished
playbackState = PlaybackStateCompat.STATE_NONE;
mSession.setPlaybackState(new PlaybackStateCompat.Builder()
.setState(playbackState, currentPosition, 1.0f)
.setActions(buildPlaybackActions(playbackState, false))
.build());
stopForeground(false);
} else {
currentPosition = mPlaybackService.getCurrentPosition();
totalDuration = mPlaybackService.getTotalDuration();
playbackState = mPlaybackService.getStatus();
if (playbackState== PlaybackStateCompat.STATE_PLAYING) {
startForeground(PodcastNotification.NOTIFICATION_ID, podcastNotification.getNotification());
} else {
stopForeground(false);
}
mSession.setPlaybackState(new PlaybackStateCompat.Builder()
.setState(playbackState, currentPosition, 1.0f)
.setActions(buildPlaybackActions(playbackState, true))
.build());
}
if(playbackState == PlaybackStateCompat.STATE_PLAYING) {
mSession.setActive(true);
} else {
mSession.setActive(false);
}
podcastNotification.updateStateOfNotification(playbackState, currentPosition, totalDuration);
}
private long buildPlaybackActions(int playbackState, boolean mediaLoaded) {
long actions = playbackState == PlaybackStateCompat.STATE_PLAYING ? PlaybackStateCompat.ACTION_PAUSE : PlaybackStateCompat.ACTION_PLAY;
actions |= PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS |
PlaybackStateCompat.ACTION_SKIP_TO_NEXT;
//PlaybackStateCompat.ACTION_STOP;
//public class PodcastPlaybackServiceStarted { }
if(mediaLoaded) {
actions |= PlaybackStateCompat.ACTION_SEEK_TO;
}
return actions;
}
PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
@ -346,11 +543,14 @@ public class PodcastPlaybackService extends MediaBrowserServiceCompat {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//Incoming call: Pause music
pause();
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
}
/*
else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not in call: Play music
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
}
*/
super.onCallStateChanged(state, incomingNumber);
}
};
@ -359,12 +559,14 @@ public class PodcastPlaybackService extends MediaBrowserServiceCompat {
private final class MediaSessionCallback extends MediaSessionCompat.Callback {
@Override
public void onPlay() {
EventBus.getDefault().post(new TogglePlayerStateEvent());
Log.d(TAG, "onPlay() called");
play();
}
@Override
public void onPause() {
EventBus.getDefault().post(new TogglePlayerStateEvent());
Log.d(TAG, "onPause() called");
pause();
}
@Override
@ -375,12 +577,34 @@ public class PodcastPlaybackService extends MediaBrowserServiceCompat {
cb.send(0, b);
} else if(command.equals(CURRENT_PODCAST_ITEM_MEDIA_ITEM)) {
Bundle b = new Bundle();
b.putSerializable(CURRENT_PODCAST_ITEM_MEDIA_ITEM, mPlaybackService.getMediaItem());
if(mPlaybackService != null) {
b.putSerializable(CURRENT_PODCAST_ITEM_MEDIA_ITEM, mPlaybackService.getMediaItem());
} else {
b.putSerializable(CURRENT_PODCAST_ITEM_MEDIA_ITEM, null);
}
cb.send(0, b);
}
super.onCommand(command, extras, cb);
}
@Override
public void onSeekTo(long pos) {
Log.d(TAG, "onSeekTo() called with: pos = [" + pos + "]");
super.onSeekTo(pos);
}
@Override
public void onSkipToNext() {
Log.d(TAG, "onSkipToNext() called");
super.onSkipToNext();
}
@Override
public void onSkipToPrevious() {
Log.d(TAG, "onSkipToPrevious() called");
super.onSkipToPrevious();
}
@Override
public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
Log.d(TAG, mediaButtonEvent.getAction());
@ -392,6 +616,7 @@ public class PodcastPlaybackService extends MediaBrowserServiceCompat {
// Stop requested (e.g. notification was swiped away)
if(keyEvent.getKeyCode() == KEYCODE_MEDIA_STOP) {
pause();
endCurrentMediaPlayback();
stopSelf();
/*
boolean isPlaying = mSession.getController().getPlaybackState().getState() == PlaybackStateCompat.STATE_PLAYING;
@ -406,6 +631,7 @@ public class PodcastPlaybackService extends MediaBrowserServiceCompat {
}
private void initMediaSessions() {
//String packageName = PodcastNotificationToggle.class.getPackage().getName();
//ComponentName receiver = new ComponentName(packageName, PodcastNotificationToggle.class.getName());
ComponentName mediaButtonReceiver = new ComponentName(this, MediaButtonReceiver.class);
@ -413,8 +639,8 @@ public class PodcastPlaybackService extends MediaBrowserServiceCompat {
mSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
mSession.setPlaybackState(new PlaybackStateCompat.Builder()
.setState(PlaybackStateCompat.STATE_PAUSED, 0, 0)
.setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE).build());
.setState(PlaybackStateCompat.STATE_NONE, 0, 0)
.setActions(buildPlaybackActions(PlaybackStateCompat.STATE_PAUSED, false)).build());
mSession.setCallback(new MediaSessionCallback());
@ -424,21 +650,14 @@ public class PodcastPlaybackService extends MediaBrowserServiceCompat {
//mSession.setMediaButtonReceiver(pendingIntent);
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.requestAudioFocus(new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
// Ignore
}
}, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
updateMetadata(null);
}
//MediaControllerCompat controller = mSession.getController();
//mSession.setActive(true);
mSession.setMetadata(new MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, "")
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, "")
.build());
private PlaybackService.VideoType getCurrentlyPlayedMediaType() {
if(mPlaybackService != null) {
return mPlaybackService.getVideoType();
} else {
return PlaybackService.VideoType.None;
}
}
}

View file

@ -3,6 +3,7 @@ package de.luhmer.owncloudnewsreader.services.podcast;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Build;
import android.support.v4.media.session.PlaybackStateCompat;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
@ -21,46 +22,41 @@ import de.luhmer.owncloudnewsreader.model.PodcastItem;
public class MediaPlayerPlaybackService extends PlaybackService {
private static final String TAG = MediaPlayerPlaybackService.class.getCanonicalName();
private MediaPlayer mMediaPlayer;
private View parentResizableView;
//private View parentView;
public MediaPlayerPlaybackService(final Context context, PodcastStatusListener podcastStatusListener, MediaItem mediaItem) {
super(podcastStatusListener, mediaItem);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i2) {
setStatus(Status.FAILED);
Toast.makeText(context, "Failed to open podcast", Toast.LENGTH_LONG).show();
return false;
}
//mMediaPlayer.setOnVideoSizeChangedListener((mp, width, height) -> configureVideo(width, height));
mMediaPlayer.setOnErrorListener((mediaPlayer, i, i2) -> {
setStatus(PlaybackStateCompat.STATE_ERROR);
Toast.makeText(context, "Failed to open podcast", Toast.LENGTH_LONG).show();
return false;
});
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
setStatus(Status.PAUSED);
play();
}
mMediaPlayer.setOnPreparedListener(mediaPlayer -> {
podcastStatusListener.podcastStatusUpdated();
setStatus(PlaybackStateCompat.STATE_PAUSED);
play();
});
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
pause();//Send the over signal
podcastCompleted();
}
mMediaPlayer.setOnCompletionListener(mediaPlayer -> {
pause();//Send the over signal
podcastCompleted();
});
try {
setStatus(Status.PREPARING);
setStatus(PlaybackStateCompat.STATE_CONNECTING);
mMediaPlayer.setDataSource(((PodcastItem) mediaItem).link);
mMediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
setStatus(Status.FAILED);
setStatus(PlaybackStateCompat.STATE_ERROR);
}
}
@ -78,14 +74,14 @@ public class MediaPlayerPlaybackService extends PlaybackService {
if (progress >= 1) {
mMediaPlayer.seekTo(0);
}
setStatus(Status.PLAYING);
setStatus(PlaybackStateCompat.STATE_PLAYING);
} catch (Exception ex) {
ex.printStackTrace();
Log.e(TAG, "Error while playing", ex);
}
mMediaPlayer.start();
populateVideo();
//populateVideo();
}
@Override
@ -93,7 +89,7 @@ public class MediaPlayerPlaybackService extends PlaybackService {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
}
setStatus(Status.PAUSED);
setStatus(PlaybackStateCompat.STATE_PAUSED);
}
@Override
@ -103,16 +99,15 @@ public class MediaPlayerPlaybackService extends PlaybackService {
}
}
@Override
public void seekTo(double percent) {
double totalDuration = mMediaPlayer.getDuration();
int position = (int) ((totalDuration / 100d) * percent);
public void seekTo(int position) {
//double totalDuration = mMediaPlayer.getDuration();
//int position = (int) ((totalDuration / 100d) * percent);
mMediaPlayer.seekTo(position);
}
@Override
public int getCurrentDuration() {
public int getCurrentPosition() {
if (mMediaPlayer != null && isMediaLoaded()) {
return mMediaPlayer.getCurrentPosition();
}
@ -133,6 +128,7 @@ public class MediaPlayerPlaybackService extends PlaybackService {
}
/*
private void populateVideo() {
double videoHeightRel = (double) mSurfaceWidth / (double) mMediaPlayer.getVideoWidth();
int videoHeight = (int) (mMediaPlayer.getVideoHeight() * videoHeightRel);
@ -140,9 +136,13 @@ public class MediaPlayerPlaybackService extends PlaybackService {
if (mSurfaceWidth != 0 && videoHeight != 0 && mSurfaceHolder != null) {
//mSurfaceHolder.setFixedSize(mSurfaceWidth, videoHeight);
parentResizableView.getLayoutParams().height = videoHeight;
parentResizableView.setLayoutParams(parentResizableView.getLayoutParams());
parentView.getLayoutParams().height = videoHeight;
parentView.setLayoutParams(parentView.getLayoutParams());
}
}*/
public long getVideoWidth() {
return mMediaPlayer.getVideoWidth();
}
public void setVideoView(SurfaceView surfaceView, View parentResizableView) {
@ -153,37 +153,32 @@ public class MediaPlayerPlaybackService extends PlaybackService {
mMediaPlayer.setScreenOnWhilePlaying(false);
} else {
if (surfaceView.getHolder() != mSurfaceHolder) {
this.parentResizableView = parentResizableView;
//this.parentView = parentResizableView;
surfaceView.getHolder().addCallback(mSHCallback);
//videoOutput.surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); //holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
populateVideo();
//Log.v(TAG, "Enable Screen output!");
}
}
}
private int mSurfaceWidth;
private int mSurfaceHeight;
//private int mSurfaceWidth;
//private int mSurfaceHeight;
private SurfaceHolder mSurfaceHolder;
SurfaceHolder.Callback mSHCallback = new SurfaceHolder.Callback()
{
public void surfaceChanged(SurfaceHolder holder, int format, int surfaceWidth, int surfaceHeight)
{
mSurfaceWidth = surfaceWidth;
mSurfaceHeight = surfaceHeight;
private SurfaceHolder.Callback mSHCallback = new SurfaceHolder.Callback() {
public void surfaceChanged(SurfaceHolder holder, int format, int surfaceWidth, int surfaceHeight) {
Log.v(TAG, "surfaceChanged() called with: holder = [" + holder + "], format = [" + format + "], surfaceWidth = [" + surfaceWidth + "], surfaceHeight = [" + surfaceHeight + "]");
//mSurfaceWidth = surfaceWidth;
//mSurfaceHeight = surfaceHeight;
//populateVideo();
}
public void surfaceCreated(SurfaceHolder holder)
{
public void surfaceCreated(SurfaceHolder holder) {
Log.v(TAG, "surfaceCreated() called with: holder = [" + holder + "]");
mSurfaceHolder = holder;
mMediaPlayer.setDisplay(mSurfaceHolder); //TODO required
mMediaPlayer.setScreenOnWhilePlaying(true); //TODO required
Log.d(TAG, "surfaceCreated");
mMediaPlayer.setDisplay(mSurfaceHolder);
mMediaPlayer.setScreenOnWhilePlaying(true);
}
public void surfaceDestroyed(SurfaceHolder holder)

View file

@ -1,5 +1,7 @@
package de.luhmer.owncloudnewsreader.services.podcast;
import android.support.v4.media.session.PlaybackStateCompat;
import de.luhmer.owncloudnewsreader.model.MediaItem;
/**
@ -13,10 +15,9 @@ public abstract class PlaybackService {
void podcastCompleted();
}
public enum Status { NOT_INITIALIZED, FAILED, PREPARING, PLAYING, PAUSED, STOPPED };
public enum VideoType { None, Video, VideoType, YouTube }
private Status mStatus = Status.NOT_INITIALIZED;
private @PlaybackStateCompat.State int mStatus = PlaybackStateCompat.STATE_NONE;
private PodcastStatusListener podcastStatusListener;
private MediaItem mediaItem;
@ -31,8 +32,8 @@ public abstract class PlaybackService {
public abstract void playbackSpeedChanged(float currentPlaybackSpeed);
public void seekTo(double percent) { }
public int getCurrentDuration() { return 0; }
public void seekTo(int position) { }
public int getCurrentPosition() { return 0; }
public int getTotalDuration() { return 0; }
public VideoType getVideoType() { return VideoType.None; }
@ -40,11 +41,11 @@ public abstract class PlaybackService {
return mediaItem;
}
public Status getStatus() {
public @PlaybackStateCompat.State int getStatus() {
return mStatus;
}
protected void setStatus(Status status) {
protected void setStatus(@PlaybackStateCompat.State int status) {
this.mStatus = status;
podcastStatusListener.podcastStatusUpdated();
}
@ -54,9 +55,8 @@ public abstract class PlaybackService {
}
public boolean isMediaLoaded() {
return getStatus() != Status.NOT_INITIALIZED
&& getStatus() != Status.PREPARING
&& getStatus() != Status.FAILED;
return getStatus() != PlaybackStateCompat.STATE_NONE
&& getStatus() != PlaybackStateCompat.STATE_CONNECTING
&& getStatus() != PlaybackStateCompat.STATE_ERROR;
}
}

View file

@ -3,6 +3,7 @@ package de.luhmer.owncloudnewsreader.services.podcast;
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.support.v4.media.session.PlaybackStateCompat;
import android.util.Log;
import java.util.HashMap;
@ -22,10 +23,9 @@ public class TTSPlaybackService extends PlaybackService implements TextToSpeech.
try {
ttsController = new TextToSpeech(context, this);
setStatus(Status.PREPARING);
if(ttsController == null) {
setStatus(PlaybackStateCompat.STATE_CONNECTING);
if(ttsController != null) {
ttsController.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onDone(String utteranceId) {
@ -35,9 +35,9 @@ public class TTSPlaybackService extends PlaybackService implements TextToSpeech.
@Override public void onStart(String utteranceId) {}
@Override public void onError(String utteranceId) {}
});
}
else
} else {
onInit(TextToSpeech.SUCCESS);
}
} catch (Exception e) {
e.printStackTrace();
}
@ -59,7 +59,7 @@ public class TTSPlaybackService extends PlaybackService implements TextToSpeech.
public void pause() {
if (ttsController.isSpeaking()) {
ttsController.stop();
setStatus(Status.PAUSED);
setStatus(PlaybackStateCompat.STATE_PAUSED);
}
}
@ -84,9 +84,9 @@ public class TTSPlaybackService extends PlaybackService implements TextToSpeech.
HashMap<String,String> ttsParams = new HashMap<>();
ttsParams.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"dummyId");
ttsController.speak(((TTSItem)getMediaItem()).text, TextToSpeech.QUEUE_FLUSH, ttsParams);
setStatus(Status.PLAYING);
setStatus(PlaybackStateCompat.STATE_PLAYING);
} else {
Log.e("TTS", "Initilization Failed!");
Log.e("TTS", "Initialization Failed!");
ttsController = null;
}
}

View file

@ -5,7 +5,10 @@ import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import android.support.v4.media.MediaDescriptionCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.util.Log;
@ -36,7 +39,7 @@ public class PodcastNotification {
private final String CHANNEL_ID = "Podcast Notification";
private MediaSessionCompat mSession;
private PlaybackService.Status lastStatus = PlaybackService.Status.NOT_INITIALIZED;
private @PlaybackStateCompat.State int lastStatus = PlaybackStateCompat.STATE_NONE;
public final static int NOTIFICATION_ID = 1111;
@ -44,41 +47,22 @@ public class PodcastNotification {
this.mContext = context;
this.mSession = session;
this.notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
this.notificationBuilder = NextcloudNotificationManager.buildPodcastNotification(mContext, CHANNEL_ID, mSession);
EventBus.getDefault().register(this);
}
public void unbind() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && mSession != null) {
mSession.release();
}
//EventBus.getDefault().register(this);
}
@Subscribe
public void onEvent(UpdatePodcastStatusEvent podcast) {
public void updateStateOfNotification(@PlaybackStateCompat.State int status, long currentPosition, long totalDuration) {
if(mSession == null) {
Log.v(TAG, "Session null.. ignore UpdatePodcastStatusEvent");
return;
}
if (status != lastStatus) {
lastStatus = status;
if (podcast.getStatus() != lastStatus) {
lastStatus = podcast.getStatus();
/*
notificationBuilder.setContentTitle(podcast.getTitle());
notificationBuilder.mActions.clear();
notificationBuilder.addAction(
drawableId,
actionText,
PendingIntent.getBroadcast(mContext, 0, new Intent(mContext, PodcastNotificationToggle.class),
PendingIntent.FLAG_ONE_SHOT));
*/
/*
if(podcast.isPlaying()) {
//Prevent the Podcast Player from getting killed because of low memory
@ -100,53 +84,36 @@ public class PodcastNotification {
.build());
*/
mSession.setActive(true);
if (podcast.isPlaying()) {
mSession.setPlaybackState(new PlaybackStateCompat.Builder()
.setState(PlaybackStateCompat.STATE_PLAYING, podcast.getCurrent(), 1.0f)
.setActions(PlaybackStateCompat.ACTION_PAUSE).build());
} else {
mSession.setPlaybackState(new PlaybackStateCompat.Builder()
.setState(PlaybackStateCompat.STATE_PAUSED, podcast.getCurrent(), 0.0f)
.setActions(PlaybackStateCompat.ACTION_PLAY).build());
}
//mSession.setActive(podcast.isPlaying());
notificationBuilder = NextcloudNotificationManager.buildPodcastNotification(mContext, CHANNEL_ID, mSession);
//int drawableId = podcast.isPlaying() ? android.R.drawable.ic_media_pause : android.R.drawable.ic_media_play;
//String actionText = podcast.isPlaying() ? "Pause" : "Play";
//notificationBuilder.addAction(new NotificationCompat.Action(drawableId, actionText, intent));
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
int hours = (int)( podcast.getCurrent() / (1000*60*60));
int minutes = (int)(podcast.getCurrent() % (1000*60*60)) / (1000*60);
int seconds = (int) ((podcast.getCurrent() % (1000*60*60)) % (1000*60) / 1000);
int hours = (int) (currentPosition / (1000*60*60));
int minutes = (int) ((currentPosition % (1000*60*60)) / (1000*60));
int seconds = (int) ((currentPosition % (1000*60*60)) % (1000*60) / 1000);
minutes += hours * 60;
String fromText = (String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds));
hours = (int)( podcast.getMax() / (1000*60*60));
minutes = (int)(podcast.getMax() % (1000*60*60)) / (1000*60);
seconds = (int) ((podcast.getMax() % (1000*60*60)) % (1000*60) / 1000);
hours = (int) (totalDuration / (1000*60*60));
minutes = (int) ((totalDuration % (1000*60*60)) / (1000*60));
seconds = (int) ((totalDuration % (1000*60*60)) % (1000*60) / 1000);
minutes += hours * 60;
String toText = (String.format(Locale.getDefault(),"%02d:%02d", minutes, seconds));
double progressDouble = ((double)podcast.getCurrent() / (double)podcast.getMax()) * 100d;
double progressDouble = ((double)currentPosition / (double)totalDuration) * 100d;
int progress = ((int) progressDouble);
notificationBuilder
.setContentText(fromText + " - " + toText)
.setProgress(100, progress, podcast.getStatus() == PlaybackService.Status.PREPARING);
.setProgress(100, progress, status == PlaybackStateCompat.STATE_CONNECTING); // TODO IMPLEMENT THIS!!!!
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
@ -156,14 +123,17 @@ public class PodcastNotification {
if(notificationManager != null) {
notificationManager.cancel(NOTIFICATION_ID);
}
/*
if(mSession != null) {
mSession.setActive(false);
}
*/
}
public void podcastChanged() {
public void createPodcastNotification() {
/*
MediaItem podcastItem = ((PodcastPlaybackService)mContext).getCurrentlyPlayingPodcast();
*/
/*
String favIconUrl = podcastItem.favIcon;
DisplayImageOptions displayImageOptions = new DisplayImageOptions.Builder().
@ -173,13 +143,14 @@ public class PodcastNotification {
build();
*/
//TODO networkOnMainThreadExceptionHere!
//Bitmap bmpAlbumArt = ImageLoader.getInstance().loadImageSync(favIconUrl, displayImageOptions);
/*
mSession.setMetadata(new MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, podcastItem.author)
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, podcastItem.title)
.build());
*/
/*
mSession.setMetadata(new MediaMetadataCompat.Builder()