Android 实现异步任务

Android 实现异步任务,android,android-asynctask,rss-reader,Android,Android Asynctask,Rss Reader,我的应用程序中有一个RSS阅读器。然而,我渴望将线程从主I/O移开并使其异步 我真的被卡住了 我知道这可以在几行简单的代码中完成,但我真的很困惑如何实现它 这是填充列表视图的代码:- package co.uk.androidreader; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.w3c.dom.Document; import org.w3c.dom.Ele

我的应用程序中有一个RSS阅读器。然而,我渴望将线程从主I/O移开并使其异步

我真的被卡住了

我知道这可以在几行简单的代码中完成,但我真的很困惑如何实现它

这是填充列表视图的代码:-

package co.uk.androidreader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class CustomizedListView extends Activity {


Intent intent = getIntent();
// All static variables
static final String URL = "URL of RSS Feed";
// XML node keys
static final String KEY_ARTICLE = "article"; // parent node
//static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DATE = "date";
static final String KEY_STRAPLINE = "strapline";
static final String KEY_DETAIL = "detail";
static final String KEY_THUMB_URL = "image";



ListView list;
LazyAdapter adapter;

CustomizedListView thisReference = this;

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


    ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

    XMLParser parser = new XMLParser();
    String xml = parser.getXmlFromUrl(URL); // getting XML from URL
    Document doc = parser.getDomElement(xml); // getting DOM element

    NodeList nl = doc.getElementsByTagName(KEY_ARTICLE);
    // looping through all song nodes <song>
    for (int i = 0; i < nl.getLength(); i++) {
        // creating new HashMap
        HashMap<String, String> map = new HashMap<String, String>();
        Element e = (Element) nl.item(i);
        // adding each child node to HashMap key => value
        //map.put(KEY_ID, parser.getValue(e, KEY_ID));
        map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
        map.put(KEY_DATE, parser.getValue(e, KEY_DATE));
        map.put(KEY_STRAPLINE, parser.getValue(e, KEY_STRAPLINE));
        map.put(KEY_DETAIL, parser.getValue(e, KEY_DETAIL));
        map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));


        // adding HashList to ArrayList
        songsList.add(map);
    }


    list=(ListView)findViewById(R.id.list);

    // Getting adapter by passing xml data ArrayList
    adapter=new LazyAdapter(this, songsList);        
    list.setAdapter(adapter);


    // Click event for single list row
    list.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Intent intent = new Intent(thisReference, DetailsActivity.class);

            intent.putExtra(KEY_TITLE, (String) ((Map)adapter.getItem(position)).get(KEY_TITLE));
            intent.putExtra(KEY_DATE, (String) ((Map)adapter.getItem(position)).get(KEY_DATE));
            intent.putExtra(KEY_DETAIL, (String) ((Map)adapter.getItem(position)).get(KEY_DETAIL));

            startActivity(intent);
        }
    });     
}

public void GoToHome(View v)
{
         Intent myIntent = new Intent(CustomizedListView.this, MainActivity.class);
         //myIntent.putExtra("communityName", (String)getIntent().getExtras().get(CustomizedListViewCommunity.KEY_NAME));
        startActivityForResult(myIntent, 0);

 }

public void GoToBack(View v)
{
         Intent myIntent = new Intent(CustomizedListView.this, MainActivity.class);
         //myIntent.putExtra("communityName", (String)getIntent().getExtras().get(CustomizedListViewCommunity.KEY_NAME));
        startActivityForResult(myIntent, 0);

 }
