From e32a5f6816de3f043724d6a1ff1f3aeb63d10da3 Mon Sep 17 00:00:00 2001 From: Florens Douwes Date: Wed, 26 Mar 2014 19:47:03 +0100 Subject: [PATCH] Fixed load more problems in the background. --- Chan/build.gradle | 42 ----- Chan/gradlew | 164 ------------------ Chan/gradlew.bat | 90 ---------- Chan/src/org/floens/chan/ChanApplication.java | 2 +- .../org/floens/chan/adapter/PostAdapter.java | 27 +-- .../floens/chan/fragment/ThreadFragment.java | 2 +- Chan/src/org/floens/chan/loader/Loader.java | 154 +++++++++------- .../floens/chan/service/PinnedService.java | 17 +- .../floens/chan/utils/ChanPreferences.java | 4 +- .../src/org/floens/chan/watch/PinWatcher.java | 4 +- .../org/floens/chan/watch/WatchNotifier.java | 40 ++++- 11 files changed, 155 insertions(+), 391 deletions(-) delete mode 100644 Chan/build.gradle delete mode 100644 Chan/gradlew delete mode 100644 Chan/gradlew.bat diff --git a/Chan/build.gradle b/Chan/build.gradle deleted file mode 100644 index b7c62412..00000000 --- a/Chan/build.gradle +++ /dev/null @@ -1,42 +0,0 @@ -buildscript { - repositories { - mavenCentral() - } - dependencies { - classpath 'com.android.tools.build:gradle:0.5.+' - } -} -apply plugin: 'android' - -dependencies { - compile fileTree(dir: 'libs', include: '*.jar') -} - -android { - compileSdkVersion 19 - buildToolsVersion "19.0.0" - - sourceSets { - main { - manifest.srcFile 'AndroidManifest.xml' - java.srcDirs = ['src'] - resources.srcDirs = ['src'] - aidl.srcDirs = ['src'] - renderscript.srcDirs = ['src'] - res.srcDirs = ['res'] - assets.srcDirs = ['assets'] - } - - // Move the tests to tests/java, tests/res, etc... - instrumentTest.setRoot('tests') - - // Move the build types to build-types/ - // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ... - // This moves them out of them default location under src//... which would - // conflict with src/ being used by the main source set. - // Adding new build types or product flavors should be accompanied - // by a similar customization. - debug.setRoot('build-types/debug') - release.setRoot('build-types/release') - } -} diff --git a/Chan/gradlew b/Chan/gradlew deleted file mode 100644 index 91a7e269..00000000 --- a/Chan/gradlew +++ /dev/null @@ -1,164 +0,0 @@ -#!/usr/bin/env bash - -############################################################################## -## -## Gradle start up script for UN*X -## -############################################################################## - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" - -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" - -warn ( ) { - echo "$*" -} - -die ( ) { - echo - echo "$*" - echo - exit 1 -} - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; -esac - -# For Cygwin, ensure paths are in UNIX format before anything is touched. -if $cygwin ; then - [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` -fi - -# Attempt to set APP_HOME -# Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi -done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >&- -APP_HOME="`pwd -P`" -cd "$SAVED" >&- - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." -fi - -# Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi -fi - -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi - -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi - # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" - fi - i=$((i+1)) - done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac -fi - -# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules -function splitJvmOpts() { - JVM_OPTS=("$@") -} -eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS -JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" - -exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/Chan/gradlew.bat b/Chan/gradlew.bat deleted file mode 100644 index 8a0b282a..00000000 --- a/Chan/gradlew.bat +++ /dev/null @@ -1,90 +0,0 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windowz variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/Chan/src/org/floens/chan/ChanApplication.java b/Chan/src/org/floens/chan/ChanApplication.java index 643545d9..6436fe05 100644 --- a/Chan/src/org/floens/chan/ChanApplication.java +++ b/Chan/src/org/floens/chan/ChanApplication.java @@ -71,7 +71,7 @@ public class ChanApplication extends Application { new PinnedManager(this); new ReplyManager(this); - PinnedService.startStopAccordingToSettings(this); + PinnedService.updateRunningState(this); } } diff --git a/Chan/src/org/floens/chan/adapter/PostAdapter.java b/Chan/src/org/floens/chan/adapter/PostAdapter.java index baf99c75..22120a81 100644 --- a/Chan/src/org/floens/chan/adapter/PostAdapter.java +++ b/Chan/src/org/floens/chan/adapter/PostAdapter.java @@ -26,7 +26,6 @@ public class PostAdapter extends BaseAdapter { private final ThreadManager threadManager; private final ListView listView; private boolean endOfLine; - private int count = 0; private final List postList = new ArrayList(); private long lastViewedTime = 0; @@ -39,9 +38,9 @@ public class PostAdapter extends BaseAdapter { @Override public int getCount() { if (threadManager.getLoadable().isBoardMode() || threadManager.getLoadable().isThreadMode()) { - return count + 1; + return postList.size() + 1; } else { - return count; + return postList.size(); } } @@ -62,7 +61,7 @@ public class PostAdapter extends BaseAdapter { threadManager.requestNextData(); } - if (position >= count) { + if (position >= postList.size()) { if (System.currentTimeMillis() - lastViewedTime > 10000L) { lastViewedTime = System.currentTimeMillis(); threadManager.bottomPostViewed(); @@ -110,9 +109,20 @@ public class PostAdapter extends BaseAdapter { } } - public void addList(List list) { - postList.addAll(list); - count = postList.size(); + public void appendList(List list) { + for (Post post : list) { + boolean flag = true; + for (Post own : postList) { + if (post.no == own.no) { + flag = false; + break; + } + } + + if (flag) { + postList.add(post); + } + } notifyDataSetChanged(); } @@ -120,7 +130,6 @@ public class PostAdapter extends BaseAdapter { public void setList(List list) { postList.clear(); postList.addAll(list); - count = postList.size(); notifyDataSetChanged(); } @@ -140,8 +149,6 @@ public class PostAdapter extends BaseAdapter { for (int i = 0; i < postList.size(); i++) { if (postList.get(i).no == post.no) { -// listView.smoothScrollToPosition(i); - ScrollerRunnable r = new ScrollerRunnable(listView); r.start(i); diff --git a/Chan/src/org/floens/chan/fragment/ThreadFragment.java b/Chan/src/org/floens/chan/fragment/ThreadFragment.java index 2719c860..c29975ab 100644 --- a/Chan/src/org/floens/chan/fragment/ThreadFragment.java +++ b/Chan/src/org/floens/chan/fragment/ThreadFragment.java @@ -157,7 +157,7 @@ public class ThreadFragment extends Fragment implements ThreadManager.ThreadMana } if (append) { - postAdapter.addList(posts); + postAdapter.appendList(posts); } else { postAdapter.setList(posts); } diff --git a/Chan/src/org/floens/chan/loader/Loader.java b/Chan/src/org/floens/chan/loader/Loader.java index f5d86bb1..bad53f4a 100644 --- a/Chan/src/org/floens/chan/loader/Loader.java +++ b/Chan/src/org/floens/chan/loader/Loader.java @@ -20,7 +20,7 @@ public class Loader { private static final String TAG = "Loader"; private static final Handler handler = new Handler(Looper.getMainLooper()); - private static final int[] watchTimeouts = {5, 10, 15, 20, 30, 60, 90, 120, 180, 240, 300}; + private static final int[] watchTimeouts = { 10, 15, 20, 30, 60, 90, 120, 180, 240, 300, 600, 1800, 3600 }; private final List listeners = new ArrayList(); private final Loadable loadable; @@ -28,7 +28,7 @@ public class Loader { private final List cachedPosts = new ArrayList(); private boolean destroyed = false; - private boolean activityStarted = false; + private boolean autoReload = false; private ChanReaderRequest request; private int currentTimeout; @@ -42,7 +42,9 @@ public class Loader { /** * Add a LoaderListener - * @param l the listener to add + * + * @param l + * the listener to add */ public void addListener(LoaderListener l) { listeners.add(l); @@ -50,7 +52,9 @@ public class Loader { /** * Remove a LoaderListener - * @param l the listener to remove + * + * @param l + * the listener to remove * @return true if there are no more listeners, false otherwise */ public boolean removeListener(LoaderListener l) { @@ -64,7 +68,38 @@ public class Loader { } } + /** + * Enable this if requestMoreData should me called automatically when the + * timer hits 0 + */ + public void setAutoLoadMore(boolean autoReload) { + if (this.autoReload != autoReload) { + Logger.test("Setting autoreload to " + autoReload); + this.autoReload = autoReload; + + if (!autoReload) { + clearTimer(); + } + } + } + + /** + * Request more data if the time left is below 0 + * If auto load more is disabled, this needs to be called manually. + * Otherwise this is called automatically when the timer hits 0. + */ + public void tryLoadMoreIfTime() { + if (getTimeUntilLoadMore() < 0L) { + requestMoreData(); + } + } + + /** + * Request data for the first time. + */ public void requestData() { + clearTimer(); + if (request != null) { request.cancel(); } @@ -80,7 +115,12 @@ public class Loader { request = getData(); } - public void requestNextData() { + /** + * Request more data + */ + public void requestMoreData() { + clearTimer(); + if (loadable.isBoardMode()) { loadable.no++; @@ -94,15 +134,16 @@ public class Loader { return; } - clearTimer(); - request = getData(); } } - public void requestNextDataResetTimer() { + /** + * Request more data and reset the watch timer. + */ + public void requestMoreDataAndResetTimer() { currentTimeout = 0; - requestNextData(); + requestMoreData(); } /** @@ -120,28 +161,11 @@ public class Loader { return loadable; } - // Temp fix - public void activityHasBinded() { - activityStarted = true; - } - - public void onStart() { - if (!activityStarted) { - activityStarted = true; - if (loadable.isThreadMode()) { - requestNextDataResetTimer(); - } - } - } - - public void onStop() { - if (activityStarted) { - activityStarted = false; - clearTimer(); - } - } - - public long getTimeUntilReload() { + /** + * Get the time in milliseconds until another loadMore is recommended + * @return + */ + public long getTimeUntilLoadMore() { if (request != null) { return 0L; } else { @@ -156,57 +180,64 @@ public class Loader { } if (pendingRunnable == null) { - lastPostCount = postCount; - if (postCount > lastPostCount) { currentTimeout = 0; } else { - currentTimeout = Math.min(watchTimeouts.length - 1, currentTimeout + 1); + currentTimeout++; + if (currentTimeout >= watchTimeouts.length) { + currentTimeout = watchTimeouts.length - 1; + } } - if (activityStarted) { + if (!autoReload && currentTimeout < 4) { + currentTimeout = 4; // At least 60 seconds in the background + } + + lastPostCount = postCount; + + Logger.test("Current timeout: " + watchTimeouts[currentTimeout]); + + if (autoReload) { pendingRunnable = new Runnable() { @Override public void run() { - pendingRunnableCallback(); + pendingRunnable = null; + tryLoadMoreIfTime(); }; }; - + Logger.test("Scheduled reload"); handler.postDelayed(pendingRunnable, watchTimeouts[currentTimeout] * 1000L); + } } } private void clearTimer() { if (pendingRunnable != null) { + Logger.test("Removed reload"); handler.removeCallbacks(pendingRunnable); pendingRunnable = null; } } - private void pendingRunnableCallback() { - Logger.d(TAG, "pending callback"); - pendingRunnable = null; - requestNextData(); - } - private ChanReaderRequest getData() { Logger.i(TAG, "Requested " + loadable.board + ", " + loadable.no); - ChanReaderRequest request = ChanReaderRequest.newInstance(loadable, cachedPosts, new Response.Listener>() { - @Override - public void onResponse(List list) { - Loader.this.request = null; - onData(list); - } - }, new Response.ErrorListener() { - @Override - public void onErrorResponse(VolleyError error) { - Loader.this.request = null; - onError(error); - } - }); + ChanReaderRequest request = ChanReaderRequest.newInstance(loadable, cachedPosts, + new Response.Listener>() { + @Override + public void onResponse(List list) { + Loader.this.request = null; + onData(list); + } + }, new Response.ErrorListener() { + @Override + public void onErrorResponse(VolleyError error) { + Loader.this.request = null; + onError(error); + } + }); ChanApplication.getVolleyRequestQueue().add(request); @@ -214,7 +245,8 @@ public class Loader { } private void onData(List result) { - if (destroyed) return; + if (destroyed) + return; cachedPosts.clear(); @@ -238,7 +270,8 @@ public class Loader { } private void onError(VolleyError error) { - if (destroyed) return; + if (destroyed) + return; cachedPosts.clear(); @@ -261,8 +294,3 @@ public class Loader { public void onError(VolleyError error); } } - - - - - diff --git a/Chan/src/org/floens/chan/service/PinnedService.java b/Chan/src/org/floens/chan/service/PinnedService.java index b7e0e345..fa59a467 100644 --- a/Chan/src/org/floens/chan/service/PinnedService.java +++ b/Chan/src/org/floens/chan/service/PinnedService.java @@ -25,7 +25,7 @@ public class PinnedService extends Service { private Thread loadThread; private boolean running = true; - private final WatchNotifier watchNotifier; + private WatchNotifier watchNotifier; public static void onActivityStart() { activityInForeground = true; @@ -41,7 +41,11 @@ public class PinnedService extends Service { } } - public static void startStopAccordingToSettings(Context context) { + public static boolean getActivityInForeground() { + return activityInForeground; + } + + public static void updateRunningState(Context context) { if (ChanPreferences.getWatchEnabled()) { if (!getRunning()) { enable(context); @@ -78,14 +82,12 @@ public class PinnedService extends Service { }); } - public PinnedService() { - watchNotifier = new WatchNotifier(this); - } - @Override public void onCreate() { super.onCreate(); + watchNotifier = new WatchNotifier(this); + instance = this; startThread(); @@ -141,10 +143,11 @@ public class PinnedService extends Service { if (loadThread != null) { loadThread.interrupt(); } + watchNotifier.onForegroundChanged(); } private void onActivityInBackground() { - + watchNotifier.onForegroundChanged(); } private void update() { diff --git a/Chan/src/org/floens/chan/utils/ChanPreferences.java b/Chan/src/org/floens/chan/utils/ChanPreferences.java index 7a64c76a..083f5256 100644 --- a/Chan/src/org/floens/chan/utils/ChanPreferences.java +++ b/Chan/src/org/floens/chan/utils/ChanPreferences.java @@ -33,7 +33,7 @@ public class ChanPreferences { } /** - * This also calls startStopAccordingToSettings on the PinnedService to + * This also calls updateRunningState on the PinnedService to * start/stop the service as needed. * * @param enabled @@ -41,7 +41,7 @@ public class ChanPreferences { public static void setWatchEnabled(boolean enabled) { if (getWatchEnabled() != enabled) { ChanApplication.getPreferences().edit().putBoolean("preference_watch_enabled", enabled).commit(); - PinnedService.startStopAccordingToSettings(ChanApplication.getInstance()); + PinnedService.updateRunningState(ChanApplication.getInstance()); } } } diff --git a/Chan/src/org/floens/chan/watch/PinWatcher.java b/Chan/src/org/floens/chan/watch/PinWatcher.java index b4a55d6d..2d9cd2cd 100644 --- a/Chan/src/org/floens/chan/watch/PinWatcher.java +++ b/Chan/src/org/floens/chan/watch/PinWatcher.java @@ -34,9 +34,7 @@ public class PinWatcher implements Loader.LoaderListener { // Logger.test("PinWatcher update"); if (!isError) { - if (loader.getTimeUntilReload() < 0L) { - loader.requestNextDataResetTimer(); - } + loader.tryLoadMoreIfTime(); } } diff --git a/Chan/src/org/floens/chan/watch/WatchNotifier.java b/Chan/src/org/floens/chan/watch/WatchNotifier.java index 6b5f5fdf..72d7de41 100644 --- a/Chan/src/org/floens/chan/watch/WatchNotifier.java +++ b/Chan/src/org/floens/chan/watch/WatchNotifier.java @@ -3,20 +3,26 @@ package org.floens.chan.watch; import java.util.List; import org.floens.chan.R; +import org.floens.chan.activity.BoardActivity; import org.floens.chan.manager.PinnedManager; import org.floens.chan.model.Pin; +import org.floens.chan.service.PinnedService; import android.app.Notification; import android.app.NotificationManager; +import android.app.PendingIntent; import android.content.Context; +import android.content.Intent; public class WatchNotifier { private final int NOTIFICATION_ID = 1; - private final Context context; + private final PinnedService pinnedService; + private final NotificationManager nm; - public WatchNotifier(Context context) { - this.context = context; + public WatchNotifier(PinnedService pinnedService) { + this.pinnedService = pinnedService; + nm = (NotificationManager) pinnedService.getSystemService(Context.NOTIFICATION_SERVICE); } public void update() { @@ -30,20 +36,38 @@ public class WatchNotifier { pinCount++; } - showNotification(count + " new posts in " + pinCount + " threads"); -// showNotification("WatchNotifier update"); + if (!PinnedService.getActivityInForeground()) { + showNotification(count + " new posts in " + pinCount + " threads\n" + System.currentTimeMillis()); + } + } + + public void onForegroundChanged() { + if (PinnedService.getActivityInForeground()) { + nm.cancel(NOTIFICATION_ID); + } else { + + } } + @SuppressWarnings("deprecation") private void showNotification(String text) { - NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); + Intent intent = new Intent(pinnedService, BoardActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); + PendingIntent pending = PendingIntent.getActivity(pinnedService, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); + + Notification.Builder builder = new Notification.Builder(pinnedService); + builder.setContentIntent(pending); - Notification.Builder builder = new Notification.Builder(context); builder.setTicker(text); builder.setContentTitle(text); builder.setContentText(text); builder.setSmallIcon(R.drawable.ic_stat_notify); - builder.setOnlyAlertOnce(false); nm.notify(NOTIFICATION_ID, builder.getNotification()); } } + + + + +