Safe way to stop a thread - Android
I'm trying to implement an auto-suggest like functionality for a part of my application. As a part of this, as a user types into a text field, I ping a web service for the results, parse the xml and update the listview with a list of returned results.
Here's the basic flow for my program. My question is if I'm stopping the thread the right way. Does calling thread.interrupt() 开发者_StackOverflow社区suffice?
init() {
// <snip>
searchTxt.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
FetchResults();
}});
}
private void FetchResults()
{
if(mCurrentNetworkThread != null)
{
mCurrentNetworkThread.interrupt();
mCurrentNetworkThread = null;
}
mCurrentNetworkThread = new Thread(
new Runnable() {
public void run() {
List<NameValuePair> paramTable = new ArrayList<NameValuePair>(1);
paramTable.add(new BasicNameValuePair("searchText", searchTxt.getText().toString()));
String methodName = "GetSearchResults";
NetworkAccessClass nac = new NetworkAccessClass(paramTable, IP_ADDR, methodName, 0, this);
nac.startRequest();
}
});
mCurrentNetworkThread.start();
}
@Override
public void requestSucceeded(String responseMessage, int callID) {
parseResponseFromNetwork(responseMessage);
}
@Override
public void requestFailed(String responseCode, int callID) {
}
If that code is executed from an Activity you will most likely run into concurrency problems modifying something in the GUI thread from another thread without use of a Handler. The easy way around this i recommend using an AsyncTask. It solves any of the problems you will have in Android. These tasks can be canceled via the cancel() function and will be safe as far as any Threading exceptions in Android are concerned.
[Edit]
Make sure you check out Jon's comment below about using Loaders, a 3.0 function I wasn't aware of.
Since android 3.0, AsyncTasks
will largely be replaced by Loaders
They can even be used down to Android 1.6 with the new compatibility library.
These links should help you along:
android-3-0-what-are-the-advantages-of-using-loadermanager-instances-exactly
Android Loader - Dev Guide
Try this Where to stop/destroy threads in Android Service class?
精彩评论