Paul
Paul

Reputation: 5974

runOnUiThread from class that doesn't support it

I am editing this code from cSipSimple: https://code.google.com/p/csipsimple/source/browse/trunk/CSipSimple/src/com/csipsimple/ui/incall/InCallCard.java?spec=svn2170&r=2170

And wish to add this method:

public void pushtotalk2(final View view) {

        final boolean on = ((ToggleButton) view).isChecked();
        ((ToggleButton) view).setEnabled(false);

        new Thread(new Runnable() {
            @Override


    public void run() {
            try {
                Instrumentation inst = new Instrumentation();
                if (on) {

                    inst.sendKeyDownUpSync(KeyEvent.KEYCODE_NUMPAD_MULTIPLY);
                    Thread.sleep(500);
                    inst.sendKeyDownUpSync(KeyEvent.KEYCODE_9);
                    Thread.sleep(500);

                    runOnUiThread(new Runnable() {
                        public void run() {
                            ((ToggleButton) view).setBackgroundResource(R.drawable.btn_blue_glossy);
                            ((ToggleButton) view).setEnabled(true);
                        }
                    });
                } else {
                    inst.sendKeyDownUpSync(KeyEvent.KEYCODE_POUND);
                    Thread.sleep(500);
                    inst.sendKeyDownUpSync(KeyEvent.KEYCODE_9);
                    Thread.sleep(500);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            ((ToggleButton) view).setBackgroundResource(R.drawable.btn_lightblue_glossy);
                            ((ToggleButton) view).setEnabled(true);
                        }
                    });
                }
            } catch (InterruptedException e) {
                Log.d(TAG, "Failed to send keycodes: " + e.getMessage());
            }
        }
    }).start();
}

However I get the error: runOnUiThread(new Runnable(){}) is undefined for the type new Thread(){}

My understanding is that the activity class has this method, but how do I access it from my code?

I tried making a constructor and got this error:

Implicit super constructor FrameLayout() is undefined. Must explicitly invoke another constructor

Any ideas on how this is done correctly?

Upvotes: 0

Views: 2437

Answers (2)

creaity
creaity

Reputation: 665

runOnUiThread is not defined for Views. Only for Activities. And InCallCard is just a view.

You can use the post(Runnable) method instead of runOnUiThread().

Upvotes: 1

Carnal
Carnal

Reputation: 22064

Since you want to run something in the UI Thread from a non Activity class, you can use a Handler instead.

new Handler().post(new Runnable() {
     public void run() {
         ((ToggleButton) view).setBackgroundResource(R.drawable.btn_blue_glossy);
         ((ToggleButton) view).setEnabled(true);
     }
});

Upvotes: 7

Related Questions