Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class TrackInfoUpdator {
- private static final String DEFAULT_TILE = "default_title";
- private static final String DEFAULT_ARTIST = "default_artist";
- public static void demo() {
- Callback callback = (title, artist) -> {
- titleTextView.setText(title);
- artistTextView.setText(artist);
- };
- // this is field of your activity/fragment
- TrackInfoUpdator updator = new TrackInfoUpdator(callback);
- // somewhere in onResume()
- updator.startTracking("anyLink here");
- // somewhere in onPause()
- updator.stopTracking();
- }
- private final Handler uiHandler;
- private final Callback callback;
- // not marked as volatile, used only from UI thread
- private UpdatorThread backgroundThread;
- public TrackInfoUpdator(Callback callback) {
- this.uiHandler = new Handler(Looper.getMainLooper());
- this.callback = callback;
- }
- @UiThread
- public void startTracking(String link) {
- stopTracking();
- backgroundThread = new UpdatorThread(uiHandler, callback, link);
- backgroundThread.start();
- }
- @UiThread
- public void stopTracking() {
- if (backgroundThread != null) {
- backgroundThread.disable();
- backgroundThread = null;
- }
- }
- private static class UpdatorThread extends Thread {
- private static final int MSECS_REPEAT = 3000;
- private final Handler callbackThread;
- private final Callback callback;
- private final String link;
- private volatile boolean isDisabled = false;
- public UpdatorThread(Handler callbackThread, Callback callback, String link) {
- this.callbackThread = callbackThread;
- this.callback = callback;
- this.link = link;
- }
- public void disable() {
- isDisabled = true;
- }
- @Override
- public void run() {
- while (!isDisabled) {
- try {
- waitForRepeat();
- } catch (Exception ignored) {
- }
- try {
- fetchData();
- } catch (Exception ignored) {
- }
- }
- }
- private void waitForRepeat() throws Exception {
- Thread.sleep(MSECS_REPEAT);
- }
- private void fetchData() throws Exception {
- URL url = new URL(link);
- ParsingHeaderData streaming = new ParsingHeaderData();
- Utils.TrackData trackData = streaming.getTrackDetails(url);
- String title = TextUtils.isEmpty(trackData.title) ? DEFAULT_TITLE : trackData.title;
- String artist = TextUtils.isEmpty(trackData.artist) ? DEFAULT_ARTIST : trackData.artist;
- callbackThread.post(() -> {
- if (!isDisabled) {
- callback.onTrackInfoUpdated(title, artist);
- }
- });
- }
- }
- public interface Callback {
- void onTrackInfoUpdated(String title, String artist);
- }
- }
Add Comment
Please, Sign In to add comment