从MainActivity通知onPostExecute的片段

时间:2015-04-09 19:52:25

标签: java android listener

在Android中,我很难弄清楚当AsyncTask完成时如何通知正在侦听的片段。似乎通常的Java内容,比如说PropertyChangeLIstener不可用。因此,在onPostExecute中,我想要触发一个事件并让OtherFragment看到它。

我该怎么做?

    public class MainActivity extends FragmentActivity {

        <stuff>

        private class ConsumeWebService extends AsyncTask 
                 <String,   // type of the parameters sent to the task upon execution - doInBackground()
                  Integer,  // type of the progress units published during the background computation -onProgressUpdate()
                  String> { 

            public ConsumeWebService(SomeKindOfListener listener){
                    this.myListener = listener;
            }

            protected String doInBackground(String... urls) {

                  < get JSON data from RESTful service>
                  < create and populate SQLite db wit JSON data>

                  return jsonData;
            }

            @Override
            protected void onPostExecute(String result) {
                     try {
                         <fire some kind of event>
                     } 
                     catch (Exception e) {
                     }
            }
        }
    }

    public class OtherFragment extends Fragment implements SomeKindOfListener {

        @Override
        public void someKindOfChange(SomeKindOfChangeEvent arg0) {
            < do the stuff we want to do>
        }

    }

    public interface SomeKindOfListener {
          void onPostExecuteDone();
    }

2 个答案:

答案 0 :(得分:1)

使用FragmentManager:

SomeKindOfListener  listener = (SomeKindOfListener ) 
      getFragmentManager().findFragmentById(R.id.myFragment);

new ConsumeWebService(listener);

        @Override
        protected void onPostExecute(String result) {
                 try {
                    this.myListener.someKindOfChange();
                 } 
                 catch (Exception e) {
                 }
        }

答案 1 :(得分:1)

我会做这样的事情:

1 - 有一个界面

public interface OnXListener {
    void onX(Object data);
}

2-让片段实现它

public class MyFragment extends Fragment implements OnXListener{
    public void onX(Object data) {
        doSomething(data);
    }
    public void doSomething(data) {
        /do the real thing
    }
}
当asynctask完成时,

3-在actvitiy中调用它

public class MyActivity extends Activity {
    Fragment mMyFragment fragment;
    //stuff, initializate fragment, show fragment, etc.

    private class MyAsyncTask extends AsyncTask {
        //stuff
        @override
        protected void onPostExecute(Object result) {
           ((OnXListener) MyActivity.this.mMyFragment).onX(result);
        }
    }
}