Android generic Asynctask

后端 未结 2 580
孤独总比滥情好
孤独总比滥情好 2021-01-16 02:17

I currently have multiple activity that needs to perform an asynctask for http post and I wish to make the asynctask as another class file so that the different activity can

2条回答
  •  孤街浪徒
    2021-01-16 02:52

    Generic AsyncTask Example

    Call it like

    new RetrieveFeedTask(new OnTaskFinished()
            {
                @Override
                public void onFeedRetrieved(String feeds)
                {
                    //do whatever you want to do with the feeds
                }
            }).execute("http://enterurlhere.com");
    

    RetrieveFeedTask.class

    class RetrieveFeedTask extends AsyncTask
    {
        String HTML_response= "";
    
        OnTaskFinished onOurTaskFinished;
    
    
        public RetrieveFeedTask(OnTaskFinished onTaskFinished)
        {
            onOurTaskFinished = onTaskFinished;
        }
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
        }
    
        @Override
        protected String doInBackground(String... urls)
        {
            try
            {
                URL url = new URL(urls[0]); // enter your url here which to download
    
                URLConnection conn = url.openConnection();
    
                // open the stream and put it into BufferedReader
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    
                String inputLine;
    
                while ((inputLine = br.readLine()) != null)
                {
                    // System.out.println(inputLine);
                    HTML_response += inputLine;
                }
                br.close();
    
                System.out.println("Done");
    
            }
            catch (MalformedURLException e)
            {
                e.printStackTrace();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return HTML_response;
        }
    
        @Override
        protected void onPostExecute(String feed)
        {
            onOurTaskFinished.onFeedRetrieved(feed);
        }
    }
    

    OnTaskFinished.java

    public interface OnTaskFinished
    {
        public void onFeedRetrieved(String feeds);
    }
    

提交回复
热议问题