Passing function as a parameter in java

后端 未结 6 988
南笙
南笙 2020-11-28 22:13

I\'m getting familiar with Android framework and Java and wanted to create a general \"NetworkHelper\" class which would handle most of the networking code enabling me to ju

6条回答
  •  Happy的楠姐
    2020-11-28 22:30

    Use a callback interface or an abstract class with abstract callback methods.

    Callback interface example:

    public class SampleActivity extends Activity {
    
        //define callback interface
        interface MyCallbackInterface {
    
            void onDownloadFinished(String result);
        }
    
        //your method slightly modified to take callback into account 
        public void downloadUrl(String stringUrl, MyCallbackInterface callback) {
            new DownloadWebpageTask(callback).execute(stringUrl);
        }
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            //example to modified downloadUrl method
            downloadUrl("http://google.com", new MyCallbackInterface() {
    
                @Override
                public void onDownloadFinished(String result) {
                    // Do something when download finished
                }
            });
        }
    
        //your async task class
        private class DownloadWebpageTask extends AsyncTask {
    
            final MyCallbackInterface callback;
    
            DownloadWebpageTask(MyCallbackInterface callback) {
                this.callback = callback;
            }
    
            @Override
            protected void onPostExecute(String result) {
                callback.onDownloadFinished(result);
            }
    
            //except for this leave your code for this class untouched...
        }
    }
    

    The second option is even more concise. You do not even have to define an abstract method for "onDownloaded event" as onPostExecute does exactly what is needed. Simply extend your DownloadWebpageTask with an anonymous inline class inside your downloadUrl method.

        //your method slightly modified to take callback into account 
        public void downloadUrl(String stringUrl, final MyCallbackInterface callback) {
            new DownloadWebpageTask() {
    
                @Override
                protected void onPostExecute(String result) {
                    super.onPostExecute(result);
                    callback.onDownloadFinished(result);
                }
            }.execute(stringUrl);
        }
    
        //...
    

提交回复
热议问题