如何排序切换按钮监听器和调用AsyncTask的? [英] How to sort ToggleButton listener and AsyncTask call?

查看:207
本文介绍了如何排序切换按钮监听器和调用AsyncTask的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将尝试设置的问题没有任何粘贴code,因为很可能是更清晰。

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

我有一个切换按钮一个Android应用程序。当切换按钮是开,它开始使用在AsyncTask的插座的通信和当切换按钮是关,它停止通信。
我使用的事件setOnCheckedChangeListener来检测按钮的变化。

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.

至极一会整理所有code的正确方法?难道我设置UI线程上的监听器,从UI的AsyncTask的调用,并从AsyncTask的返回插座女巫我已经建立了连接?
我需要知道巫插座是开放关闭它一旦切换按钮关闭...

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?

推荐答案

有可能是几种可能的方式。您可以使用广播发送者和接收者对你的情况下。

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

步骤中提到:

第1步:在您的AsyncTask从您的活动接收广播创建广播接收机

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.

这篇关于如何排序切换按钮监听器和调用AsyncTask的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