Skip to content

Commit

Permalink
Fix notifications to work with Android Oreo
Browse files Browse the repository at this point in the history
Whan the background service is launcher, it is launched on the foreground and a notification is always shown.
The service stays on while something is playing. It stops itself on a connection error, quitting Kodi or 5 seconds after stopping
Make the Pause Phone Calls preference dependent on the Show Notification preference, as we always need to show a notification when the service is running
  • Loading branch information
SyncedSynapse committed Dec 24, 2017
1 parent 250c1f0 commit 3077653
Show file tree
Hide file tree
Showing 6 changed files with 163 additions and 64 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.v4.content.ContextCompat;
Expand Down Expand Up @@ -51,6 +52,10 @@ public class ConnectionObserversManagerService extends Service
private HostConnectionObserver mHostConnectionObserver = null;

private List<HostConnectionObserver.PlayerEventsObserver> mConnectionObservers = new ArrayList<>();
private NotificationObserver mNotificationObserver;

private boolean somethingPlaying = false;
private Handler mStopHandler = new Handler();

@Override
public void onCreate() {
Expand All @@ -69,6 +74,7 @@ public int onStartCommand(Intent intent, int flags, int startId) {
if (mConnectionObservers.isEmpty()) {
LogUtils.LOGD(TAG, "No observers, stopping observer service.");
stopSelf();
return START_NOT_STICKY;
}

// Get the connection observer here, not on create to check if
Expand All @@ -81,6 +87,16 @@ public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}

// Create the observers we are managing
createObservers();
if (mConnectionObservers.isEmpty()) {
stopForeground(true);
stopSelf();
return START_NOT_STICKY;
}

startForeground(NotificationObserver.NOTIFICATION_ID, mNotificationObserver.getNothingPlayingNotification());

// If there's a change in hosts, unregister from the previous one
if (mHostConnectionObserver != null) {
mHostConnectionObserver.unregisterPlayerObserver(this);
Expand All @@ -97,14 +113,13 @@ public int onStartCommand(Intent intent, int flags, int startId) {
private void createObservers() {
mConnectionObservers = new ArrayList<>();

// Check whether we should show a notification
boolean showNotification = PreferenceManager
.getDefaultSharedPreferences(this)
.getBoolean(Settings.KEY_PREF_SHOW_NOTIFICATION,
Settings.DEFAULT_PREF_SHOW_NOTIFICATION);
if (showNotification) {
mConnectionObservers.add(new NotificationObserver(this));
}
// Always show a notification
// boolean showNotification = PreferenceManager
// .getDefaultSharedPreferences(this)
// .getBoolean(Settings.KEY_PREF_SHOW_NOTIFICATION,
// Settings.DEFAULT_PREF_SHOW_NOTIFICATION);
mNotificationObserver = new NotificationObserver(this);
mConnectionObservers.add(mNotificationObserver);

// Check whether we should react to phone state changes and wether
// we have permissions to do so
Expand Down Expand Up @@ -136,6 +151,7 @@ public void onTaskRemoved (Intent rootIntent) {
if (mHostConnectionObserver != null) {
mHostConnectionObserver.unregisterPlayerObserver(this);
}
stopForeground(true);
stopSelf();
}

Expand Down Expand Up @@ -165,6 +181,7 @@ public void playerOnPlay(PlayerType.GetActivePlayersReturnType getActivePlayerRe
for (HostConnectionObserver.PlayerEventsObserver observer : mConnectionObservers) {
observer.playerOnPlay(getActivePlayerResult, getPropertiesResult, getItemResult);
}
somethingPlaying = true;
}

public void playerOnPause(PlayerType.GetActivePlayersReturnType getActivePlayerResult,
Expand All @@ -173,50 +190,66 @@ public void playerOnPause(PlayerType.GetActivePlayersReturnType getActivePlayerR
for (HostConnectionObserver.PlayerEventsObserver observer : mConnectionObservers) {
observer.playerOnPause(getActivePlayerResult, getPropertiesResult, getItemResult);
}
somethingPlaying = true;
}

public void playerOnStop() {
for (HostConnectionObserver.PlayerEventsObserver observer : mConnectionObservers) {
observer.playerOnStop();
}

// Stop service
LogUtils.LOGD(TAG, "Player stopped");
// if (mHostConnectionObserver != null) {
// mHostConnectionObserver.unregisterPlayerObserver(this);
// }
// stopSelf();
somethingPlaying = false;

// Stop service if nothing starts in a couple of seconds
mStopHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (!somethingPlaying) {
LogUtils.LOGD(TAG, "Stopping service");
if (mHostConnectionObserver != null) {
mHostConnectionObserver.unregisterPlayerObserver(ConnectionObserversManagerService.this);
}
stopForeground(true);
stopSelf();
}
}
}, 5000);
}

public void playerNoResultsYet() {
for (HostConnectionObserver.PlayerEventsObserver observer : mConnectionObservers) {
observer.playerNoResultsYet();
}
somethingPlaying = false;
}

public void playerOnConnectionError(int errorCode, String description) {
for (HostConnectionObserver.PlayerEventsObserver observer : mConnectionObservers) {
observer.playerOnConnectionError(errorCode, description);
}
somethingPlaying = false;

// Stop service
LogUtils.LOGD(TAG, "Shutting down observer service - Connection error");
if (mHostConnectionObserver != null) {
mHostConnectionObserver.unregisterPlayerObserver(this);
}
stopForeground(true);
stopSelf();
}

public void systemOnQuit() {
for (HostConnectionObserver.PlayerEventsObserver observer : mConnectionObservers) {
observer.systemOnQuit();
}
somethingPlaying = false;

// Stop service
LogUtils.LOGD(TAG, "Shutting down observer service - System quit");
if (mHostConnectionObserver != null) {
mHostConnectionObserver.unregisterPlayerObserver(this);
}
stopForeground(true);
stopSelf();
}

Expand All @@ -233,6 +266,7 @@ public void observerOnStopObserving() {
}
// Called when the user changes host
LogUtils.LOGD(TAG, "Shutting down observer service - Stop observing");
stopForeground(true);
stopSelf();
}
}
91 changes: 74 additions & 17 deletions app/src/main/java/org/xbmc/kore/service/NotificationObserver.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,11 @@

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
Expand Down Expand Up @@ -52,11 +55,15 @@ public class NotificationObserver
implements HostConnectionObserver.PlayerEventsObserver {
public static final String TAG = LogUtils.makeLogTag(NotificationObserver.class);

private static final int NOTIFICATION_ID = 1;
public static final int NOTIFICATION_ID = 1;
public static final String NOTIFICATION_CHANNEL = "KORE";

private PendingIntent mRemoteStartPendingIntent;
private Service mService;

private Notification mNothingPlayingNotification;


public NotificationObserver(Service service) {
this.mService = service;

Expand All @@ -65,6 +72,12 @@ public NotificationObserver(Service service) {
stackBuilder.addParentStack(RemoteActivity.class);
stackBuilder.addNextIntent(new Intent(mService, RemoteActivity.class));
mRemoteStartPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

// Create the notification channel
if (Utils.isOreoOrLater()) {
buildNotificationChannel();
}
mNothingPlayingNotification = buildNothingPlayingNotification();
}

@Override
Expand All @@ -78,21 +91,21 @@ public void playerOnPropertyChanged(Player.NotificationsData notificationsData)
public void playerOnPlay(PlayerType.GetActivePlayersReturnType getActivePlayerResult,
PlayerType.PropertyValue getPropertiesResult,
ListType.ItemsAll getItemResult) {
buildNotification(getActivePlayerResult, getPropertiesResult, getItemResult);
notifyPlaying(getActivePlayerResult, getPropertiesResult, getItemResult);
}

public void playerOnPause(PlayerType.GetActivePlayersReturnType getActivePlayerResult,
PlayerType.PropertyValue getPropertiesResult,
ListType.ItemsAll getItemResult) {
buildNotification(getActivePlayerResult, getPropertiesResult, getItemResult);
notifyPlaying(getActivePlayerResult, getPropertiesResult, getItemResult);
}

public void playerOnStop() {
removeNotification();
notifyNothingPlaying();
}

public void playerNoResultsYet() {
removeNotification();
notifyNothingPlaying();
}

public void playerOnConnectionError(int errorCode, String description) {
Expand All @@ -111,13 +124,53 @@ public void observerOnStopObserving() {
removeNotification();
}

@TargetApi(Build.VERSION_CODES.O)
private void buildNotificationChannel() {

NotificationChannel channel =
new NotificationChannel(NOTIFICATION_CHANNEL,
mService.getString(R.string.app_name),
NotificationManager.IMPORTANCE_LOW);
channel.enableLights(false);
channel.enableVibration(false);
channel.setShowBadge(false);

NotificationManager notificationManager =
(NotificationManager) mService.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}

// Picasso target that will be used to load images
private static Target picassoTarget = null;

private Notification buildNothingPlayingNotification() {
int smallIcon = R.drawable.ic_devices_white_24dp;

NotificationCompat.Builder builder = new NotificationCompat.Builder(mService, NOTIFICATION_CHANNEL);
return builder
.setSmallIcon(smallIcon)
.setShowWhen(false)
.setOngoing(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setCategory(NotificationCompat.CATEGORY_TRANSPORT)
.setContentIntent(mRemoteStartPendingIntent)
.setContentTitle(String.format(mService.getString(R.string.connected_to),
HostManager.getInstance(mService).getHostInfo().getName()))
.setContentText(mService.getString(R.string.nothing_playing))
.build();
}

public Notification getNothingPlayingNotification() {
if (mNothingPlayingNotification == null) {
mNothingPlayingNotification = buildNothingPlayingNotification();
}
return mNothingPlayingNotification;
}

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void buildNotification(PlayerType.GetActivePlayersReturnType getActivePlayerResult,
PlayerType.PropertyValue getPropertiesResult,
ListType.ItemsAll getItemResult) {
private void notifyPlaying(PlayerType.GetActivePlayersReturnType getActivePlayerResult,
PlayerType.PropertyValue getPropertiesResult,
ListType.ItemsAll getItemResult) {
final String title, underTitle, poster;
int smallIcon, playPauseIcon, rewindIcon, ffIcon;

Expand Down Expand Up @@ -212,7 +265,7 @@ private void buildNotification(PlayerType.GetActivePlayersReturnType getActivePl
}

// Build the notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(mService);
NotificationCompat.Builder builder = new NotificationCompat.Builder(mService, NOTIFICATION_CHANNEL);
final Notification notification = builder
.setSmallIcon(smallIcon)
.setShowWhen(false)
Expand Down Expand Up @@ -270,10 +323,9 @@ private void showNotification(Bitmap bitmap) {
expandedRV.setImageViewBitmap(expandedIconResId, bitmap);
}

// NotificationManager notificationManager =
// (NotificationManager) mService.getSystemService(Context.NOTIFICATION_SERVICE);
// notificationManager.notify(NOTIFICATION_ID, notification);
mService.startForeground(NOTIFICATION_ID, notification);
NotificationManager notificationManager =
(NotificationManager) mService.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notification);
picassoTarget = null;
}
};
Expand All @@ -296,9 +348,14 @@ private PendingIntent buildActionPendingIntent(int playerId, String action) {
}

private void removeNotification() {
// NotificationManager notificationManager =
// (NotificationManager) mService.getSystemService(Context.NOTIFICATION_SERVICE);
// notificationManager.cancel(NOTIFICATION_ID);
mService.stopForeground(true);
NotificationManager notificationManager =
(NotificationManager) mService.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
}

private void notifyNothingPlaying() {
NotificationManager notificationManager =
(NotificationManager) mService.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, mNothingPlayingNotification);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
import org.xbmc.kore.utils.LogUtils;
import org.xbmc.kore.utils.TabsAdapter;
import org.xbmc.kore.utils.UIUtils;
import org.xbmc.kore.utils.Utils;

import java.net.MalformedURLException;
import java.net.URL;
Expand Down Expand Up @@ -623,32 +624,20 @@ public void playerOnPlay(PlayerType.GetActivePlayersReturnType getActivePlayerRe
}
lastImageUrl = imageUrl;

// Start service that manages connection observers
LogUtils.LOGD(TAG, "Starting observer service");
startService(new Intent(this, ConnectionObserversManagerService.class));


// // Check whether we should show a notification
// boolean showNotification = PreferenceManager
// .getDefaultSharedPreferences(this)
// .getBoolean(Settings.KEY_PREF_SHOW_NOTIFICATION,
// Settings.DEFAULT_PREF_SHOW_NOTIFICATION);
// if (showNotification) {
// // Let's start the notification service
// LogUtils.LOGD(TAG, "Starting notification service");
// startService(new Intent(this, NotificationObserver.class));
// }
//
// // Check whether we should react to phone state changes
// boolean shouldPause = PreferenceManager
// .getDefaultSharedPreferences(this)
// .getBoolean(Settings.KEY_PREF_USE_HARDWARE_VOLUME_KEYS,
// Settings.DEFAULT_PREF_USE_HARDWARE_VOLUME_KEYS);
// if (shouldPause) {
// // Let's start the listening service
// LogUtils.LOGD(TAG, "Starting phone state listener");
// startService(new Intent(this, PauseCallObserver.class));
// }
// Check whether we should show a notification
boolean showNotification = PreferenceManager
.getDefaultSharedPreferences(this)
.getBoolean(Settings.KEY_PREF_SHOW_NOTIFICATION,
Settings.DEFAULT_PREF_SHOW_NOTIFICATION);
if (showNotification) {
// Start service that manages connection observers
LogUtils.LOGD(TAG, "Starting observer service");
if (Utils.isOreoOrLater()) {
startForegroundService(new Intent(this, ConnectionObserversManagerService.class));
} else {
startService(new Intent(this, ConnectionObserversManagerService.class));
}
}
}

public void playerOnPause(PlayerType.GetActivePlayersReturnType getActivePlayerResult,
Expand Down
Loading

0 comments on commit 3077653

Please sign in to comment.