我有2個活動:MainActivity
它與main.xml
佈局(應用程序「主頁」屏幕)和AboutActivity
關聯about.xml
佈局(應用程序「關於」屏幕)。活動開關和異步Android
雖然在AboutActivity
,MainActivity
內的Async
任務仍嘗試訪問main.xml
。我的應用程序因此而停止工作。
有什麼辦法可以嗎?
- 「暫停」內
MainActivity
的Async
任務和「履歷」他們當 用戶切換從AboutActivity
回 - 或仍然在後臺訪問
main.xml
而在AboutActivity
其他信息:
MainActivity
是發起活動。 AboutActivity extends MainActivity
。用戶可以轉到「關於」屏幕/使用選項菜單切換到AboutActivity
。
MainActivity
中的Async
任務將用戶的當前位置放入文本視圖中。 about.xml
只包含靜態文本。 AboutActivity
什麼都不做,只能顯示about.xml
。
AboutActivity:
public class AboutActivity extends MainActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
}
}
MainActivity:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Creating a new non-ui thread task to download Google place json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
@Override
protected String doInBackground(String... url) {
//make asynctask wait for debugger
//android.os.Debug.waitForDebugger();
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d(DEBUG,e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
@Override
protected void onPostExecute(String result){
TextView curLoc = (TextView) findViewById(R.id.CurrentLocation);
curLoc.setText(result);
}
}
}