Update Activity from service using handler

2019-02-19 01:02发布

问题:

I want change the state of a ToggleButton in my Activity when an event occurs in a service. Can anybody please help me to implement this using Handler? I mean where should I write the code to create the handler and how to trigger it from a service? I read similar posts but, they were not really helpful in achieving this.

回答1:

In your Activity

public class MyActivity extends Activity {
    public static Runnable runnable;
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

           runnable=new Runnable(){

            @Override
            public void run() {
            //Change status here

            }

           };

From the service

Handler handler=new Handler();
handler.post(MyActivity.runnable);