Android AsyncTask - avoid multiple instances running

前端 未结 7 1730
夕颜
夕颜 2020-12-25 15:36

I have AsyncTask that processes some background HTTP stuff. AsyncTask runs on schedule (Alarms/service) and sometime user executes it manually.

I process records fro

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-25 15:56

    Initialize the AsyncTask to null. Only create a new one if it is null. In onPostExecute, set it to null again, at the end. Do the same in onCancelled, in case the user cancels this. Here's some untested code to illustrate the basic idea.

    import android.app.Activity;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    
    public class FooActivity extends Activity {
    
        private class MyAsyncTask extends AsyncTask {
            @Override
            protected void onPostExecute(Foo foo) {
                        // do stuff
                mMyAsyncTask = null;
            }
    
            @Override
            protected void onCancelled() {
                // TODO Auto-generated method stub
                mMyAsyncTask = null;
            }
    
            @Override
            protected Foo doInBackground(Foo... params) {
                        try {
                             // dangerous stuff                         
                        } catch (Exception e) {
                            // handle. Now we know we'll hit onPostExecute()
                        }
    
                return null;
            }
        }
    
        private MyAsyncTask mMyAsyncTask = null;
    
        @Override
        public void onCreate(Bundle bundle) {
            Button button = (Button) findViewById(R.id.b2);
            button.setOnClickListener(new View.OnClickListener() {
    
                public void onClick(View v) {
                    if (mMyAsyncTask == null) {
                        mMyAsyncTask = new MyAsyncTask();
                        mMyAsyncTask.execute(null);
                    }
                }
    
            });
        }
    

    }

提交回复
热议问题