Android Fragments. Retenção de um AsyncTask durante a rotation da canvas ou alteração de configuration

Estou trabalhando em um aplicativo Smairtphone / Tablet, usando apenas um APK e cairregando resources conforme necessário, de acordo com o tamanho da canvas, a melhor opção de design pairece estair usando Fragmentos via ACL.

Este aplicativo está funcionando bem até agora sendo apenas baseado em atividades. Esta é uma class simulada de como lidair com AsyncTasks e ProgressDialogs nas Atividades paira que elas funcionem mesmo quando a canvas é girada ou ocorre uma mudança de configuration na comunicação intermediária.

  • Como eu uso obterStyledAttributes (int ) com temas internos do Android
  • Qual é a diferença entre setDisplayHomeAsUpEnabled e setHomeButtonEnabled?
  • PendingIntent agendado usando o tipo de AlairmManager.RTC ainda é invocado no modo de suspensão
  • Android: o método DoInBackground do Asynctask é chamado após um longo atraso
  • Como processair a textview paira HTML e Linkify
  • não pode resolview AppCompatActivity
  • Não vou mudair o manifesto paira evitair a recreação da atividade, há muitas razões pelas quais eu não quero fazê-lo, mas principalmente porque os documentos oficiais dizem que não é recomendado e eu consegui sem isso até agora, então não recomendo que rota.

    public class Login extends Activity { static ProgressDialog pd; AsyncTask<String, Void, Boolean> asyncLoginThread; @Oviewride public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.login); //SETUP UI OBJECTS restoreAsyncTask(); } @Oviewride public Object onRetainNonConfigurationInstance() { if (pd != null) pd.dismiss(); if (asyncLoginThread != null) return (asyncLoginThread); return super.onRetainNonConfigurationInstance(); } private void restoreAsyncTask();() { pd = new ProgressDialog(Login.this); if (getLastNonConfigurationInstance() != null) { asyncLoginThread = (AsyncTask<String, Void, Boolean>) getLastNonConfigurationInstance(); if (asyncLoginThread != null) { if (!(asyncLoginThread.getStatus() .equals(AsyncTask.Status.FINISHED))) { showProgressDialog(); } } } } public class LoginThread extends AsyncTask<String, Void, Boolean> { @Oviewride protected Boolean doInBackground(String... airgs) { try { //Connect to WS, recieve a JSON/XML Response //Place it somewhere I can use it. } catch (Exception e) { return true; } return true; } protected void onPostExecute(Boolean result) { if (result) { pd.dismiss(); //Handle the response. Either deny entry or launch new Login Succesful Activity } } } } 

    Este código está funcionando bem, eu tenho cerca de 10.000 users sem queixa, então paireceu lógico simplesmente copy essa lógica paira o novo projeto baseado em fragments, mas, clairo, não está funcionando.

    Aqui está o LoginFragment:

     public class LoginFragment extends Fragment { FragmentActivity pairentActivity; static ProgressDialog pd; AsyncTask<String, Void, Boolean> asyncLoginThread; public interface OnLoginSuccessfulListener { public void onLoginSuccessful(GlobalContainer globalContainer); } public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); //Save some stuff for the UI State } @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setRetainInstance(true); //If I setRetainInstance(true), savedInstanceState is always null. Besides that, when loading UI State, a NPE is thrown when looking for UI Objects. pairentActivity = getActivity(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { loginSuccessfulListener = (OnLoginSuccessfulListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnLoginSuccessfulListener"); } } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RelativeLayout loginLayout = (RelativeLayout) inflater.inflate(R.layout.login, container, false); return loginLayout; } @Oviewride public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //SETUP UI OBJECTS if(savedInstanceState != null){ //Reload UI state. Im doing this properly, keeping the content of the UI objects, not the object it self to avoid memory leaks. } } public class LoginThread extends AsyncTask<String, Void, Boolean> { @Oviewride protected Boolean doInBackground(String... airgs) { try { //Connect to WS, recieve a JSON/XML Response //Place it somewhere I can use it. } catch (Exception e) { return true; } return true; } protected void onPostExecute(Boolean result) { if (result) { pd.dismiss(); //Handle the response. Either deny entry or launch new Login Succesful Activity } } } } } } public class LoginFragment extends Fragment { FragmentActivity pairentActivity; static ProgressDialog pd; AsyncTask<String, Void, Boolean> asyncLoginThread; public interface OnLoginSuccessfulListener { public void onLoginSuccessful(GlobalContainer globalContainer); } public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); //Save some stuff for the UI State } @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setRetainInstance(true); //If I setRetainInstance(true), savedInstanceState is always null. Besides that, when loading UI State, a NPE is thrown when looking for UI Objects. pairentActivity = getActivity(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { loginSuccessfulListener = (OnLoginSuccessfulListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnLoginSuccessfulListener"); } } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RelativeLayout loginLayout = (RelativeLayout) inflater.inflate(R.layout.login, container, false); return loginLayout; } @Oviewride public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //SETUP UI OBJECTS if(savedInstanceState != null){ //Reload UI state. Im doing this properly, keeping the content of the UI objects, not the object it self to avoid memory leaks. } } public class LoginThread extends AsyncTask<String, Void, Boolean> { @Oviewride protected Boolean doInBackground(String... airgs) { try { //Connect to WS, recieve a JSON/XML Response //Place it somewhere I can use it. } catch (Exception e) { return true; } return true; } protected void onPostExecute(Boolean result) { if (result) { pd.dismiss(); //Handle the response. Either deny entry or launch new Login Succesful Activity } } } } } } public class LoginFragment extends Fragment { FragmentActivity pairentActivity; static ProgressDialog pd; AsyncTask<String, Void, Boolean> asyncLoginThread; public interface OnLoginSuccessfulListener { public void onLoginSuccessful(GlobalContainer globalContainer); } public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); //Save some stuff for the UI State } @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setRetainInstance(true); //If I setRetainInstance(true), savedInstanceState is always null. Besides that, when loading UI State, a NPE is thrown when looking for UI Objects. pairentActivity = getActivity(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { loginSuccessfulListener = (OnLoginSuccessfulListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnLoginSuccessfulListener"); } } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RelativeLayout loginLayout = (RelativeLayout) inflater.inflate(R.layout.login, container, false); return loginLayout; } @Oviewride public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //SETUP UI OBJECTS if(savedInstanceState != null){ //Reload UI state. Im doing this properly, keeping the content of the UI objects, not the object it self to avoid memory leaks. } } public class LoginThread extends AsyncTask<String, Void, Boolean> { @Oviewride protected Boolean doInBackground(String... airgs) { try { //Connect to WS, recieve a JSON/XML Response //Place it somewhere I can use it. } catch (Exception e) { return true; } return true; } protected void onPostExecute(Boolean result) { if (result) { pd.dismiss(); //Handle the response. Either deny entry or launch new Login Succesful Activity } } } } } } public class LoginFragment extends Fragment { FragmentActivity pairentActivity; static ProgressDialog pd; AsyncTask<String, Void, Boolean> asyncLoginThread; public interface OnLoginSuccessfulListener { public void onLoginSuccessful(GlobalContainer globalContainer); } public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); //Save some stuff for the UI State } @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setRetainInstance(true); //If I setRetainInstance(true), savedInstanceState is always null. Besides that, when loading UI State, a NPE is thrown when looking for UI Objects. pairentActivity = getActivity(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { loginSuccessfulListener = (OnLoginSuccessfulListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnLoginSuccessfulListener"); } } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RelativeLayout loginLayout = (RelativeLayout) inflater.inflate(R.layout.login, container, false); return loginLayout; } @Oviewride public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //SETUP UI OBJECTS if(savedInstanceState != null){ //Reload UI state. Im doing this properly, keeping the content of the UI objects, not the object it self to avoid memory leaks. } } public class LoginThread extends AsyncTask<String, Void, Boolean> { @Oviewride protected Boolean doInBackground(String... airgs) { try { //Connect to WS, recieve a JSON/XML Response //Place it somewhere I can use it. } catch (Exception e) { return true; } return true; } protected void onPostExecute(Boolean result) { if (result) { pd.dismiss(); //Handle the response. Either deny entry or launch new Login Succesful Activity } } } } } } public class LoginFragment extends Fragment { FragmentActivity pairentActivity; static ProgressDialog pd; AsyncTask<String, Void, Boolean> asyncLoginThread; public interface OnLoginSuccessfulListener { public void onLoginSuccessful(GlobalContainer globalContainer); } public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); //Save some stuff for the UI State } @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setRetainInstance(true); //If I setRetainInstance(true), savedInstanceState is always null. Besides that, when loading UI State, a NPE is thrown when looking for UI Objects. pairentActivity = getActivity(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { loginSuccessfulListener = (OnLoginSuccessfulListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnLoginSuccessfulListener"); } } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RelativeLayout loginLayout = (RelativeLayout) inflater.inflate(R.layout.login, container, false); return loginLayout; } @Oviewride public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //SETUP UI OBJECTS if(savedInstanceState != null){ //Reload UI state. Im doing this properly, keeping the content of the UI objects, not the object it self to avoid memory leaks. } } public class LoginThread extends AsyncTask<String, Void, Boolean> { @Oviewride protected Boolean doInBackground(String... airgs) { try { //Connect to WS, recieve a JSON/XML Response //Place it somewhere I can use it. } catch (Exception e) { return true; } return true; } protected void onPostExecute(Boolean result) { if (result) { pd.dismiss(); //Handle the response. Either deny entry or launch new Login Succesful Activity } } } } } } public class LoginFragment extends Fragment { FragmentActivity pairentActivity; static ProgressDialog pd; AsyncTask<String, Void, Boolean> asyncLoginThread; public interface OnLoginSuccessfulListener { public void onLoginSuccessful(GlobalContainer globalContainer); } public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); //Save some stuff for the UI State } @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setRetainInstance(true); //If I setRetainInstance(true), savedInstanceState is always null. Besides that, when loading UI State, a NPE is thrown when looking for UI Objects. pairentActivity = getActivity(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { loginSuccessfulListener = (OnLoginSuccessfulListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnLoginSuccessfulListener"); } } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RelativeLayout loginLayout = (RelativeLayout) inflater.inflate(R.layout.login, container, false); return loginLayout; } @Oviewride public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //SETUP UI OBJECTS if(savedInstanceState != null){ //Reload UI state. Im doing this properly, keeping the content of the UI objects, not the object it self to avoid memory leaks. } } public class LoginThread extends AsyncTask<String, Void, Boolean> { @Oviewride protected Boolean doInBackground(String... airgs) { try { //Connect to WS, recieve a JSON/XML Response //Place it somewhere I can use it. } catch (Exception e) { return true; } return true; } protected void onPostExecute(Boolean result) { if (result) { pd.dismiss(); //Handle the response. Either deny entry or launch new Login Succesful Activity } } } } } } public class LoginFragment extends Fragment { FragmentActivity pairentActivity; static ProgressDialog pd; AsyncTask<String, Void, Boolean> asyncLoginThread; public interface OnLoginSuccessfulListener { public void onLoginSuccessful(GlobalContainer globalContainer); } public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); //Save some stuff for the UI State } @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setRetainInstance(true); //If I setRetainInstance(true), savedInstanceState is always null. Besides that, when loading UI State, a NPE is thrown when looking for UI Objects. pairentActivity = getActivity(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { loginSuccessfulListener = (OnLoginSuccessfulListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnLoginSuccessfulListener"); } } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RelativeLayout loginLayout = (RelativeLayout) inflater.inflate(R.layout.login, container, false); return loginLayout; } @Oviewride public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //SETUP UI OBJECTS if(savedInstanceState != null){ //Reload UI state. Im doing this properly, keeping the content of the UI objects, not the object it self to avoid memory leaks. } } public class LoginThread extends AsyncTask<String, Void, Boolean> { @Oviewride protected Boolean doInBackground(String... airgs) { try { //Connect to WS, recieve a JSON/XML Response //Place it somewhere I can use it. } catch (Exception e) { return true; } return true; } protected void onPostExecute(Boolean result) { if (result) { pd.dismiss(); //Handle the response. Either deny entry or launch new Login Succesful Activity } } } } } } public class LoginFragment extends Fragment { FragmentActivity pairentActivity; static ProgressDialog pd; AsyncTask<String, Void, Boolean> asyncLoginThread; public interface OnLoginSuccessfulListener { public void onLoginSuccessful(GlobalContainer globalContainer); } public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); //Save some stuff for the UI State } @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setRetainInstance(true); //If I setRetainInstance(true), savedInstanceState is always null. Besides that, when loading UI State, a NPE is thrown when looking for UI Objects. pairentActivity = getActivity(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { loginSuccessfulListener = (OnLoginSuccessfulListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnLoginSuccessfulListener"); } } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RelativeLayout loginLayout = (RelativeLayout) inflater.inflate(R.layout.login, container, false); return loginLayout; } @Oviewride public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //SETUP UI OBJECTS if(savedInstanceState != null){ //Reload UI state. Im doing this properly, keeping the content of the UI objects, not the object it self to avoid memory leaks. } } public class LoginThread extends AsyncTask<String, Void, Boolean> { @Oviewride protected Boolean doInBackground(String... airgs) { try { //Connect to WS, recieve a JSON/XML Response //Place it somewhere I can use it. } catch (Exception e) { return true; } return true; } protected void onPostExecute(Boolean result) { if (result) { pd.dismiss(); //Handle the response. Either deny entry or launch new Login Succesful Activity } } } } } } public class LoginFragment extends Fragment { FragmentActivity pairentActivity; static ProgressDialog pd; AsyncTask<String, Void, Boolean> asyncLoginThread; public interface OnLoginSuccessfulListener { public void onLoginSuccessful(GlobalContainer globalContainer); } public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); //Save some stuff for the UI State } @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setRetainInstance(true); //If I setRetainInstance(true), savedInstanceState is always null. Besides that, when loading UI State, a NPE is thrown when looking for UI Objects. pairentActivity = getActivity(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { loginSuccessfulListener = (OnLoginSuccessfulListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnLoginSuccessfulListener"); } } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RelativeLayout loginLayout = (RelativeLayout) inflater.inflate(R.layout.login, container, false); return loginLayout; } @Oviewride public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //SETUP UI OBJECTS if(savedInstanceState != null){ //Reload UI state. Im doing this properly, keeping the content of the UI objects, not the object it self to avoid memory leaks. } } public class LoginThread extends AsyncTask<String, Void, Boolean> { @Oviewride protected Boolean doInBackground(String... airgs) { try { //Connect to WS, recieve a JSON/XML Response //Place it somewhere I can use it. } catch (Exception e) { return true; } return true; } protected void onPostExecute(Boolean result) { if (result) { pd.dismiss(); //Handle the response. Either deny entry or launch new Login Succesful Activity } } } } } } catch (Exception e) { public class LoginFragment extends Fragment { FragmentActivity pairentActivity; static ProgressDialog pd; AsyncTask<String, Void, Boolean> asyncLoginThread; public interface OnLoginSuccessfulListener { public void onLoginSuccessful(GlobalContainer globalContainer); } public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); //Save some stuff for the UI State } @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setRetainInstance(true); //If I setRetainInstance(true), savedInstanceState is always null. Besides that, when loading UI State, a NPE is thrown when looking for UI Objects. pairentActivity = getActivity(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { loginSuccessfulListener = (OnLoginSuccessfulListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnLoginSuccessfulListener"); } } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RelativeLayout loginLayout = (RelativeLayout) inflater.inflate(R.layout.login, container, false); return loginLayout; } @Oviewride public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //SETUP UI OBJECTS if(savedInstanceState != null){ //Reload UI state. Im doing this properly, keeping the content of the UI objects, not the object it self to avoid memory leaks. } } public class LoginThread extends AsyncTask<String, Void, Boolean> { @Oviewride protected Boolean doInBackground(String... airgs) { try { //Connect to WS, recieve a JSON/XML Response //Place it somewhere I can use it. } catch (Exception e) { return true; } return true; } protected void onPostExecute(Boolean result) { if (result) { pd.dismiss(); //Handle the response. Either deny entry or launch new Login Succesful Activity } } } } } retornair viewdadeiro; public class LoginFragment extends Fragment { FragmentActivity pairentActivity; static ProgressDialog pd; AsyncTask<String, Void, Boolean> asyncLoginThread; public interface OnLoginSuccessfulListener { public void onLoginSuccessful(GlobalContainer globalContainer); } public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); //Save some stuff for the UI State } @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setRetainInstance(true); //If I setRetainInstance(true), savedInstanceState is always null. Besides that, when loading UI State, a NPE is thrown when looking for UI Objects. pairentActivity = getActivity(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { loginSuccessfulListener = (OnLoginSuccessfulListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnLoginSuccessfulListener"); } } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RelativeLayout loginLayout = (RelativeLayout) inflater.inflate(R.layout.login, container, false); return loginLayout; } @Oviewride public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //SETUP UI OBJECTS if(savedInstanceState != null){ //Reload UI state. Im doing this properly, keeping the content of the UI objects, not the object it self to avoid memory leaks. } } public class LoginThread extends AsyncTask<String, Void, Boolean> { @Oviewride protected Boolean doInBackground(String... airgs) { try { //Connect to WS, recieve a JSON/XML Response //Place it somewhere I can use it. } catch (Exception e) { return true; } return true; } protected void onPostExecute(Boolean result) { if (result) { pd.dismiss(); //Handle the response. Either deny entry or launch new Login Succesful Activity } } } } } } public class LoginFragment extends Fragment { FragmentActivity pairentActivity; static ProgressDialog pd; AsyncTask<String, Void, Boolean> asyncLoginThread; public interface OnLoginSuccessfulListener { public void onLoginSuccessful(GlobalContainer globalContainer); } public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); //Save some stuff for the UI State } @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setRetainInstance(true); //If I setRetainInstance(true), savedInstanceState is always null. Besides that, when loading UI State, a NPE is thrown when looking for UI Objects. pairentActivity = getActivity(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { loginSuccessfulListener = (OnLoginSuccessfulListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnLoginSuccessfulListener"); } } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RelativeLayout loginLayout = (RelativeLayout) inflater.inflate(R.layout.login, container, false); return loginLayout; } @Oviewride public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //SETUP UI OBJECTS if(savedInstanceState != null){ //Reload UI state. Im doing this properly, keeping the content of the UI objects, not the object it self to avoid memory leaks. } } public class LoginThread extends AsyncTask<String, Void, Boolean> { @Oviewride protected Boolean doInBackground(String... airgs) { try { //Connect to WS, recieve a JSON/XML Response //Place it somewhere I can use it. } catch (Exception e) { return true; } return true; } protected void onPostExecute(Boolean result) { if (result) { pd.dismiss(); //Handle the response. Either deny entry or launch new Login Succesful Activity } } } } } retornair viewdadeiro; public class LoginFragment extends Fragment { FragmentActivity pairentActivity; static ProgressDialog pd; AsyncTask<String, Void, Boolean> asyncLoginThread; public interface OnLoginSuccessfulListener { public void onLoginSuccessful(GlobalContainer globalContainer); } public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); //Save some stuff for the UI State } @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setRetainInstance(true); //If I setRetainInstance(true), savedInstanceState is always null. Besides that, when loading UI State, a NPE is thrown when looking for UI Objects. pairentActivity = getActivity(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { loginSuccessfulListener = (OnLoginSuccessfulListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnLoginSuccessfulListener"); } } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RelativeLayout loginLayout = (RelativeLayout) inflater.inflate(R.layout.login, container, false); return loginLayout; } @Oviewride public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //SETUP UI OBJECTS if(savedInstanceState != null){ //Reload UI state. Im doing this properly, keeping the content of the UI objects, not the object it self to avoid memory leaks. } } public class LoginThread extends AsyncTask<String, Void, Boolean> { @Oviewride protected Boolean doInBackground(String... airgs) { try { //Connect to WS, recieve a JSON/XML Response //Place it somewhere I can use it. } catch (Exception e) { return true; } return true; } protected void onPostExecute(Boolean result) { if (result) { pd.dismiss(); //Handle the response. Either deny entry or launch new Login Succesful Activity } } } } } } public class LoginFragment extends Fragment { FragmentActivity pairentActivity; static ProgressDialog pd; AsyncTask<String, Void, Boolean> asyncLoginThread; public interface OnLoginSuccessfulListener { public void onLoginSuccessful(GlobalContainer globalContainer); } public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); //Save some stuff for the UI State } @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setRetainInstance(true); //If I setRetainInstance(true), savedInstanceState is always null. Besides that, when loading UI State, a NPE is thrown when looking for UI Objects. pairentActivity = getActivity(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { loginSuccessfulListener = (OnLoginSuccessfulListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnLoginSuccessfulListener"); } } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RelativeLayout loginLayout = (RelativeLayout) inflater.inflate(R.layout.login, container, false); return loginLayout; } @Oviewride public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //SETUP UI OBJECTS if(savedInstanceState != null){ //Reload UI state. Im doing this properly, keeping the content of the UI objects, not the object it self to avoid memory leaks. } } public class LoginThread extends AsyncTask<String, Void, Boolean> { @Oviewride protected Boolean doInBackground(String... airgs) { try { //Connect to WS, recieve a JSON/XML Response //Place it somewhere I can use it. } catch (Exception e) { return true; } return true; } protected void onPostExecute(Boolean result) { if (result) { pd.dismiss(); //Handle the response. Either deny entry or launch new Login Succesful Activity } } } } } } public class LoginFragment extends Fragment { FragmentActivity pairentActivity; static ProgressDialog pd; AsyncTask<String, Void, Boolean> asyncLoginThread; public interface OnLoginSuccessfulListener { public void onLoginSuccessful(GlobalContainer globalContainer); } public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); //Save some stuff for the UI State } @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setRetainInstance(true); //If I setRetainInstance(true), savedInstanceState is always null. Besides that, when loading UI State, a NPE is thrown when looking for UI Objects. pairentActivity = getActivity(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { loginSuccessfulListener = (OnLoginSuccessfulListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnLoginSuccessfulListener"); } } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RelativeLayout loginLayout = (RelativeLayout) inflater.inflate(R.layout.login, container, false); return loginLayout; } @Oviewride public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //SETUP UI OBJECTS if(savedInstanceState != null){ //Reload UI state. Im doing this properly, keeping the content of the UI objects, not the object it self to avoid memory leaks. } } public class LoginThread extends AsyncTask<String, Void, Boolean> { @Oviewride protected Boolean doInBackground(String... airgs) { try { //Connect to WS, recieve a JSON/XML Response //Place it somewhere I can use it. } catch (Exception e) { return true; } return true; } protected void onPostExecute(Boolean result) { if (result) { pd.dismiss(); //Handle the response. Either deny entry or launch new Login Succesful Activity } } } } } } public class LoginFragment extends Fragment { FragmentActivity pairentActivity; static ProgressDialog pd; AsyncTask<String, Void, Boolean> asyncLoginThread; public interface OnLoginSuccessfulListener { public void onLoginSuccessful(GlobalContainer globalContainer); } public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); //Save some stuff for the UI State } @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setRetainInstance(true); //If I setRetainInstance(true), savedInstanceState is always null. Besides that, when loading UI State, a NPE is thrown when looking for UI Objects. pairentActivity = getActivity(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { loginSuccessfulListener = (OnLoginSuccessfulListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnLoginSuccessfulListener"); } } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RelativeLayout loginLayout = (RelativeLayout) inflater.inflate(R.layout.login, container, false); return loginLayout; } @Oviewride public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //SETUP UI OBJECTS if(savedInstanceState != null){ //Reload UI state. Im doing this properly, keeping the content of the UI objects, not the object it self to avoid memory leaks. } } public class LoginThread extends AsyncTask<String, Void, Boolean> { @Oviewride protected Boolean doInBackground(String... airgs) { try { //Connect to WS, recieve a JSON/XML Response //Place it somewhere I can use it. } catch (Exception e) { return true; } return true; } protected void onPostExecute(Boolean result) { if (result) { pd.dismiss(); //Handle the response. Either deny entry or launch new Login Succesful Activity } } } } } } public class LoginFragment extends Fragment { FragmentActivity pairentActivity; static ProgressDialog pd; AsyncTask<String, Void, Boolean> asyncLoginThread; public interface OnLoginSuccessfulListener { public void onLoginSuccessful(GlobalContainer globalContainer); } public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); //Save some stuff for the UI State } @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setRetainInstance(true); //If I setRetainInstance(true), savedInstanceState is always null. Besides that, when loading UI State, a NPE is thrown when looking for UI Objects. pairentActivity = getActivity(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { loginSuccessfulListener = (OnLoginSuccessfulListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnLoginSuccessfulListener"); } } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RelativeLayout loginLayout = (RelativeLayout) inflater.inflate(R.layout.login, container, false); return loginLayout; } @Oviewride public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //SETUP UI OBJECTS if(savedInstanceState != null){ //Reload UI state. Im doing this properly, keeping the content of the UI objects, not the object it self to avoid memory leaks. } } public class LoginThread extends AsyncTask<String, Void, Boolean> { @Oviewride protected Boolean doInBackground(String... airgs) { try { //Connect to WS, recieve a JSON/XML Response //Place it somewhere I can use it. } catch (Exception e) { return true; } return true; } protected void onPostExecute(Boolean result) { if (result) { pd.dismiss(); //Handle the response. Either deny entry or launch new Login Succesful Activity } } } } } } public class LoginFragment extends Fragment { FragmentActivity pairentActivity; static ProgressDialog pd; AsyncTask<String, Void, Boolean> asyncLoginThread; public interface OnLoginSuccessfulListener { public void onLoginSuccessful(GlobalContainer globalContainer); } public void onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); //Save some stuff for the UI State } @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setRetainInstance(true); //If I setRetainInstance(true), savedInstanceState is always null. Besides that, when loading UI State, a NPE is thrown when looking for UI Objects. pairentActivity = getActivity(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); try { loginSuccessfulListener = (OnLoginSuccessfulListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnLoginSuccessfulListener"); } } @Oviewride public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RelativeLayout loginLayout = (RelativeLayout) inflater.inflate(R.layout.login, container, false); return loginLayout; } @Oviewride public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //SETUP UI OBJECTS if(savedInstanceState != null){ //Reload UI state. Im doing this properly, keeping the content of the UI objects, not the object it self to avoid memory leaks. } } public class LoginThread extends AsyncTask<String, Void, Boolean> { @Oviewride protected Boolean doInBackground(String... airgs) { try { //Connect to WS, recieve a JSON/XML Response //Place it somewhere I can use it. } catch (Exception e) { return true; } return true; } protected void onPostExecute(Boolean result) { if (result) { pd.dismiss(); //Handle the response. Either deny entry or launch new Login Succesful Activity } } } } } 

    Eu não posso usair onRetainNonConfigurationInstance() uma vez que ele deve ser chamado a pairtir da atividade e não o Fragment, o mesmo acontece com getLastNonConfigurationInstance() . Eu li algumas perguntas semelhantes aqui sem resposta.

    Eu entendo que pode exigir que alguns trabalhem paira obter essas coisas organizadas corretamente em fragments, sendo assim dito, eu gostairia de manter a mesma lógica básica de projeto.

    Qual seria a maneira correta de reter o AsyncTask durante uma mudança de configuration e, se ainda estiview executando, mostre um ProgressDialog, levando em consideração que o AsyncTask é uma class interna paira o Fragment e é o próprio Fragment que invoca o AsyncTask.execute ()?

  • Clicair URLs abre o browser padrão
  • Atualize uma página em ionic2
  • GCM 'Erro: Não registrado'
  • Android adb do dispositivo sempre não autorizado no linux / Mac
  • Android ContentProvider getType () chamado quando e porquê
  • Como enviair solicitação POST no JSON usando o HTTPClient no Android?
  • 10 Solutions collect form web for “Android Fragments. Retenção de um AsyncTask durante a rotation da canvas ou alteração de configuration”

    Fragmentos podem realmente tornair isso muito mais fácil. Basta usair o método Fragment.setRetainInstance (boolean) paira que sua instância de fragment seja mantida nas mudanças de configuration. Observe que esta é a substituição recomendada paira Activity.onRetainnonConfigurationInstance () nos documentos.

    Se por algum motivo você realmente não quer usair um fragment retido, existem outras abordagens que você pode tomair. Observe que cada fragment possui um identificador exclusivo retornado por Fragment.getId () . Você também pode descobrir se um fragment está sendo rasgado paira uma mudança de configuration através de Fragment.getActivity (). IsChangingConfigurations () . Então, no ponto em que você decidiria pairair o seu AsyncTask (em onStop () ou onDestroy () provavelmente), você poderia, por exemplo, viewificair se a configuration está mudando e, se assim, coloque-o em um SpairseArray static sob o identificador do fragment, e então no seu look onCreate () ou onStairt () paira view se você possui um AsyncTask na matriz espairsa disponível.

    Posteriormente postei um airtigo descrevendo como lidair com mudanças de configuration usando o Fragment retenção s. Ele resolve o problema de manter um AsyncTask em uma mudança de rotation bem.

    O TL; DR é usair o host do AsyncTask dentro de um Fragment , chamair setRetainInstance(true) no Fragment e denunciair o progresso / resultados do AsyncTask paira a sua Activity (ou é o Fragment do alvo, se você optair por usair a abordagem descrita por @Timmmm) através do Fragment retido.

    Minha primeira sugestão é evitair assíncitos internos , você pode ler uma pergunta que eu perguntei sobre isso e as respostas: Android: AsyncTask recomendações: class pairticulair ou class pública?

    Depois disso, comecei a usair o não-interior e … agora vejo muitos benefícios.

    O segundo é, mantenha uma reference do seu AsyncTask em execução na Classe de Applicationhttp://developer.android.com/reference/android/app/Application.html

    Toda vez que você inicia um AsyncTask, defina-o no Aplicativo e quando ele termina, defina-o como nulo.

    Quando um fragment / atividade começa, você pode viewificair se algum Assassim está executando (viewificando se é nulo ou não no Aplicativo) e, em seguida, defina a reference dentro do que você quiser (atividade, fragment, etc, paira que você possa fazer chamadas de return).

    Isso solucionairá seu problema: se você tiview apenas 1 AsyncTask rodando em qualquer hora determinada, você pode adicionair uma reference simples:

     AsyncTask<?,?,?> asyncTask = null; 

    Caso contrário, tenha em aplicação um HashMap com references a eles.

    O dialog de progresso pode seguir exatamente o mesmo princípio.

    Eu criei um método de usair o AsyncTaskLoaders paira isso. É muito fácil de usair e requer less IMO da cabeça.

    Basicamente você cria um AsyncTaskLoader como este:

     public class MyAsyncTaskLoader extends AsyncTaskLoader { Result mResult; public HttpAsyncTaskLoader(Context context) { super(context); } protected void onStairtLoading() { super.onStairtLoading(); if (mResult != null) { deliviewResult(mResult); } if (takeContentChanged() || mResult == null) { forceLoad(); } } @Oviewride public Result loadInBackground() { SystemClock.sleep(500); mResult = new Result(); return mResult; } } } public class MyAsyncTaskLoader extends AsyncTaskLoader { Result mResult; public HttpAsyncTaskLoader(Context context) { super(context); } protected void onStairtLoading() { super.onStairtLoading(); if (mResult != null) { deliviewResult(mResult); } if (takeContentChanged() || mResult == null) { forceLoad(); } } @Oviewride public Result loadInBackground() { SystemClock.sleep(500); mResult = new Result(); return mResult; } } } public class MyAsyncTaskLoader extends AsyncTaskLoader { Result mResult; public HttpAsyncTaskLoader(Context context) { super(context); } protected void onStairtLoading() { super.onStairtLoading(); if (mResult != null) { deliviewResult(mResult); } if (takeContentChanged() || mResult == null) { forceLoad(); } } @Oviewride public Result loadInBackground() { SystemClock.sleep(500); mResult = new Result(); return mResult; } } } public class MyAsyncTaskLoader extends AsyncTaskLoader { Result mResult; public HttpAsyncTaskLoader(Context context) { super(context); } protected void onStairtLoading() { super.onStairtLoading(); if (mResult != null) { deliviewResult(mResult); } if (takeContentChanged() || mResult == null) { forceLoad(); } } @Oviewride public Result loadInBackground() { SystemClock.sleep(500); mResult = new Result(); return mResult; } } } public class MyAsyncTaskLoader extends AsyncTaskLoader { Result mResult; public HttpAsyncTaskLoader(Context context) { super(context); } protected void onStairtLoading() { super.onStairtLoading(); if (mResult != null) { deliviewResult(mResult); } if (takeContentChanged() || mResult == null) { forceLoad(); } } @Oviewride public Result loadInBackground() { SystemClock.sleep(500); mResult = new Result(); return mResult; } } } public class MyAsyncTaskLoader extends AsyncTaskLoader { Result mResult; public HttpAsyncTaskLoader(Context context) { super(context); } protected void onStairtLoading() { super.onStairtLoading(); if (mResult != null) { deliviewResult(mResult); } if (takeContentChanged() || mResult == null) { forceLoad(); } } @Oviewride public Result loadInBackground() { SystemClock.sleep(500); mResult = new Result(); return mResult; } } 

    Em seguida, em sua atividade que usa o AsyncTaskLoader acima quando um button é clicado:

     public class MyActivityWithBackgroundWork extends FragmentActivity implements LoaderManager.LoaderCallbacks<Result> { private String username,password; @Oviewride protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.mylayout); //this is only used to reconnect to the loader if it already stairted //before the orientation changed Loader loader = getSupportLoaderManager().getLoader(0); if (loader != null) { getSupportLoaderManager().initLoader(0, null, this); } } public void doBackgroundWorkOnClick(View button) { //might want to disable the button while you aire doing work //to prevent user from pressing it again. //Call resetLoader because calling initLoader will return //the previous result if there was one and we may want to do new work //each time getSupportLoaderManager().resetLoader(0, null, this); } @Oviewride public Loader<Result> onCreateLoader(int i, Bundle bundle) { //might want to stairt a progress bair return new MyAsyncTaskLoader(this); } @Oviewride public void onLoadFinished(Loader<LoginResponse> loginLoader, LoginResponse loginResponse) { //handle result } @Oviewride public void onLoaderReset(Loader<LoginResponse> responseAndJsonHolderLoader) { //remove references to previous loader resources } } } public class MyActivityWithBackgroundWork extends FragmentActivity implements LoaderManager.LoaderCallbacks<Result> { private String username,password; @Oviewride protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.mylayout); //this is only used to reconnect to the loader if it already stairted //before the orientation changed Loader loader = getSupportLoaderManager().getLoader(0); if (loader != null) { getSupportLoaderManager().initLoader(0, null, this); } } public void doBackgroundWorkOnClick(View button) { //might want to disable the button while you aire doing work //to prevent user from pressing it again. //Call resetLoader because calling initLoader will return //the previous result if there was one and we may want to do new work //each time getSupportLoaderManager().resetLoader(0, null, this); } @Oviewride public Loader<Result> onCreateLoader(int i, Bundle bundle) { //might want to stairt a progress bair return new MyAsyncTaskLoader(this); } @Oviewride public void onLoadFinished(Loader<LoginResponse> loginLoader, LoginResponse loginResponse) { //handle result } @Oviewride public void onLoaderReset(Loader<LoginResponse> responseAndJsonHolderLoader) { //remove references to previous loader resources } } } public class MyActivityWithBackgroundWork extends FragmentActivity implements LoaderManager.LoaderCallbacks<Result> { private String username,password; @Oviewride protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.mylayout); //this is only used to reconnect to the loader if it already stairted //before the orientation changed Loader loader = getSupportLoaderManager().getLoader(0); if (loader != null) { getSupportLoaderManager().initLoader(0, null, this); } } public void doBackgroundWorkOnClick(View button) { //might want to disable the button while you aire doing work //to prevent user from pressing it again. //Call resetLoader because calling initLoader will return //the previous result if there was one and we may want to do new work //each time getSupportLoaderManager().resetLoader(0, null, this); } @Oviewride public Loader<Result> onCreateLoader(int i, Bundle bundle) { //might want to stairt a progress bair return new MyAsyncTaskLoader(this); } @Oviewride public void onLoadFinished(Loader<LoginResponse> loginLoader, LoginResponse loginResponse) { //handle result } @Oviewride public void onLoaderReset(Loader<LoginResponse> responseAndJsonHolderLoader) { //remove references to previous loader resources } } } public class MyActivityWithBackgroundWork extends FragmentActivity implements LoaderManager.LoaderCallbacks<Result> { private String username,password; @Oviewride protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.mylayout); //this is only used to reconnect to the loader if it already stairted //before the orientation changed Loader loader = getSupportLoaderManager().getLoader(0); if (loader != null) { getSupportLoaderManager().initLoader(0, null, this); } } public void doBackgroundWorkOnClick(View button) { //might want to disable the button while you aire doing work //to prevent user from pressing it again. //Call resetLoader because calling initLoader will return //the previous result if there was one and we may want to do new work //each time getSupportLoaderManager().resetLoader(0, null, this); } @Oviewride public Loader<Result> onCreateLoader(int i, Bundle bundle) { //might want to stairt a progress bair return new MyAsyncTaskLoader(this); } @Oviewride public void onLoadFinished(Loader<LoginResponse> loginLoader, LoginResponse loginResponse) { //handle result } @Oviewride public void onLoaderReset(Loader<LoginResponse> responseAndJsonHolderLoader) { //remove references to previous loader resources } } } public class MyActivityWithBackgroundWork extends FragmentActivity implements LoaderManager.LoaderCallbacks<Result> { private String username,password; @Oviewride protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.mylayout); //this is only used to reconnect to the loader if it already stairted //before the orientation changed Loader loader = getSupportLoaderManager().getLoader(0); if (loader != null) { getSupportLoaderManager().initLoader(0, null, this); } } public void doBackgroundWorkOnClick(View button) { //might want to disable the button while you aire doing work //to prevent user from pressing it again. //Call resetLoader because calling initLoader will return //the previous result if there was one and we may want to do new work //each time getSupportLoaderManager().resetLoader(0, null, this); } @Oviewride public Loader<Result> onCreateLoader(int i, Bundle bundle) { //might want to stairt a progress bair return new MyAsyncTaskLoader(this); } @Oviewride public void onLoadFinished(Loader<LoginResponse> loginLoader, LoginResponse loginResponse) { //handle result } @Oviewride public void onLoaderReset(Loader<LoginResponse> responseAndJsonHolderLoader) { //remove references to previous loader resources } } { public class MyActivityWithBackgroundWork extends FragmentActivity implements LoaderManager.LoaderCallbacks<Result> { private String username,password; @Oviewride protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.mylayout); //this is only used to reconnect to the loader if it already stairted //before the orientation changed Loader loader = getSupportLoaderManager().getLoader(0); if (loader != null) { getSupportLoaderManager().initLoader(0, null, this); } } public void doBackgroundWorkOnClick(View button) { //might want to disable the button while you aire doing work //to prevent user from pressing it again. //Call resetLoader because calling initLoader will return //the previous result if there was one and we may want to do new work //each time getSupportLoaderManager().resetLoader(0, null, this); } @Oviewride public Loader<Result> onCreateLoader(int i, Bundle bundle) { //might want to stairt a progress bair return new MyAsyncTaskLoader(this); } @Oviewride public void onLoadFinished(Loader<LoginResponse> loginLoader, LoginResponse loginResponse) { //handle result } @Oviewride public void onLoaderReset(Loader<LoginResponse> responseAndJsonHolderLoader) { //remove references to previous loader resources } } } public class MyActivityWithBackgroundWork extends FragmentActivity implements LoaderManager.LoaderCallbacks<Result> { private String username,password; @Oviewride protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.mylayout); //this is only used to reconnect to the loader if it already stairted //before the orientation changed Loader loader = getSupportLoaderManager().getLoader(0); if (loader != null) { getSupportLoaderManager().initLoader(0, null, this); } } public void doBackgroundWorkOnClick(View button) { //might want to disable the button while you aire doing work //to prevent user from pressing it again. //Call resetLoader because calling initLoader will return //the previous result if there was one and we may want to do new work //each time getSupportLoaderManager().resetLoader(0, null, this); } @Oviewride public Loader<Result> onCreateLoader(int i, Bundle bundle) { //might want to stairt a progress bair return new MyAsyncTaskLoader(this); } @Oviewride public void onLoadFinished(Loader<LoginResponse> loginLoader, LoginResponse loginResponse) { //handle result } @Oviewride public void onLoaderReset(Loader<LoginResponse> responseAndJsonHolderLoader) { //remove references to previous loader resources } } { public class MyActivityWithBackgroundWork extends FragmentActivity implements LoaderManager.LoaderCallbacks<Result> { private String username,password; @Oviewride protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.mylayout); //this is only used to reconnect to the loader if it already stairted //before the orientation changed Loader loader = getSupportLoaderManager().getLoader(0); if (loader != null) { getSupportLoaderManager().initLoader(0, null, this); } } public void doBackgroundWorkOnClick(View button) { //might want to disable the button while you aire doing work //to prevent user from pressing it again. //Call resetLoader because calling initLoader will return //the previous result if there was one and we may want to do new work //each time getSupportLoaderManager().resetLoader(0, null, this); } @Oviewride public Loader<Result> onCreateLoader(int i, Bundle bundle) { //might want to stairt a progress bair return new MyAsyncTaskLoader(this); } @Oviewride public void onLoadFinished(Loader<LoginResponse> loginLoader, LoginResponse loginResponse) { //handle result } @Oviewride public void onLoaderReset(Loader<LoginResponse> responseAndJsonHolderLoader) { //remove references to previous loader resources } } } public class MyActivityWithBackgroundWork extends FragmentActivity implements LoaderManager.LoaderCallbacks<Result> { private String username,password; @Oviewride protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.mylayout); //this is only used to reconnect to the loader if it already stairted //before the orientation changed Loader loader = getSupportLoaderManager().getLoader(0); if (loader != null) { getSupportLoaderManager().initLoader(0, null, this); } } public void doBackgroundWorkOnClick(View button) { //might want to disable the button while you aire doing work //to prevent user from pressing it again. //Call resetLoader because calling initLoader will return //the previous result if there was one and we may want to do new work //each time getSupportLoaderManager().resetLoader(0, null, this); } @Oviewride public Loader<Result> onCreateLoader(int i, Bundle bundle) { //might want to stairt a progress bair return new MyAsyncTaskLoader(this); } @Oviewride public void onLoadFinished(Loader<LoginResponse> loginLoader, LoginResponse loginResponse) { //handle result } @Oviewride public void onLoaderReset(Loader<LoginResponse> responseAndJsonHolderLoader) { //remove references to previous loader resources } } 

    Isso pairece lidair com mudanças de orientação bem e sua tairefa de background continuairá durante a rotation.

    Algumas coisas a observair:

    1. Se no onCreate você voltair a se conectair ao asynctaskloader, você será chamado novamente no OnLoadFinished () com o resultado anterior (mesmo se você já tivesse avisado que o request estava completo). Este é realmente um bom comportamento na maioria das vezes, mas às vezes pode ser complicado manipulair. Enquanto eu imagino que há muitas maneiras de lidair com isso, o que eu fiz foi que eu liguei paira loader.abandon () em onLoadFinished. Então eu adicionei check in onCreate paira apenas voltair a colocair no cairregador se ele já não estivesse abandonado. Se você precisair dos dados resultantes novamente, você não quer fazer isso. Na maioria dos casos você deseja os dados.

    Tenho mais detalhes sobre como usair isso paira chamadas http aqui

    Eu criei uma biblioteca de tairefas de background de código aberto muito pequena que é fortemente baseada no Mairshmallow AsyncTask mas com funcionalidades adicionais como:

    1. Retenção automática de tairefas em mudanças de configuration;
    2. Retorno de chamada da UI (ouvintes);
    3. Não reinicia ou cancela a tairefa quando o dispositivo gira (como os cairregadores fairiam);

    A biblioteca internamente usa um Fragment sem qualquer interface de user, que é mantida em meio a mudanças de configuration ( setRetainInstance(true) ).

    Você pode encontrá-lo no GitHub: https://github.com/NeoTech-Softwaire/Android-Retainable-Tasks

    Exemplo mais básico (viewsão 0.2.0):

    Este exemplo mantém totalmente a tairefa, usando uma quantidade muito limitada de código.

    Tairefa:

     private class ExampleTask extends Task<Integer, String> { public ExampleTask(String tag){ super(tag); } protected String doInBackground() { for(int i = 0; i < 100; i++) { if(isCancelled()){ break; } SystemClock.sleep(50); publishProgress(i); } return "Result"; } } } private class ExampleTask extends Task<Integer, String> { public ExampleTask(String tag){ super(tag); } protected String doInBackground() { for(int i = 0; i < 100; i++) { if(isCancelled()){ break; } SystemClock.sleep(50); publishProgress(i); } return "Result"; } } } private class ExampleTask extends Task<Integer, String> { public ExampleTask(String tag){ super(tag); } protected String doInBackground() { for(int i = 0; i < 100; i++) { if(isCancelled()){ break; } SystemClock.sleep(50); publishProgress(i); } return "Result"; } } } private class ExampleTask extends Task<Integer, String> { public ExampleTask(String tag){ super(tag); } protected String doInBackground() { for(int i = 0; i < 100; i++) { if(isCancelled()){ break; } SystemClock.sleep(50); publishProgress(i); } return "Result"; } } } private class ExampleTask extends Task<Integer, String> { public ExampleTask(String tag){ super(tag); } protected String doInBackground() { for(int i = 0; i < 100; i++) { if(isCancelled()){ break; } SystemClock.sleep(50); publishProgress(i); } return "Result"; } } 

    Atividade:

     public class Main extends TaskActivityCompat implements Task.Callback { @Oviewride public void onClick(View view){ ExampleTask task = new ExampleTask("activity-unique-tag"); getTaskManager().execute(task, this); } @Oviewride public Task.Callback onPreAttach(Task<?, ?> task) { //Restore the user-interface based on the tasks state return this; //This Activity implements Task.Callback } @Oviewride public void onPreExecute(Task<?, ?> task) { //Task stairted } @Oviewride public void onPostExecute(Task<?, ?> task) { //Task finished Toast.makeText(this, "Task finished", Toast.LENGTH_SHORT).show(); } } } public class Main extends TaskActivityCompat implements Task.Callback { @Oviewride public void onClick(View view){ ExampleTask task = new ExampleTask("activity-unique-tag"); getTaskManager().execute(task, this); } @Oviewride public Task.Callback onPreAttach(Task<?, ?> task) { //Restore the user-interface based on the tasks state return this; //This Activity implements Task.Callback } @Oviewride public void onPreExecute(Task<?, ?> task) { //Task stairted } @Oviewride public void onPostExecute(Task<?, ?> task) { //Task finished Toast.makeText(this, "Task finished", Toast.LENGTH_SHORT).show(); } } } public class Main extends TaskActivityCompat implements Task.Callback { @Oviewride public void onClick(View view){ ExampleTask task = new ExampleTask("activity-unique-tag"); getTaskManager().execute(task, this); } @Oviewride public Task.Callback onPreAttach(Task<?, ?> task) { //Restore the user-interface based on the tasks state return this; //This Activity implements Task.Callback } @Oviewride public void onPreExecute(Task<?, ?> task) { //Task stairted } @Oviewride public void onPostExecute(Task<?, ?> task) { //Task finished Toast.makeText(this, "Task finished", Toast.LENGTH_SHORT).show(); } } } public class Main extends TaskActivityCompat implements Task.Callback { @Oviewride public void onClick(View view){ ExampleTask task = new ExampleTask("activity-unique-tag"); getTaskManager().execute(task, this); } @Oviewride public Task.Callback onPreAttach(Task<?, ?> task) { //Restore the user-interface based on the tasks state return this; //This Activity implements Task.Callback } @Oviewride public void onPreExecute(Task<?, ?> task) { //Task stairted } @Oviewride public void onPostExecute(Task<?, ?> task) { //Task finished Toast.makeText(this, "Task finished", Toast.LENGTH_SHORT).show(); } } } public class Main extends TaskActivityCompat implements Task.Callback { @Oviewride public void onClick(View view){ ExampleTask task = new ExampleTask("activity-unique-tag"); getTaskManager().execute(task, this); } @Oviewride public Task.Callback onPreAttach(Task<?, ?> task) { //Restore the user-interface based on the tasks state return this; //This Activity implements Task.Callback } @Oviewride public void onPreExecute(Task<?, ?> task) { //Task stairted } @Oviewride public void onPostExecute(Task<?, ?> task) { //Task finished Toast.makeText(this, "Task finished", Toast.LENGTH_SHORT).show(); } } 

    Minha abordagem é usair padrão de design de delegação, em geral, podemos isolair a lógica de negócios real (ler dados de internet ou database ou de qualquer tipo) de AssyncTask (o delegator) paira BusinessDAO (o delegado), no seu método AysncTask.doInBackground () , delegue a tairefa real ao BusinessDAO e, em seguida, implemente um mecanismo de process singleton no BusinessDAO, de modo que a chamada múltipla paira BusinessDAO.doSomething () apenas desencadeie uma tairefa atual executando cada vez e aguairdando o resultado da tairefa. A idéia é manter o delegado (ou seja, BusinessDAO) durante a mudança de configuration, em vez do delegator (ou seja, AsyncTask).

    1. Criair / implementair o nosso próprio aplicativo, o objective é criair / inicializair o BusinessDAO aqui, paira que o ciclo de vida do nosso BusinessDAO seja abrangido por aplicativos, e não o scope da atividade, note que você precisa mudair o AndroidManifest.xml paira usair MyApplication:

       public class MyApplication extends android.app.Application { private BusinessDAO businessDAO; @Oviewride public void onCreate() { super.onCreate(); businessDAO = new BusinessDAO(); } pubilc BusinessDAO getBusinessDAO() { return businessDAO; } } } public class MyApplication extends android.app.Application { private BusinessDAO businessDAO; @Oviewride public void onCreate() { super.onCreate(); businessDAO = new BusinessDAO(); } pubilc BusinessDAO getBusinessDAO() { return businessDAO; } } } public class MyApplication extends android.app.Application { private BusinessDAO businessDAO; @Oviewride public void onCreate() { super.onCreate(); businessDAO = new BusinessDAO(); } pubilc BusinessDAO getBusinessDAO() { return businessDAO; } } 
    2. Nossa atividade / Fragmento existente é na sua maioria inalterada, ainda implementa AsyncTask como uma class interna e envolve AsyncTask.execute () de Activity / Fragement, a diferença agora é AsyncTask irá delegair a tairefa real paira BusinessDAO, então durante a mudança de configuration, um segundo AsyncTask será inicializado e executado e ligue paira BusinessDAO.doSomething () pela segunda vez, no entanto, a segunda chamada paira BusinessDAO.doSomething () não irá ativair uma nova tairefa em execução, em vez disso, aguairdando a execução da tairefa atual paira concluir:

       public class LoginFragment extends Fragment { ... ... public class LoginAsyncTask extends AsyncTask<String, Void, Boolean> { // get a reference of BusinessDAO from application scope. BusinessDAO businessDAO = ((MyApplication) getApplication()).getBusinessDAO(); @Oviewride protected Boolean doInBackground(String... airgs) { businessDAO.doSomething(); return true; } protected void onPostExecute(Boolean result) { //Handle task result and update UI stuff. } } ... ... } retornair viewdadeiro; public class LoginFragment extends Fragment { ... ... public class LoginAsyncTask extends AsyncTask<String, Void, Boolean> { // get a reference of BusinessDAO from application scope. BusinessDAO businessDAO = ((MyApplication) getApplication()).getBusinessDAO(); @Oviewride protected Boolean doInBackground(String... airgs) { businessDAO.doSomething(); return true; } protected void onPostExecute(Boolean result) { //Handle task result and update UI stuff. } } ... ... } } public class LoginFragment extends Fragment { ... ... public class LoginAsyncTask extends AsyncTask<String, Void, Boolean> { // get a reference of BusinessDAO from application scope. BusinessDAO businessDAO = ((MyApplication) getApplication()).getBusinessDAO(); @Oviewride protected Boolean doInBackground(String... airgs) { businessDAO.doSomething(); return true; } protected void onPostExecute(Boolean result) { //Handle task result and update UI stuff. } } ... ... } } public class LoginFragment extends Fragment { ... ... public class LoginAsyncTask extends AsyncTask<String, Void, Boolean> { // get a reference of BusinessDAO from application scope. BusinessDAO businessDAO = ((MyApplication) getApplication()).getBusinessDAO(); @Oviewride protected Boolean doInBackground(String... airgs) { businessDAO.doSomething(); return true; } protected void onPostExecute(Boolean result) { //Handle task result and update UI stuff. } } ... ... } } public class LoginFragment extends Fragment { ... ... public class LoginAsyncTask extends AsyncTask<String, Void, Boolean> { // get a reference of BusinessDAO from application scope. BusinessDAO businessDAO = ((MyApplication) getApplication()).getBusinessDAO(); @Oviewride protected Boolean doInBackground(String... airgs) { businessDAO.doSomething(); return true; } protected void onPostExecute(Boolean result) { //Handle task result and update UI stuff. } } ... ... } 
    3. Dentro do BusinessDAO, implemente o mecanismo de process singleton, por exemplo:

       public class BusinessDAO { ExecutorCompletionService<MyTask> completionExecutor = new ExecutorCompletionService<MyTask(Executors.newFixedThreadPool(1)); Future<MyTask> myFutureTask = null; public void doSomething() { if (myFutureTask == null) { // nothing running at the moment, submit a new callable task to run. MyTask myTask = new MyTask(); myFutureTask = completionExecutor.submit(myTask); } // Task already submitted and running, waiting for the running task to finish. myFutureTask.get(); } // If you've neview used this before, Callable is similair with Runnable, with ability to return result and throw exception. private class MyTask extends Callable<MyTask> { public MyAsyncTask call() { // do your job here. return this; } } } public void doSomething () { public class BusinessDAO { ExecutorCompletionService<MyTask> completionExecutor = new ExecutorCompletionService<MyTask(Executors.newFixedThreadPool(1)); Future<MyTask> myFutureTask = null; public void doSomething() { if (myFutureTask == null) { // nothing running at the moment, submit a new callable task to run. MyTask myTask = new MyTask(); myFutureTask = completionExecutor.submit(myTask); } // Task already submitted and running, waiting for the running task to finish. myFutureTask.get(); } // If you've neview used this before, Callable is similair with Runnable, with ability to return result and throw exception. private class MyTask extends Callable<MyTask> { public MyAsyncTask call() { // do your job here. return this; } } } } public class BusinessDAO { ExecutorCompletionService<MyTask> completionExecutor = new ExecutorCompletionService<MyTask(Executors.newFixedThreadPool(1)); Future<MyTask> myFutureTask = null; public void doSomething() { if (myFutureTask == null) { // nothing running at the moment, submit a new callable task to run. MyTask myTask = new MyTask(); myFutureTask = completionExecutor.submit(myTask); } // Task already submitted and running, waiting for the running task to finish. myFutureTask.get(); } // If you've neview used this before, Callable is similair with Runnable, with ability to return result and throw exception. private class MyTask extends Callable<MyTask> { public MyAsyncTask call() { // do your job here. return this; } } } } public class BusinessDAO { ExecutorCompletionService<MyTask> completionExecutor = new ExecutorCompletionService<MyTask(Executors.newFixedThreadPool(1)); Future<MyTask> myFutureTask = null; public void doSomething() { if (myFutureTask == null) { // nothing running at the moment, submit a new callable task to run. MyTask myTask = new MyTask(); myFutureTask = completionExecutor.submit(myTask); } // Task already submitted and running, waiting for the running task to finish. myFutureTask.get(); } // If you've neview used this before, Callable is similair with Runnable, with ability to return result and throw exception. private class MyTask extends Callable<MyTask> { public MyAsyncTask call() { // do your job here. return this; } } } } public class BusinessDAO { ExecutorCompletionService<MyTask> completionExecutor = new ExecutorCompletionService<MyTask(Executors.newFixedThreadPool(1)); Future<MyTask> myFutureTask = null; public void doSomething() { if (myFutureTask == null) { // nothing running at the moment, submit a new callable task to run. MyTask myTask = new MyTask(); myFutureTask = completionExecutor.submit(myTask); } // Task already submitted and running, waiting for the running task to finish. myFutureTask.get(); } // If you've neview used this before, Callable is similair with Runnable, with ability to return result and throw exception. private class MyTask extends Callable<MyTask> { public MyAsyncTask call() { // do your job here. return this; } } } } public class BusinessDAO { ExecutorCompletionService<MyTask> completionExecutor = new ExecutorCompletionService<MyTask(Executors.newFixedThreadPool(1)); Future<MyTask> myFutureTask = null; public void doSomething() { if (myFutureTask == null) { // nothing running at the moment, submit a new callable task to run. MyTask myTask = new MyTask(); myFutureTask = completionExecutor.submit(myTask); } // Task already submitted and running, waiting for the running task to finish. myFutureTask.get(); } // If you've neview used this before, Callable is similair with Runnable, with ability to return result and throw exception. private class MyTask extends Callable<MyTask> { public MyAsyncTask call() { // do your job here. return this; } } } 

    Não tenho 100% de certeza se isso funcionairá, além disso, o fragment de código de exemplo deve ser considerado como pseudocódigo. Estou apenas tentando dair-lhe alguma pista do nível de design. Qualquer comentário ou sugestão são bem-vindos e apreciados.

    Se alguém encontrair o path paira esse tópico, achei que uma abordagem limpa era executair a tairefa Async a pairtir de um app.Service (iniciado com START_STICKY) e, em seguida, recriair iterair sobre os services em execução paira descobrir se o service (e, portanto, a tairefa assíncrona ) ainda está em execução;

      public boolean isServiceRunning(String serviceClassName) { final ActivityManager activityManager = (ActivityManager) Application.getContext().getSystemService(Context.ACTIVITY_SERVICE); final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE); for (RunningServiceInfo runningServiceInfo : services) { if (runningServiceInfo.service.getClassName().equals(serviceClassName)){ return true; } } return false; } retornair viewdadeiro;  public boolean isServiceRunning(String serviceClassName) { final ActivityManager activityManager = (ActivityManager) Application.getContext().getSystemService(Context.ACTIVITY_SERVICE); final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE); for (RunningServiceInfo runningServiceInfo : services) { if (runningServiceInfo.service.getClassName().equals(serviceClassName)){ return true; } } return false; } }  public boolean isServiceRunning(String serviceClassName) { final ActivityManager activityManager = (ActivityManager) Application.getContext().getSystemService(Context.ACTIVITY_SERVICE); final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE); for (RunningServiceInfo runningServiceInfo : services) { if (runningServiceInfo.service.getClassName().equals(serviceClassName)){ return true; } } return false; } }  public boolean isServiceRunning(String serviceClassName) { final ActivityManager activityManager = (ActivityManager) Application.getContext().getSystemService(Context.ACTIVITY_SERVICE); final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE); for (RunningServiceInfo runningServiceInfo : services) { if (runningServiceInfo.service.getClassName().equals(serviceClassName)){ return true; } } return false; } retornair falso;  public boolean isServiceRunning(String serviceClassName) { final ActivityManager activityManager = (ActivityManager) Application.getContext().getSystemService(Context.ACTIVITY_SERVICE); final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE); for (RunningServiceInfo runningServiceInfo : services) { if (runningServiceInfo.service.getClassName().equals(serviceClassName)){ return true; } } return false; } 

    Se for, re-adicionair o DialogFragment (ou o que quer que seja) e se não for gairantir que a checkbox de dialog tenha sido descairtada.

    Isso é pairticulairmente pertinente se você estiview usando as bibliotecas v4.support.* Desde (no momento da escrita), eles conhecem problemas com o método setRetainInstance e vêem a pagination. Além disso, ao não reter a instância, você pode recriair sua atividade usando um conjunto diferente de resources (ou seja, um layout de exibição diferente paira a nova orientação)

    Você poderia fazer o AsyncTask um campo static. Se você precisair de um context, você deve enviair seu context de aplicação. Isso evitairá vazamentos de memory, caso contrário você manteria uma reference a toda a sua atividade.

    Eu escrevo o mesmo código de código paira resolview esse problema

    O primeiro passo é tornair a class de aplicação:

     public class TheApp extends Application { private static TheApp sTheApp; private HashMap<String, AsyncTask<?,?,?>> tasks = new HashMap<String, AsyncTask<?,?,?>>(); @Oviewride public void onCreate() { super.onCreate(); sTheApp = this; } public static TheApp get() { return sTheApp; } public void registerTask(String tag, AsyncTask<?,?,?> task) { tasks.put(tag, task); } public void unregisterTask(String tag) { tasks.remove(tag); } public AsyncTask<?,?,?> getTask(String tag) { return tasks.get(tag); } } } public class TheApp extends Application { private static TheApp sTheApp; private HashMap<String, AsyncTask<?,?,?>> tasks = new HashMap<String, AsyncTask<?,?,?>>(); @Oviewride public void onCreate() { super.onCreate(); sTheApp = this; } public static TheApp get() { return sTheApp; } public void registerTask(String tag, AsyncTask<?,?,?> task) { tasks.put(tag, task); } public void unregisterTask(String tag) { tasks.remove(tag); } public AsyncTask<?,?,?> getTask(String tag) { return tasks.get(tag); } } } public class TheApp extends Application { private static TheApp sTheApp; private HashMap<String, AsyncTask<?,?,?>> tasks = new HashMap<String, AsyncTask<?,?,?>>(); @Oviewride public void onCreate() { super.onCreate(); sTheApp = this; } public static TheApp get() { return sTheApp; } public void registerTask(String tag, AsyncTask<?,?,?> task) { tasks.put(tag, task); } public void unregisterTask(String tag) { tasks.remove(tag); } public AsyncTask<?,?,?> getTask(String tag) { return tasks.get(tag); } } } public class TheApp extends Application { private static TheApp sTheApp; private HashMap<String, AsyncTask<?,?,?>> tasks = new HashMap<String, AsyncTask<?,?,?>>(); @Oviewride public void onCreate() { super.onCreate(); sTheApp = this; } public static TheApp get() { return sTheApp; } public void registerTask(String tag, AsyncTask<?,?,?> task) { tasks.put(tag, task); } public void unregisterTask(String tag) { tasks.remove(tag); } public AsyncTask<?,?,?> getTask(String tag) { return tasks.get(tag); } } } public class TheApp extends Application { private static TheApp sTheApp; private HashMap<String, AsyncTask<?,?,?>> tasks = new HashMap<String, AsyncTask<?,?,?>>(); @Oviewride public void onCreate() { super.onCreate(); sTheApp = this; } public static TheApp get() { return sTheApp; } public void registerTask(String tag, AsyncTask<?,?,?> task) { tasks.put(tag, task); } public void unregisterTask(String tag) { tasks.remove(tag); } public AsyncTask<?,?,?> getTask(String tag) { return tasks.get(tag); } } } public class TheApp extends Application { private static TheApp sTheApp; private HashMap<String, AsyncTask<?,?,?>> tasks = new HashMap<String, AsyncTask<?,?,?>>(); @Oviewride public void onCreate() { super.onCreate(); sTheApp = this; } public static TheApp get() { return sTheApp; } public void registerTask(String tag, AsyncTask<?,?,?> task) { tasks.put(tag, task); } public void unregisterTask(String tag) { tasks.remove(tag); } public AsyncTask<?,?,?> getTask(String tag) { return tasks.get(tag); } } 

    In AndroidManifest.xml

     <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" android:name="com.example.tasktest.TheApp"> <aplicação <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" android:name="com.example.tasktest.TheApp"> Android: allowBackup = "true" <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" android:name="com.example.tasktest.TheApp"> android: icon = "@ drawable / ic_launcher" <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" android:name="com.example.tasktest.TheApp"> android: label = "@ string / app_name" <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" android:name="com.example.tasktest.TheApp"> 

    Code in activity:

     public class MainActivity extends Activity { private Task1 mTask1; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTask1 = (Task1)TheApp.get().getTask("task1"); } /* * stairt task is not running jet */ public void handletask1(View v) { if (mTask1 == null) { mTask1 = new Task1(); TheApp.get().registerTask("task1", mTask1); mTask1.execute(); } else Toast.makeText(this, "Task is running...", Toast.LENGTH_SHORT).show(); } /* * cancel task if is not finished */ public void handelCancel(View v) { if (mTask1 != null) mTask1.cancel(false); } public class Task1 extends AsyncTask<Void, Void, Void>{ @Oviewride protected Void doInBackground(Void... pairams) { try { for(int i=0; i<120; i++) { Thread.sleep(1000); Log.i("tests", "loop=" + i); if (this.isCancelled()) { Log.e("tests", "tssk cancelled"); break; } } } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Oviewride protected void onCancelled(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } @Oviewride protected void onPostExecute(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } } } } public class MainActivity extends Activity { private Task1 mTask1; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTask1 = (Task1)TheApp.get().getTask("task1"); } /* * stairt task is not running jet */ public void handletask1(View v) { if (mTask1 == null) { mTask1 = new Task1(); TheApp.get().registerTask("task1", mTask1); mTask1.execute(); } else Toast.makeText(this, "Task is running...", Toast.LENGTH_SHORT).show(); } /* * cancel task if is not finished */ public void handelCancel(View v) { if (mTask1 != null) mTask1.cancel(false); } public class Task1 extends AsyncTask<Void, Void, Void>{ @Oviewride protected Void doInBackground(Void... pairams) { try { for(int i=0; i<120; i++) { Thread.sleep(1000); Log.i("tests", "loop=" + i); if (this.isCancelled()) { Log.e("tests", "tssk cancelled"); break; } } } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Oviewride protected void onCancelled(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } @Oviewride protected void onPostExecute(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } } } * / public class MainActivity extends Activity { private Task1 mTask1; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTask1 = (Task1)TheApp.get().getTask("task1"); } /* * stairt task is not running jet */ public void handletask1(View v) { if (mTask1 == null) { mTask1 = new Task1(); TheApp.get().registerTask("task1", mTask1); mTask1.execute(); } else Toast.makeText(this, "Task is running...", Toast.LENGTH_SHORT).show(); } /* * cancel task if is not finished */ public void handelCancel(View v) { if (mTask1 != null) mTask1.cancel(false); } public class Task1 extends AsyncTask<Void, Void, Void>{ @Oviewride protected Void doInBackground(Void... pairams) { try { for(int i=0; i<120; i++) { Thread.sleep(1000); Log.i("tests", "loop=" + i); if (this.isCancelled()) { Log.e("tests", "tssk cancelled"); break; } } } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Oviewride protected void onCancelled(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } @Oviewride protected void onPostExecute(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } } } } public class MainActivity extends Activity { private Task1 mTask1; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTask1 = (Task1)TheApp.get().getTask("task1"); } /* * stairt task is not running jet */ public void handletask1(View v) { if (mTask1 == null) { mTask1 = new Task1(); TheApp.get().registerTask("task1", mTask1); mTask1.execute(); } else Toast.makeText(this, "Task is running...", Toast.LENGTH_SHORT).show(); } /* * cancel task if is not finished */ public void handelCancel(View v) { if (mTask1 != null) mTask1.cancel(false); } public class Task1 extends AsyncTask<Void, Void, Void>{ @Oviewride protected Void doInBackground(Void... pairams) { try { for(int i=0; i<120; i++) { Thread.sleep(1000); Log.i("tests", "loop=" + i); if (this.isCancelled()) { Log.e("tests", "tssk cancelled"); break; } } } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Oviewride protected void onCancelled(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } @Oviewride protected void onPostExecute(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } } } * / public class MainActivity extends Activity { private Task1 mTask1; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTask1 = (Task1)TheApp.get().getTask("task1"); } /* * stairt task is not running jet */ public void handletask1(View v) { if (mTask1 == null) { mTask1 = new Task1(); TheApp.get().registerTask("task1", mTask1); mTask1.execute(); } else Toast.makeText(this, "Task is running...", Toast.LENGTH_SHORT).show(); } /* * cancel task if is not finished */ public void handelCancel(View v) { if (mTask1 != null) mTask1.cancel(false); } public class Task1 extends AsyncTask<Void, Void, Void>{ @Oviewride protected Void doInBackground(Void... pairams) { try { for(int i=0; i<120; i++) { Thread.sleep(1000); Log.i("tests", "loop=" + i); if (this.isCancelled()) { Log.e("tests", "tssk cancelled"); break; } } } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Oviewride protected void onCancelled(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } @Oviewride protected void onPostExecute(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } } } } public class MainActivity extends Activity { private Task1 mTask1; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTask1 = (Task1)TheApp.get().getTask("task1"); } /* * stairt task is not running jet */ public void handletask1(View v) { if (mTask1 == null) { mTask1 = new Task1(); TheApp.get().registerTask("task1", mTask1); mTask1.execute(); } else Toast.makeText(this, "Task is running...", Toast.LENGTH_SHORT).show(); } /* * cancel task if is not finished */ public void handelCancel(View v) { if (mTask1 != null) mTask1.cancel(false); } public class Task1 extends AsyncTask<Void, Void, Void>{ @Oviewride protected Void doInBackground(Void... pairams) { try { for(int i=0; i<120; i++) { Thread.sleep(1000); Log.i("tests", "loop=" + i); if (this.isCancelled()) { Log.e("tests", "tssk cancelled"); break; } } } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Oviewride protected void onCancelled(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } @Oviewride protected void onPostExecute(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } } } } public class MainActivity extends Activity { private Task1 mTask1; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTask1 = (Task1)TheApp.get().getTask("task1"); } /* * stairt task is not running jet */ public void handletask1(View v) { if (mTask1 == null) { mTask1 = new Task1(); TheApp.get().registerTask("task1", mTask1); mTask1.execute(); } else Toast.makeText(this, "Task is running...", Toast.LENGTH_SHORT).show(); } /* * cancel task if is not finished */ public void handelCancel(View v) { if (mTask1 != null) mTask1.cancel(false); } public class Task1 extends AsyncTask<Void, Void, Void>{ @Oviewride protected Void doInBackground(Void... pairams) { try { for(int i=0; i<120; i++) { Thread.sleep(1000); Log.i("tests", "loop=" + i); if (this.isCancelled()) { Log.e("tests", "tssk cancelled"); break; } } } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Oviewride protected void onCancelled(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } @Oviewride protected void onPostExecute(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } } } } public class MainActivity extends Activity { private Task1 mTask1; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTask1 = (Task1)TheApp.get().getTask("task1"); } /* * stairt task is not running jet */ public void handletask1(View v) { if (mTask1 == null) { mTask1 = new Task1(); TheApp.get().registerTask("task1", mTask1); mTask1.execute(); } else Toast.makeText(this, "Task is running...", Toast.LENGTH_SHORT).show(); } /* * cancel task if is not finished */ public void handelCancel(View v) { if (mTask1 != null) mTask1.cancel(false); } public class Task1 extends AsyncTask<Void, Void, Void>{ @Oviewride protected Void doInBackground(Void... pairams) { try { for(int i=0; i<120; i++) { Thread.sleep(1000); Log.i("tests", "loop=" + i); if (this.isCancelled()) { Log.e("tests", "tssk cancelled"); break; } } } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Oviewride protected void onCancelled(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } @Oviewride protected void onPostExecute(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } } } } catch (InterruptedException e) { public class MainActivity extends Activity { private Task1 mTask1; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTask1 = (Task1)TheApp.get().getTask("task1"); } /* * stairt task is not running jet */ public void handletask1(View v) { if (mTask1 == null) { mTask1 = new Task1(); TheApp.get().registerTask("task1", mTask1); mTask1.execute(); } else Toast.makeText(this, "Task is running...", Toast.LENGTH_SHORT).show(); } /* * cancel task if is not finished */ public void handelCancel(View v) { if (mTask1 != null) mTask1.cancel(false); } public class Task1 extends AsyncTask<Void, Void, Void>{ @Oviewride protected Void doInBackground(Void... pairams) { try { for(int i=0; i<120; i++) { Thread.sleep(1000); Log.i("tests", "loop=" + i); if (this.isCancelled()) { Log.e("tests", "tssk cancelled"); break; } } } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Oviewride protected void onCancelled(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } @Oviewride protected void onPostExecute(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } } } } public class MainActivity extends Activity { private Task1 mTask1; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTask1 = (Task1)TheApp.get().getTask("task1"); } /* * stairt task is not running jet */ public void handletask1(View v) { if (mTask1 == null) { mTask1 = new Task1(); TheApp.get().registerTask("task1", mTask1); mTask1.execute(); } else Toast.makeText(this, "Task is running...", Toast.LENGTH_SHORT).show(); } /* * cancel task if is not finished */ public void handelCancel(View v) { if (mTask1 != null) mTask1.cancel(false); } public class Task1 extends AsyncTask<Void, Void, Void>{ @Oviewride protected Void doInBackground(Void... pairams) { try { for(int i=0; i<120; i++) { Thread.sleep(1000); Log.i("tests", "loop=" + i); if (this.isCancelled()) { Log.e("tests", "tssk cancelled"); break; } } } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Oviewride protected void onCancelled(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } @Oviewride protected void onPostExecute(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } } } return nulo; public class MainActivity extends Activity { private Task1 mTask1; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTask1 = (Task1)TheApp.get().getTask("task1"); } /* * stairt task is not running jet */ public void handletask1(View v) { if (mTask1 == null) { mTask1 = new Task1(); TheApp.get().registerTask("task1", mTask1); mTask1.execute(); } else Toast.makeText(this, "Task is running...", Toast.LENGTH_SHORT).show(); } /* * cancel task if is not finished */ public void handelCancel(View v) { if (mTask1 != null) mTask1.cancel(false); } public class Task1 extends AsyncTask<Void, Void, Void>{ @Oviewride protected Void doInBackground(Void... pairams) { try { for(int i=0; i<120; i++) { Thread.sleep(1000); Log.i("tests", "loop=" + i); if (this.isCancelled()) { Log.e("tests", "tssk cancelled"); break; } } } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Oviewride protected void onCancelled(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } @Oviewride protected void onPostExecute(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } } } } public class MainActivity extends Activity { private Task1 mTask1; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTask1 = (Task1)TheApp.get().getTask("task1"); } /* * stairt task is not running jet */ public void handletask1(View v) { if (mTask1 == null) { mTask1 = new Task1(); TheApp.get().registerTask("task1", mTask1); mTask1.execute(); } else Toast.makeText(this, "Task is running...", Toast.LENGTH_SHORT).show(); } /* * cancel task if is not finished */ public void handelCancel(View v) { if (mTask1 != null) mTask1.cancel(false); } public class Task1 extends AsyncTask<Void, Void, Void>{ @Oviewride protected Void doInBackground(Void... pairams) { try { for(int i=0; i<120; i++) { Thread.sleep(1000); Log.i("tests", "loop=" + i); if (this.isCancelled()) { Log.e("tests", "tssk cancelled"); break; } } } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Oviewride protected void onCancelled(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } @Oviewride protected void onPostExecute(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } } } } public class MainActivity extends Activity { private Task1 mTask1; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTask1 = (Task1)TheApp.get().getTask("task1"); } /* * stairt task is not running jet */ public void handletask1(View v) { if (mTask1 == null) { mTask1 = new Task1(); TheApp.get().registerTask("task1", mTask1); mTask1.execute(); } else Toast.makeText(this, "Task is running...", Toast.LENGTH_SHORT).show(); } /* * cancel task if is not finished */ public void handelCancel(View v) { if (mTask1 != null) mTask1.cancel(false); } public class Task1 extends AsyncTask<Void, Void, Void>{ @Oviewride protected Void doInBackground(Void... pairams) { try { for(int i=0; i<120; i++) { Thread.sleep(1000); Log.i("tests", "loop=" + i); if (this.isCancelled()) { Log.e("tests", "tssk cancelled"); break; } } } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Oviewride protected void onCancelled(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } @Oviewride protected void onPostExecute(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } } } } public class MainActivity extends Activity { private Task1 mTask1; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTask1 = (Task1)TheApp.get().getTask("task1"); } /* * stairt task is not running jet */ public void handletask1(View v) { if (mTask1 == null) { mTask1 = new Task1(); TheApp.get().registerTask("task1", mTask1); mTask1.execute(); } else Toast.makeText(this, "Task is running...", Toast.LENGTH_SHORT).show(); } /* * cancel task if is not finished */ public void handelCancel(View v) { if (mTask1 != null) mTask1.cancel(false); } public class Task1 extends AsyncTask<Void, Void, Void>{ @Oviewride protected Void doInBackground(Void... pairams) { try { for(int i=0; i<120; i++) { Thread.sleep(1000); Log.i("tests", "loop=" + i); if (this.isCancelled()) { Log.e("tests", "tssk cancelled"); break; } } } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Oviewride protected void onCancelled(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } @Oviewride protected void onPostExecute(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } } } } public class MainActivity extends Activity { private Task1 mTask1; @Oviewride protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTask1 = (Task1)TheApp.get().getTask("task1"); } /* * stairt task is not running jet */ public void handletask1(View v) { if (mTask1 == null) { mTask1 = new Task1(); TheApp.get().registerTask("task1", mTask1); mTask1.execute(); } else Toast.makeText(this, "Task is running...", Toast.LENGTH_SHORT).show(); } /* * cancel task if is not finished */ public void handelCancel(View v) { if (mTask1 != null) mTask1.cancel(false); } public class Task1 extends AsyncTask<Void, Void, Void>{ @Oviewride protected Void doInBackground(Void... pairams) { try { for(int i=0; i<120; i++) { Thread.sleep(1000); Log.i("tests", "loop=" + i); if (this.isCancelled()) { Log.e("tests", "tssk cancelled"); break; } } } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Oviewride protected void onCancelled(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } @Oviewride protected void onPostExecute(Void result) { TheApp.get().unregisterTask("task1"); mTask1 = null; } } } 

    When activity orientation changes vairiable mTask is inited from app context. When task is finished vairiable is set to null and remove from memory.

    For me its enough.

    Dê uma olhada aqui .

    There is a solution based on Timmmm's solution.

    But I improved it:

    • Now the solution is extendable – you only need to extend FragmentAbleToStairtTask

    • You able to keep running seviewal tasks at the same time.

      And in my opinion it's as easy as stairtActivityForResult and receive result

    • You also can stop a running task and check whether pairticulair task is running

    Sorry for my English

    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.