2012-06-23 197 views
-1

我正在創建一個簡單的RSS閱讀器,它在ListView中顯示標題,從指定網站的.xml文件下載它。將單線程應用程序轉換爲ASyncTask應用程序

我寫了應用程序,它在單線程上工作,但我想使用ASyncTask,以便所有下載都發生在後臺並且UI不會掛起。

現在,我從來沒有使用AsyncTask之前,我GOOGLE了它,但我仍然不知道在哪裏將我的代碼的方法轉移到哪個ASyncTask方法。請幫我做。

SimpleRssReaderActivity.java

package mohit.app.rssreader; 

import java.io.IOException; 
import java.io.InputStream; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.util.ArrayList; 
import java.util.List; 

import org.xmlpull.v1.XmlPullParser; 
import org.xmlpull.v1.XmlPullParserException; 
import org.xmlpull.v1.XmlPullParserFactory; 

import android.app.ListActivity; 
import android.content.Intent; 
import android.net.Uri; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 

public class SimpleRssReaderActivity extends ListActivity { 
    List headlines; 
    List links; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

    // Initializing instance variables arrays 
     headlines = new ArrayList(); 
     links = new ArrayList(); 

     try { 
      URL url = new URL("http://feeds.pcworld.com/pcworld/latestnews"); 

      XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
      factory.setNamespaceAware(false); 
      XmlPullParser xpp = factory.newPullParser(); 

       // get the XML from an input stream 
      xpp.setInput(getInputStream(url), "UTF_8"); 


      boolean insideItem = false; 

       // Returns the type of current event: START_TAG, END_TAG, etc.. 
      int eventType = xpp.getEventType(); 
      while (eventType != XmlPullParser.END_DOCUMENT) 
      { 
        if (eventType == XmlPullParser.START_TAG) 
       { 

        if (xpp.getName().equalsIgnoreCase("item")) 
        { 
         insideItem = true; 
        } 
        else if (xpp.getName().equalsIgnoreCase("title")) 
        { 
         if (insideItem) 
          headlines.add(xpp.nextText()); //extract the headline 
        } 
        else if (xpp.getName().equalsIgnoreCase("link")) 
        { 
         if (insideItem) 
          links.add(xpp.nextText()); //extract the link of article 
        } 
       } 
       else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")) 
       { 
        insideItem=false; 
       } 

       eventType = xpp.next(); //move to next element 
      } 

     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (XmlPullParserException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     // Binding data 
     ArrayAdapter adapter = new ArrayAdapter(this, 
       android.R.layout.simple_list_item_1, headlines); 

     setListAdapter(adapter); 



    } 

public InputStream getInputStream(URL url) { 
    try { 
     return url.openConnection().getInputStream(); 
    } catch (IOException e) { 
     return null; 
    } 
} 

@Override 
protected void onListItemClick(ListView l, View v, int position, long id) { 
    Uri uri = Uri.parse((String) links.get(position)); 
    Intent intent = new Intent(Intent.ACTION_VIEW, uri); 
    startActivity(intent); 
} 


} 

SO這就是我的全部代碼,告訴我要創造出新的方法和代碼,以在該方法轉移。日Thnx!

+0

那麼你想讓HTTP部分在單獨的線程上運行嗎? – iNan

+0

是的....多數民衆贊成 – Mohit

+0

以及許多答案已經:) – iNan

回答

3
@Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     InitTask _initTask = new InitTask(); 
     _initTask.execute(this); 

} 

一些這樣的事......

/** 
    * sub-class of AsyncTask 
    */ 
    protected class InitTask extends AsyncTask<Context, Integer, ArrayList> 
    { 
     // -- run intensive processes here 
     // -- notice that the datatype of the first param in the class definition matches the param passed to this method 
     // -- and that the datatype of the last param in the class definition matches the return type of this method 
       @Override 
       protected String doInBackground(Context... params) 
       { 

         return inBackground(); 
       } 

       // -- gets called just before thread begins 
       @Override 
       protected void onPreExecute() 
       { 
         Log.i("makemachine", "onPreExecute()"); 
         super.onPreExecute(); 

       } 

       // -- called from the publish progress 
       // -- notice that the datatype of the second param gets passed to this method 
       @Override 
       protected void onProgressUpdate(Integer... values) 
       { 
         super.onProgressUpdate(values); 
         Log.i("makemachine", "onProgressUpdate(): " + String.valueOf(values[0])); 
       } 

       // -- called if the cancel button is pressed 
       @Override 
       protected void onCancelled() 
       { 
         super.onCancelled(); 
         Log.i("makemachine", "onCancelled()"); 

       } 

       // -- called as soon as doInBackground method completes 
       // -- notice that the third param gets passed to this method 
       @Override 
       protected void onPostExecute(ArrayList result) 
       { 
         super.onPostExecute(result); 
         Log.i("makemachine", "onPostExecute(): " + result); 
       // Binding data 
       ArrayAdapter adapter = new ArrayAdapter(this, 
          android.R.layout.simple_list_item_1, result); 

        SimpleRssReaderActivity.this.setListAdapter(adapter); 

       } 
    }  