package co.uk.androidreader;
导入java.util.ArrayList;
导入java.util.HashMap;
导入java.util.Map;
导入org.w3c.dom.Document;
导入org.w3c.dom.Element;
导入org.w3c.dom.NodeList;
导入android.app.Activity;
导入android.content.Intent;
导入android.os.Bundle;
导入android.os.StrictMode;
导入android.view.view;
导入android.widget.AdapterView;
导入android.widget.AdapterView.OnItemClickListener;
导入android.widget.ListView;
公共类CustomizedListView扩展活动{
Intent=getIntent();
//所有静态变量
静态最终字符串URL=“RSS提要的URL”;
//XML节点密钥
静态最终字符串KEY\u ARTICLE=“ARTICLE”//父节点
//静态最终字符串键\u ID=“ID”;
静态最终字符串键\u TITLE=“TITLE”;
静态最终字符串键\u DATE=“DATE”;
静态最终字符串键\u STRAPLINE=“STRAPLINE”;
静态最终字符串键\u DETAIL=“DETAIL”;
静态最终字符串键\u THUMB\u URL=“image”;
列表视图列表;
懒散适配器;
CustomizedListView thisReference=此;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList songsList=新的ArrayList();
XMLParser=新的XMLParser();
字符串xml=parser.getXmlFromUrl(URL);//从URL获取xml
Document doc=parser.getDomeElement(xml);//获取DOM元素
NodeList nl=doc.getElementsByTagName(关键字文章);
//循环通过所有歌曲节点
对于(int i=0;ivalue
//put(KEY_ID,parser.getValue(e,KEY_ID));
put(KEY_TITLE,parser.getValue(e,KEY_TITLE));
put(KEY_DATE,parser.getValue(e,KEY_DATE));
put(KEY_STRAPLINE,parser.getValue(e,KEY_STRAPLINE));
put(KEY_DETAIL,parser.getValue(e,KEY_DETAIL));
put(KEY_THUMB_URL,parser.getValue(e,KEY_THUMB_URL));
//将哈希列表添加到ArrayList
歌曲列表。添加(地图);
}
list=(ListView)findViewById(R.id.list);
//通过传递xml数据ArrayList获取适配器
adapter=新的LazyAdapter(此,songsList);
list.setAdapter(适配器);
//单击单个列表行的事件
list.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父对象、视图、整型位置、长id){
意向意向=新意向(thisReference,DetailsActivity.class);
intent.putExtra(KEY_TITLE,(String)((Map)adapter.getItem(position)).get(KEY_TITLE));
intent.putExtra(KEY_DATE,(String)((Map)adapter.getItem(position)).get(KEY_DATE));
intent.putExtra(KEY_DETAIL,(String)((Map)adapter.getItem(position)).get(KEY_DETAIL));
星触觉(意向);
}
});     
}
公共空间GoToHome(视图五)
{
Intent myIntent=newintent(CustomizedListView.this,MainActivity.class);
//myIntent.putExtra(“communityName”,(String)getIntent().getExtras().get(CustomizedListViewCommunity.KEY_NAME));
startActivityForResult(myIntent,0);
}
公共无效GoToBack(视图五)
{
Intent myIntent=newintent(CustomizedListView.this,MainActivity.class);
//myIntent.putExtra(“communityName”,(String)getIntent().getExtras().get(CustomizedListViewCommunity.KEY_NAME));
startActivityForResult(myIntent,0);
}
}

希望这有助于:

AsyncTask<String, Void, String> worker = new AsyncTask<String, Void, String>() {

    @Override
    protected String doInBackground(String... param) {
        // here goes the code you want off the main thread
        return "the result of this code that goes on onPostExecute";
    }

    @Override
    protected void onPostExecute(String str) {
        super.onPostExecute(str);

        // here goes the code that will run after you doInBackground has finished working
    }

};

worker.execute("any param you want");
AsyncTask worker=new AsyncTask(){
@凌驾
受保护的字符串doInBackground(字符串…参数){
//下面是您希望从主线程中删除的代码
返回“此代码在PostExecute上运行的结果”;
}
@凌驾
受保护的void onPostExecute(字符串str){
super.onPostExecute(str);
//下面是您完成后台工作后将运行的代码
}
};
worker.execute(“您想要的任何参数”);

任何网络任务都无法在主线程上运行,因此我们需要一个异步任务

