44import com .google .gson .GsonBuilder ;
55
66import java .io .*;
7+ import java .util .concurrent .Executors ;
8+ import java .util .concurrent .ScheduledExecutorService ;
9+ import java .util .concurrent .TimeUnit ;
710
811public class SMTC4J {
912
1013 private static final Gson GSON = new GsonBuilder ().create ();
1114
1215 private static boolean loaded = false ;
13- private static Thread updateThread = null ;
16+
17+ private static ScheduledExecutorService scheduler = null ;
1418
1519 private static MediaInfo lastMediaInfo = null ;
1620 private static PlaybackState lastPlaybackState = null ;
@@ -50,6 +54,17 @@ public static boolean isLoaded() {
5054 return loaded ;
5155 }
5256
57+ private static synchronized ScheduledExecutorService getScheduler () {
58+ if (scheduler == null || scheduler .isShutdown ()) {
59+ scheduler = Executors .newSingleThreadScheduledExecutor (r -> {
60+ Thread t = new Thread (r , "SMTC4J-Executor" );
61+ t .setDaemon (true );
62+ return t ;
63+ });
64+ }
65+ return scheduler ;
66+ }
67+
5368 public static MediaInfo getCachedMediaInfo () {
5469 return lastMediaInfo ;
5570 }
@@ -59,27 +74,17 @@ public static PlaybackState getCachedPlaybackState() {
5974 }
6075
6176 public static void updateCache () {
77+ checkIsLoaded ();
78+
6279 lastMediaInfo = parsedMediaInfo ();
6380 lastPlaybackState = parsedPlaybackState ();
6481 }
6582
66- public static void startUpdateThread (long intervalMillis ) {
67- if (updateThread != null && updateThread .isAlive ())
68- return ;
69-
70- updateThread = new Thread (() -> {
71- while (true ) {
72- try {
73- updateCache ();
74- Thread .sleep (intervalMillis );
75- } catch (InterruptedException e ) {
76- Thread .currentThread ().interrupt ();
77- break ;
78- }
79- }
80- }, "SMTC4J-Update-Thread" );
81- updateThread .setDaemon (true );
82- updateThread .start ();
83+ public static synchronized void startUpdateScheduler (long intervalMillis ) {
84+ checkIsLoaded ();
85+
86+ ScheduledExecutorService exec = getScheduler ();
87+ exec .scheduleAtFixedRate (SMTC4J ::updateCache , 0 , intervalMillis , TimeUnit .MILLISECONDS );
8388 }
8489
8590 public static MediaInfo parsedMediaInfo () {
@@ -122,6 +127,12 @@ public static void pressKey(MediaKey key) {
122127 pressMediaKey (key .ordinal ());
123128 }
124129
130+ public static void scheduleKeyPress (MediaKey key ) {
131+ checkIsLoaded ();
132+
133+ getScheduler ().execute (() -> pressKey (key ));
134+ }
135+
125136 private static void checkIsLoaded () {
126137 if (!isLoaded ())
127138 throw new IllegalStateException ("SMTC4J native library is not loaded." );
0 commit comments