简体   繁体   中英

android call function from another activity on timer task

I'm properly setting parameters of objects from another class setting an interface for it. Now I need to do the same but delayed by a timer. For that, I'm using a timer task that is called properly but then crashes when should set param from another activity. How to reach it?

        TimerTask task = new TimerTask() {
                        public void run() {
                            anotherClass.aBridge.button_back.setVisibility(View.INVISIBLE); //working fine outside timer
                        }
                    };

                    Timer timer = new Timer();
                    timer.schedule(task, 5000);

logcat error:

    10-05 12:26:58.083: E/AndroidRuntime(9815): FATAL EXCEPTION: Timer-0
    10-05 12:26:58.083: E/AndroidRuntime(9815): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
    10-05 12:26:58.083: E/AndroidRuntime(9815):     at android.view.ViewRoot.checkThread(ViewRoot.java:2990)
    10-05 12:26:58.083: E/AndroidRuntime(9815):     at android.view.ViewRoot.invalidateChild(ViewRoot.java:663)
    10-05 12:26:58.083: E/AndroidRuntime(9815):     at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:689)
    10-05 12:26:58.083: E/AndroidRuntime(9815):     at android.view.ViewGroup.invalidateChild(ViewGroup.java:2604)
    10-05 12:26:58.083: E/AndroidRuntime(9815):     at android.view.View.invalidate(View.java:5374)
    10-05 12:26:58.083: E/AndroidRuntime(9815):     at android.view.View.setFlags(View.java:4723)
    10-05 12:26:58.083: E/AndroidRuntime(9815):     at android.view.View.setVisibility(View.java:3183)
    10-05 12:26:58.083: E/AndroidRuntime(9815):     at webPush$6.run(webPush.java:274)
    10-05 12:26:58.083: E/AndroidRuntime(9815):     at java.util.Timer$TimerImpl.run(Timer.java:284)

You can't update UI from background thread. You can update UI only from UI thread. Use runOnUiThread(runnable_instance) to update UI from a non-UI Thread.

Because timer task will be started in a separate thread. But the View created by UI thread can not be touched by any other. Just as the error says.

    private Handler handler =  new Handler(){

    @Override
    public void handleMessage(Message msg) {
        //do ur work
}};

add the above code to ur class and from run call this method handler.sendMessage(Message message)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM