Search in sources :

Example 61 with Timer

use of java.util.Timer in project openhab1-addons by openhab.

the class DelayedExecutor method schedule.

/**
     * Schedules a Task which starts after the specified delay.
     */
public void schedule(TimerTask task, long delay) {
    this.task = task;
    timer = new Timer();
    timer.schedule(task, delay);
}
Also used : Timer(java.util.Timer)

Example 62 with Timer

use of java.util.Timer in project xabber-android by redsolution.

the class ChatViewerFragment method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View view = inflater.inflate(R.layout.chat_viewer_fragment, container, false);
    contactTitleView = view.findViewById(R.id.contact_title);
    abstractContact = RosterManager.getInstance().getBestContact(account, user);
    contactTitleView.findViewById(R.id.avatar).setOnClickListener(this);
    toolbar = (Toolbar) view.findViewById(R.id.toolbar_default);
    toolbar.inflateMenu(R.menu.chat);
    toolbar.setOnMenuItemClickListener(this);
    toolbar.setNavigationIcon(R.drawable.ic_arrow_left_white_24dp);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            NavUtils.navigateUpFromSameTask(getActivity());
        }
    });
    setHasOptionsMenu(true);
    sendButton = (ImageButton) view.findViewById(R.id.button_send_message);
    sendButton.setColorFilter(ColorManager.getInstance().getAccountPainter().getGreyMain());
    AbstractChat abstractChat = MessageManager.getInstance().getChat(account, user);
    securityButton = (ImageButton) view.findViewById(R.id.button_security);
    if (abstractChat instanceof RegularChat) {
        securityButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                showSecurityMenu();
            }
        });
    } else {
        securityButton.setVisibility(View.GONE);
    }
    chatMessageAdapter = new ChatMessageAdapter(getActivity(), account, user, this, this);
    recyclerView = (RecyclerView) view.findViewById(R.id.chat_messages_recycler_view);
    recyclerView.setAdapter(chatMessageAdapter);
    layoutManager = new LinearLayoutManager(getActivity());
    layoutManager.setStackFromEnd(true);
    recyclerView.setLayoutManager(layoutManager);
    // to avoid strange bug on some 4.x androids
    view.findViewById(R.id.input_layout).setBackgroundColor(ColorManager.getInstance().getChatInputBackgroundColor());
    inputView = (EditText) view.findViewById(R.id.chat_input);
    view.findViewById(R.id.button_send_message).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            sendMessage();
        }
    });
    inputView.setOnKeyListener(new View.OnKeyListener() {

        @Override
        public boolean onKey(View view, int keyCode, KeyEvent event) {
            if (SettingsManager.chatsSendByEnter() && event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                sendMessage();
                return true;
            }
            return false;
        }
    });
    inputView.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (!skipOnTextChanges && stopTypingTimer != null) {
                stopTypingTimer.cancel();
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable text) {
            setUpInputViewButtons();
            if (skipOnTextChanges) {
                return;
            }
            ChatStateManager.getInstance().onComposing(account, user, text);
            stopTypingTimer = new Timer();
            stopTypingTimer.schedule(new TimerTask() {

                @Override
                public void run() {
                    Application.getInstance().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            ChatStateManager.getInstance().onPaused(account, user);
                        }
                    });
                }
            }, STOP_TYPING_DELAY);
        }
    });
    final ImageButton emojiButton = (ImageButton) view.findViewById(R.id.button_emoticon);
    final View rootView = view.findViewById(R.id.root_view);
    // Give the topmost view of your activity layout hierarchy. This will be used to measure soft keyboard height
    final EmojiconsPopup popup = new EmojiconsPopup(rootView, getActivity());
    //Will automatically set size according to the soft keyboard size
    popup.setSizeForSoftKeyboard();
    //If the emoji popup is dismissed, change emojiButton to smiley icon
    popup.setOnDismissListener(new PopupWindow.OnDismissListener() {

        @Override
        public void onDismiss() {
            changeEmojiKeyboardIcon(emojiButton, R.drawable.ic_mood_black_24dp);
        }
    });
    //If the text keyboard closes, also dismiss the emoji popup
    popup.setOnSoftKeyboardOpenCloseListener(new EmojiconsPopup.OnSoftKeyboardOpenCloseListener() {

        @Override
        public void onKeyboardOpen(int keyBoardHeight) {
        }

        @Override
        public void onKeyboardClose() {
            if (popup.isShowing())
                popup.dismiss();
        }
    });
    //On emoji clicked, add it to edittext
    popup.setOnEmojiconClickedListener(new EmojiconGridView.OnEmojiconClickedListener() {

        @Override
        public void onEmojiconClicked(Emojicon emojicon) {
            if (inputView == null || emojicon == null) {
                return;
            }
            int start = inputView.getSelectionStart();
            int end = inputView.getSelectionEnd();
            if (start < 0) {
                inputView.append(emojicon.getEmoji());
            } else {
                inputView.getText().replace(Math.min(start, end), Math.max(start, end), emojicon.getEmoji(), 0, emojicon.getEmoji().length());
            }
        }
    });
    //On backspace clicked, emulate the KEYCODE_DEL key event
    popup.setOnEmojiconBackspaceClickedListener(new EmojiconsPopup.OnEmojiconBackspaceClickedListener() {

        @Override
        public void onEmojiconBackspaceClicked(View v) {
            KeyEvent event = new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL);
            inputView.dispatchKeyEvent(event);
        }
    });
    // To toggle between text keyboard and emoji keyboard keyboard(Popup)
    emojiButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //If popup is not showing => emoji keyboard is not visible, we need to show it
            if (!popup.isShowing()) {
                //If keyboard is visible, simply show the emoji popup
                if (popup.isKeyBoardOpen()) {
                    popup.showAtBottom();
                    changeEmojiKeyboardIcon(emojiButton, R.drawable.ic_keyboard_black_24dp);
                } else //else, open the text keyboard first and immediately after that show the emoji popup
                {
                    inputView.setFocusableInTouchMode(true);
                    inputView.requestFocus();
                    popup.showAtBottomPending();
                    final InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.showSoftInput(inputView, InputMethodManager.SHOW_IMPLICIT);
                    changeEmojiKeyboardIcon(emojiButton, R.drawable.ic_keyboard_black_24dp);
                }
            } else //If popup is showing, simply dismiss it to show the undelying text keyboard
            {
                popup.dismiss();
            }
        }
    });
    attachButton = (ImageButton) view.findViewById(R.id.button_attach);
    attachButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            onAttachButtonPressed();
        }
    });
    return view;
}
Also used : EmojiconGridView(github.ankushsachdeva.emojicon.EmojiconGridView) PopupWindow(android.widget.PopupWindow) ChatMessageAdapter(com.xabber.android.ui.adapter.ChatMessageAdapter) InputMethodManager(android.view.inputmethod.InputMethodManager) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) RegularChat(com.xabber.android.data.message.RegularChat) KeyEvent(android.view.KeyEvent) ImageButton(android.widget.ImageButton) TimerTask(java.util.TimerTask) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) EmojiconsPopup(github.ankushsachdeva.emojicon.EmojiconsPopup) AbstractChat(com.xabber.android.data.message.AbstractChat) ImageView(android.widget.ImageView) View(android.view.View) EmojiconGridView(github.ankushsachdeva.emojicon.EmojiconGridView) RecyclerView(android.support.v7.widget.RecyclerView) Timer(java.util.Timer) Emojicon(github.ankushsachdeva.emojicon.emoji.Emojicon)

