-1

我正在创建一个简单的 RSS 阅读器,它在 ListView 中显示标题,从指定网站的 .xml 文件中下载它。

我编写了应用程序,它在单线程上工作,但我想使用 ASyncTask 以便所有下载都在后台进行,并且 UI 不会挂起。

现在,我以前从未使用过 AsyncTask,我用谷歌搜索了它,但我仍然不确定将我的代码的方法转移到哪个 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);
}


}

这就是我的全部代码,告诉我要创建哪些新方法以及要在该方法中传输的代码。太好了!

4

5 回答 5

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 中更改的通知数据集。

于 2012-06-23T06:03:57.180 回答
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

于 2012-06-23T06:04:30.537 回答
0

除了通过创建适配器并设置它来更新 UI 的部分之外,所有内容都在 doInBackground 中。这在 onPostExecute 中。

于 2012-06-23T06:03:16.703 回答
0

对于 android 中的每个应用程序,都有一个称为 UI 线程的主线程。如果您一直在 UI 线程中执行任务,您的应用程序可能无法很好地响应并导致强制关闭一段时间。为避免此类问题,您必须使用异步任务。我建议您阅读Process&Threads,他们在其中解释了如何在后台处理耗时任务。您必须继承 AsyncTask 并实现 doInBackground() 回调方法来执行长任务。

于 2012-06-23T06:04:28.807 回答
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. 这是一个很好的教程:

    <= 往下看“5. 教程:AsyncTask”

'希望有帮助

于 2012-06-23T06:09:47.423 回答