2012-06-23 196 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”

'希望有帮助

相关问题