Example 63 with Timer

use of java.util.Timer in project StaticLayoutView by ragnraok.

the class AutoScrollHandler method startAutoScrollDown.

public void startAutoScrollDown() {
    final Timer timer = new Timer();
    FpsCalculator.instance().startCalculate();
    timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            if (listView.getLastVisiblePosition() >= itemCount - 1) {
                final int avgFps = FpsCalculator.instance().stopGetAvgFPS();
                uiHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(listView.getContext(), "Average FPS: " + avgFps, Toast.LENGTH_LONG).show();
                    }
                });
                timer.cancel();
            }
            uiHandler.post(new Runnable() {

                @Override
                public void run() {
                    listView.smoothScrollByOffset(Util.AUTO_SCROLL_STEP);
                }
            });
        }
    }, 0, Util.AUTO_SCROLL_INTERVAL);
}
Also used : Timer(java.util.Timer) TimerTask(java.util.TimerTask)

Example 64 with Timer

use of java.util.Timer in project robovm by robovm.

the class TimerTaskTest method test_run.

/**
     * java.util.TimerTask#run()
     */
public void test_run() {
    Timer t = null;
    try {
        // Ensure a new task is never run
        TimerTestTask testTask = new TimerTestTask();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
        }
        assertEquals("TimerTask.run() method should not have been called", 0, testTask.wasRun());
        // Ensure a task is run
        t = new Timer();
        testTask = new TimerTestTask();
        t.schedule(testTask, 200);
        while (testTask.wasRun() < 1) {
            try {
                Thread.sleep(400);
            } catch (InterruptedException e) {
            }
        }
        assertFalse(testTask.cancel());
        t.cancel();
    } finally {
        if (t != null)
            t.cancel();
    }
}
Also used : Timer(java.util.Timer)

Example 65 with Timer

use of java.util.Timer in project robovm by robovm.

the class TimerTest method test_scheduleAtFixedRateLjava_util_TimerTaskLjava_util_DateJ.

