How to sort ToggleButton listener and AsyncTask call?

旧时模样 提交于 2019-12-12 02:34:24

问题


I will try to set the question without pasting any code because will be probably more clear.

I have an android application with one ToggleButton. When the ToggleButton is "ON" it starts a communication using sockets in an AsyncTask and when ToggleButton is "OFF" it stops the communication. I am using the event setOnCheckedChangeListener to detect the changes in the button.

Wich one will be the right way to sort all the code? Do I set the listener on the UI thread, call from the UI the asyncTask and return from the asyncTask the socket witch I have established connection with? I will need to know witch socket is open to close it once the ToggleButton is switched off...

It looks a little bit messy to me, is there a better way to do it?


回答1:


There can be several possible ways. You can use broadcast sender and receiver for you case.

Steps mentioned below:

Step 1: Create a broadcast receiver in your AsyncTask to receive broadcast from your activity.

BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("close_socket")) {
                // close your socket here.
            }
        }
    };

Step 2: Register your receiver after creating your broadcast receiver.

IntentFilter filter = new IntentFilter("close_socket");
registerReceiver(receiver, filter);

Step 3: Send broadcast from your activity to close socket.

Intent intent = new Intent("close_socket");
SendBroadcast(intent);

Wherever you have registered your broadcast receiver it will automatically receive broadcast and close socket. Hope it will help you.



来源:https://stackoverflow.com/questions/19680280/how-to-sort-togglebutton-listener-and-asynctask-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!