private ArrayList inBackground(){ 


// Initializing instance variables arrays 
     headlines = new ArrayList(); 
     links = new ArrayList(); 

     try { 
      URL url = new URL("http://feeds.pcworld.com/pcworld/latestnews"); 

      XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
      factory.setNamespaceAware(false); 
      XmlPullParser xpp = factory.newPullParser(); 

       // get the XML from an input stream 
      xpp.setInput(getInputStream(url), "UTF_8"); 


      boolean insideItem = false; 

       // Returns the type of current event: START_TAG, END_TAG, etc.. 
      int eventType = xpp.getEventType(); 
      while (eventType != XmlPullParser.END_DOCUMENT) 
      { 
        if (eventType == XmlPullParser.START_TAG) 
       { 

        if (xpp.getName().equalsIgnoreCase("item")) 
        { 
         insideItem = true; 
        } 
        else if (xpp.getName().equalsIgnoreCase("title")) 
        { 
         if (insideItem) 
          headlines.add(xpp.nextText()); //extract the headline 
        } 
        else if (xpp.getName().equalsIgnoreCase("link")) 
        { 
         if (insideItem) 
          links.add(xpp.nextText()); //extract the link of article 
        } 
       } 
       else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")) 
       { 
        insideItem=false; 
       } 

       eventType = xpp.next(); //move to next element 
      } 

     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (XmlPullParserException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

    return headlines ; 


} 

這個例子是按照您的代碼,但如果可能的話我想給一些建議,不應該,但應該使用

1-創建和設置適配器的工作應該保持在Oncreate中,只需在那裏設置空的數組列表並將該列表傳遞給Asytask(在構造函數中)並填充數據,並調用onPostExecute中更改的通知數據集。

+0

k..so我只是在onCreate中定義contectview,關閉它。然後編寫InitTask類的過程?對? – Mohit

+0

我想你是要求使用InitTask ...?我已經更新了代碼.... –

0

除了通過創建適配器並對其進行設置更新UI的部分以外,一切都在doInBackground中進行。這在onPostExecute。

0

對於android中的每個應用程序,都有一個稱爲UI線程的主線程。如果你一直在UI線程中執行任務,那麼你的應用程序可能不會很好地響應,並且會導致部分時間關閉。爲了避免這種問題,你必須使用異步任務。 我建議你通過Process&Threads,他們已經解釋瞭如何處理背後的任務。您必須繼承AsyncTask並實現doInBackground()回調方法來執行長時間任務。

2

嗯,我真的不知道你想要什麼方法在異步任務做,但基本上你在這裏使用這個模型

public class PostTask extends AsyncTask<Void/*what the doInBackground method wants*/, String/* What the onProgress method wants*/, Boolean /*What the doInBackground method returns*/> { 

     @Override 
     protected Boolean doInBackground(Void... params) { 
      boolean result = false; 

      //All your code goes in here 

      //If you want to do something on the UI use progress update 

      publishProgress("progress"); 
      return result; 
     } 

     protected void onProgressUpdate(String... progress) { 
      StringBuilder str = new StringBuilder(); 
       for (int i = 1; i < progress.length; i++) { 
        str.append(progress[i] + " "); 
       } 

     } 
    } 

你想要做的所有的網絡任務異步任務:d

0
  1. 創建一個類的非同步任務

    例:MyActivity.java =>

    public class MyActivity extends MyBaseActivity { 
        ... 
        MyDownloaderTask downloaderTask = null; 
        ... 
    
        public void onCreate (Bundl savedInstanceState) { 
        ... 
        downloaderTask = new MyDownloaderTask(); 
        ... 
        } 
    } 
    
    private class MyDownloaderTask extends AsyncTask<Object, String, Boolean> { 
        ... 
        @Override 
        protected void onPreExecute() { 
        ... 
    
  2. 根據需要將您的XML方法移動到新的「下載器」類中。

    我的猜測是,你只剪切/粘貼到一切的重寫 「doInBackground()」

  3. 這裏有一個很好的教程:

    < =看down to「5. Tutorial:AsyncTask」

'希望有幫助

相關問題