我将 Activity 中的 Web 服务调用推送到线程(如下所示)。我第一次在 Activity 中这样做时它工作正常(从我的编辑文本中获取文本并加载服务以获取纬度/经度数据)
但是当我单击后退按钮(模拟器)并尝试第二次触发该线程时,它在 .start(); 之后爆炸了。在我的点击处理程序中。我在这里做错了什么?谢谢
private Thread getLocationByZip = new Thread() {
public void run() {
try {
EditText filterText = (EditText) findViewById(R.id.zipcode);
Editable zip = filterText.getText();
LocationLookupService locationLookupService = new LocationLookupService();
selectedLocation = locationLookupService.getLocationByZip(zip.toString());
locationHandler.post(launchFindWithLocationInfo);
} catch (Exception e) {
}
}
};
private Runnable launchFindWithLocationInfo = new Runnable() {
@Override
public void run() {
try {
Intent abc = new Intent(LocationLookup.this, FindWithLocation.class);
startActivity(abc);
} catch (Exception e) {
}
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
locationHandler = new Handler();
findViewById(R.id.findbyzip).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getLocationByZip.start();
}
});
}
更新
在听取了很好的建议后,我选择了 AsyncTask,所以如果有人发现这会继续下去,上面的线程/处理程序模型看起来像下面的异步任务
private class LocationLookupTask extends AsyncTask<String, Void, Location> {
private ProgressDialog dialog;
@Override
protected void onPreExecute() {
this.dialog = ProgressDialog.show(LocationLookup.this, "", "Loading...");
}
@Override
protected Location doInBackground(String... zips) {
Location selectedLocation = null;
for (String zip : zips) {
LocationLookupService locationLookupService = new LocationLookupService();
selectedLocation = locationLookupService.getLocationByZip(zip);
}
return selectedLocation;
}
@Override
protected void onPostExecute(Location location) {
this.dialog.dismiss();
((AppDelegate) getApplicationContext()).setSelectedLocation(location);
Intent abc = new Intent(LocationLookup.this, FindWithLocation.class);
startActivity(abc);
}
}
现在要在 onclick 中调用它,您可以这样做
findViewById(R.id.findbyzip).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText filterText = (EditText) findViewById(R.id.zipcode);
Editable zip = filterText.getText();
LocationLookupTask task = new LocationLookupTask();
task.execute(new String[]{zip.toString()});
}
});
最佳答案
你不能启动一个线程两次:
It is never legal to start a thread more than once.
取自Thread.start() .
因此,您需要创建一个新线程并启动该线程。
关于java - 为什么我不能在我的 Activity 中启动线程 2x?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6162984/