我正在创建一个简单的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);
}
}
这就是我的整个代码,告诉我要创建哪些新方法以及在该方法中传输的代码。日Thnx!
答案 0 :(得分: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中更改的通知数据集。 / p>
答案 1 :(得分: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
答案 2 :(得分:0)
除了通过创建适配器并设置它来更新UI的部分之外,所有内容都在doInBackground中。那就是onPostExecute。
答案 3 :(得分:0)
对于android中的每个应用程序,都有一个名为UI线程的主线程。如果你一直在UI线程中执行任务,那么你的应用程序可能无法很好地响应并导致强制关闭一段时间。要避免此类问题,您必须使用异步任务。 我建议你通过Process&Threads,他们已经解释了如何处理在后台执行任务的时间。您必须继承AsyncTask并实现doInBackground()回调方法来执行长任务。
答案 4 :(得分:0)
为您的Asynch任务创建一个类
示例:MyActivity.java =&gt;
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 () {
...
将您的XML方法移动到新的&#34;下载程序&#34;适当的课程。
我的猜测是,您只需将所有内容剪切/粘贴到&#34; doInBackground()&#34;
这是一个很好的教程:
&lt; =向下看&#34; 5。教程:AsyncTask&#34;
&#39;希望有所帮助