问题
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