class RequestTask extends AsyncTask<String, String, String>{



    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null; // THIS IS WHERE THE INFO IS SAVED

        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){

                ByteArrayOutputStream out = new ByteArrayOutputStream();
                 response.getEntity().writeTo(out);
                 out.close();
                 responseString = out.toString("UTF-8");
            } 

            else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } 

        catch (ClientProtocolException e) {
            e.printStackTrace();

            //Handle httprequest when answer is not expected
        } 

        catch (IOException e) { 
            e.printStackTrace();

            //Handle httprequest when answer is not expected
        }
        return responseString;
    }



    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result); 
        progressDialog.dismiss();

              //handle your result here and any catches



        }           









    }




}
class RequestTask扩展了AsyncTask{
@凌驾
受保护的字符串doInBackground(字符串…uri){
HttpClient HttpClient=新的DefaultHttpClient();
HttpResponse响应;
String responseString=null;//这是保存信息的地方
试一试{
response=httpclient.execute(新的HttpGet(uri[0]);
StatusLine StatusLine=response.getStatusLine();
if(statusLine.getStatusCode()==HttpStatus.SC\u OK){
ByteArrayOutputStream out=新建ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString=out.toString(“UTF-8”);
} 
否则{
//关闭连接。
response.getEntity().getContent().close();
抛出新IOException(statusLine.getReasonPhrase());
}
} 
捕获(客户端协议例外e){
e、 printStackTrace();
//在不需要回答时处理httprequest
} 
捕获(IOE){
e、 printStackTrace();
//在不需要回答时处理httprequest
}
回报率;
}
@凌驾
受保护的void onPostExecute(字符串结果){
super.onPostExecute(结果);
progressDialog.disclose();
//在这里处理您的结果和任何捕获
}           
}
}
然后你用
newrequesttask().execute(“http:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

     //define the task as an anonymous type (you could create a concrete inner class as well)
    AsyncTask<Void, Void, ArrayList<HashMap<String,String>>> task = new AsyncTask<Void, Void, ArrayList<HashMap<String,String>>>() {

        @Override
        protected ArrayList<HashMap<String, String>> doInBackground(
                Void... params) {
            ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

            XMLParser parser = new XMLParser();
            String xml = parser.getXmlFromUrl(URL); // getting XML from URL
            Document doc = parser.getDomElement(xml); // getting DOM element

            NodeList nl = doc.getElementsByTagName(KEY_ARTICLE);
            // looping through all song nodes <song>
            for (int i = 0; i < nl.getLength(); i++) {
                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();
                Element e = (Element) nl.item(i);
                // adding each child node to HashMap key => value
                //map.put(KEY_ID, parser.getValue(e, KEY_ID));
                map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
                map.put(KEY_DATE, parser.getValue(e, KEY_DATE));
                map.put(KEY_STRAPLINE, parser.getValue(e, KEY_STRAPLINE));
                map.put(KEY_DETAIL, parser.getValue(e, KEY_DETAIL));
                map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));


                // adding HashList to ArrayList
                songsList.add(map);
            }
            return songsList;
        }

        @Override
        protected void onPostExecute(
                ArrayList<HashMap<String, String>> result) {
            super.onPostExecute(result);

            ListView list=(ListView)CustomizedListView.this.findViewById(R.id.list);
            // Getting adapter by passing xml data ArrayList                
            list.setAdapter(new LazyAdapter(this, result));
        }

    };

            //execute the task
    task.execute((Void[])null);

    list=(ListView)findViewById(R.id.list);
    // Click event for single list row
    list.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Intent intent = new Intent(thisReference, DetailsActivity.class);

            intent.putExtra(KEY_TITLE, (String) ((Map)adapter.getItem(position)).get(KEY_TITLE));
            intent.putExtra(KEY_DATE, (String) ((Map)adapter.getItem(position)).get(KEY_DATE));
            intent.putExtra(KEY_DETAIL, (String) ((Map)adapter.getItem(position)).get(KEY_DETAIL));

            startActivity(intent);
        }
    });     
}