/**
     * java.util.Timer#scheduleAtFixedRate(java.util.TimerTask,
     *        java.util.Date, long)
     */
public void test_scheduleAtFixedRateLjava_util_TimerTaskLjava_util_DateJ() throws Exception {
    Timer t = null;
    try {
        // Ensure a Timer throws an IllegalStateException after cancelled
        t = new Timer();
        TimerTestTask testTask = new TimerTestTask();
        t.cancel();
        Date d = new Date(System.currentTimeMillis() + 100);
        try {
            t.scheduleAtFixedRate(testTask, d, 100);
            fail("scheduleAtFixedRate after Timer.cancel() should throw exception");
        } catch (IllegalStateException expected) {
        }
        // Ensure a Timer throws an IllegalArgumentException if delay is
        // negative
        t = new Timer();
        testTask = new TimerTestTask();
        d = new Date(-100);
        try {
            t.scheduleAtFixedRate(testTask, d, 100);
            fail("scheduleAtFixedRate with negative Date should throw IllegalArgumentException");
        } catch (IllegalArgumentException expected) {
        }
        t.cancel();
        // Ensure a Timer throws an IllegalArgumentException if period is
        // negative
        t = new Timer();
        testTask = new TimerTestTask();
        try {
            t.scheduleAtFixedRate(testTask, d, -100);
            fail("scheduleAtFixedRate with negative period should throw IllegalArgumentException");
        } catch (IllegalArgumentException expected) {
        }
        t.cancel();
        // Ensure a Timer throws an NullPointerException if date is Null
        t = new Timer();
        testTask = new TimerTestTask();
        try {
            t.scheduleAtFixedRate(testTask, null, 100);
            fail("scheduleAtFixedRate with null date should throw NullPointerException");
        } catch (NullPointerException expected) {
        }
        t.cancel();
        // Ensure proper sequence of exceptions
        t = new Timer();
        d = new Date(-100);
        try {
            t.scheduleAtFixedRate(null, d, 10);
            fail("Scheduling a null task with negative date should throw IllegalArgumentException first");
        } catch (IllegalArgumentException expected) {
        }
        t.cancel();
        // Ensure proper sequence of exceptions
        t = new Timer();
        try {
            t.scheduleAtFixedRate(null, null, -10);
            fail("Scheduling a null task & null date & negative period should throw IllegalArgumentException first");
        } catch (IllegalArgumentException expected) {
        }
        t.cancel();
        // Ensure a task is run at least twice
        t = new Timer();
        testTask = new TimerTestTask();
        d = new Date(System.currentTimeMillis() + 100);
        t.scheduleAtFixedRate(testTask, d, 100);
        Thread.sleep(400);
        assertTrue("TimerTask.run() method should have been called at least twice (" + testTask.wasRun() + ")", testTask.wasRun() >= 2);
        t.cancel();
        class SlowThenFastTask extends TimerTask {

            int wasRun = 0;

            long startedAt;

            long lastDelta;

            public void run() {
                if (wasRun == 0)
                    startedAt = System.currentTimeMillis();
                lastDelta = System.currentTimeMillis() - (startedAt + (100 * wasRun));
                wasRun++;
                if (wasRun == 2) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }

            public long lastDelta() {
                return lastDelta;
            }

            public int wasRun() {
                return wasRun;
            }
        }
        // Ensure multiple tasks are run
        t = new Timer();
        SlowThenFastTask slowThenFastTask = new SlowThenFastTask();
        d = new Date(System.currentTimeMillis() + 100);
        // at least 9 times even when asleep
        t.scheduleAtFixedRate(slowThenFastTask, d, 100);
        Thread.sleep(1000);
        long lastDelta = slowThenFastTask.lastDelta();
        assertTrue("Fixed Rate Schedule should catch up, but is off by " + lastDelta + " ms", lastDelta < 300);
        t.cancel();
    } finally {
        if (t != null)
            t.cancel();
    }
}
Also used : Timer(java.util.Timer) TimerTask(java.util.TimerTask) Date(java.util.Date)

Aggregations

Timer (java.util.Timer)448 TimerTask (java.util.TimerTask)262 IOException (java.io.IOException)33 Date (java.util.Date)22 Test (org.junit.Test)15 File (java.io.File)11 ArrayList (java.util.ArrayList)10 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)10 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)9 JobExecutor (org.activiti.engine.impl.jobexecutor.JobExecutor)9 Intent (android.content.Intent)8 Location (android.location.Location)8 LocationListener (android.location.LocationListener)8 Bundle (android.os.Bundle)8 ActivitiException (org.activiti.engine.ActivitiException)8 View (android.view.View)7 InputMethodManager (android.view.inputmethod.InputMethodManager)7 ImageView (android.widget.ImageView)7 BufferedReader (java.io.BufferedReader)7 InputStreamReader (java.io.InputStreamReader)7