RSS News Reader – Related Android Technology Knowledge Point

1. Handler message processor: android.os.Handler

Sending and receiving processing messages are generally used to process messages sent by child threads.

When the application starts, Android will start a main thread first(that is UIThread),< span style="font-size:16px">The main thread is the management interfaceUIControl, event distribution,For example,If you click oneButton,Androidwill Distribute events toButtonUp, to respond to your actions. If you need a time-consuming operation at this time, for example:When you read data online, or read a large file locally, you can’t put these operations in the main thread. If you put them in the main thread, the interface will appear suspended animation ,If5If the second has not been completed, you will receiveAndroidAn error message from the systemForced close“,At this time, we need to put these time-consuming operations in a child thread,Because the child thread involvesUIUpdate,AndroidThe main thread is not thread-safe, which means , UpdateUIOnly in the main thread Update, operation in sub-threads is dangerous.At this time,Because Handlerruns in the main thread(UIin thread),It and the child thread can passMessageobject to pass data,This time,HandlerOnly accept the message from the child threadMessageObject(It contains data), These messages are placed in the main thread queue and updated with the main threadUI.

Implementation:
1. Create in the main thread:

mHandler = new Handler()
{
   @Override
   public void handleMessage(Message msg)
  {//Overload message processing function
      super.handleMessage(msg);
     do();//Process the message in this function
  }
};

2, send a message in the child thread:

mHandler.sendMessage(msg);

3, message generation

Message msg = new Message();//To create a new message, new needs to open up space again

Message msg = mHandler.obtainMessage();//Remove one from the message pool of the message processor, no Need new, high efficiency.

Of course, the message can add parameters, and these parameters can also be obtained for processing when processing the message.

Second, Thread sub-thread processing class: java.lang.Thread, this is a class in java, not android

1. Create thread: just create at this time, thread has not started yet

Thread thread = new Thread(new Runnable ()
{
  public void run()
  {//Thread running function
     do();//Related processing in thread
  }
}); 

Actually, this code is written in this way to understand

//First create a running interface and specify in the interface Run function
Runnable runnable = new Runnable()
{
  public void run()
{//Thread running function
do(); //Related processing in the thread
}
}
//Create a thread with this running interface as a parameter, and run the run function in the interface when the thread starts
Thread thread = new Thread(runnable);

2, start thread:
thread.start();

Three, create a menu in the program: android.view.Menu

Android programs generally do not have a menu bar, but it can be achieved through the menu key on the phone panel The function of the menu. There are three types of menus in Android: 1. Options menu (optinosMenu) 2. Context menu (ContextMenu) 3. Submenu (subMenu)
The most commonly used one is the options menu (optionsMenu), the menu is clicked on the menu button It will be displayed at the bottom of the corresponding Activity. Activity has a mechanism to manage the menu.

Option menu implementation:

1, public boolean onCreateOptionsMenu(Menu menu): This method is used For the initialization menu, the menu parameter is the Menu instance to be displayed. Return true to display the menu, false to not display;
(Only called when the menu is initialized for the first time, the system provides This function is automatically called at runtime to facilitate menu creation)

Add menu item: menu.add((int groupId, int itemId, int order, charsequence title) .setIcon (drawable ID)

The four parameters of the add() method, in order:

1. Group, if not grouped, write Menu.NONE, < /p>

2. Id, this is very important, Android determines different menus according to this Id

3. The order, which menu item is in front is determined by the size of this parameter

< p> 4. Text, the display text of the menu item

The add() method returns the MenuItem object, call its setIcon() method to set Icon
for the corresponding MenuItem 2. Menu response function: public boolean onOptionsItemSelected(MenuItem item)
               菜单项被点击时调用,也就是菜单项的监听方法。
             
3.public void onOptionsMenuClosed(Menu menu):每次菜单被关闭时调用.

(There are three situations when the menu is closed, the menu button is clicked again, the back button is clicked, or the user selects a menu item)

四、RSS源解析的实现

1、 Sample RSS source file format to be parsed




<![CDATA[IT-Sina Blog]]>



<![CDATA[Sina Blog Channel]]>

http://blog.sina.com.cn
http://www.sinaimg.cn/blog/main/index2010/blog_logo.png



http://blog.sina.com.cn/lm/tech/
zh-cn
WWW.SINA.COM.CN
5


Fri, 23 Aug 2013 07:39:40 GMT




<![CDATA[What Baidu Light Application wants to do]]>

http://go.rss.sina.com.cn/redirect.php?url=http://blog.sina.com.cn/s/blog_88acd9c80101gld8.html
WWW.SINA.COM.CN
http://go.rss.sina.com.cn/redirect.php?url=http://blog.sina.com.cn/s/blog_88acd9c80101gld8.html


Fri, 23 Aug 2013 06:35:27 GMT






<![CDATA[Internet Finance: A Model of American Platform Worth Learning From]]>

http://go.rss.sina.com.cn/redirect.php?url=http://blog.sina.com.cn/s/blog_bee732060101npb7.html
WWW.SINA.COM.CN
http://go.rss.sina.com.cn/redirect.php?url=http://blog.sina.com.cn/s/blog_bee732060101npb7.html


Fri, 23 Aug 2013 06:05:08 GMT






2. Implement the class that represents each RSS item

//Rssitem information, used to store each RSS item item
public class RssItem
{
public static final String TITLE = "title";
public static final String PUBDATE = "pubDate";
//Title
private String title;
	//details
private String description;
	//Link
private String link;
//Source
private String source;
	//date
private String pubDate;

//Get the title
public String getTitle() {
return title;
}
//Set title
public void setTitle(String title) {
this.title = title;
}
//Get detailed information
public String getDescription() {
return description;
}
//Set the details
public void setDescription(String description) {
this.description = description;
}
//Get link
public String getLink() {
return link;
}
//Set link
public void setLink(String link) {
this.link = link;
}
//Get the source
public String getSource() {
return source;
}
//Set source
public void setSource(String source) {
this.source = source;
}
//Get the date
public String getPubDate() {
return pubDate;
}
//Set the date
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}

}

3. Implement an RSS source class

//RSS source class, used to store all the information of an RSS source
public class RssFeed
{
//Title
private String title;//RSS source, channel title
	//date
private String pubdate;//RSS source, channel release date

//Number of entries
private int itemcount;

//Used to store the list of RSS information
private List itemlist;
public RssFeed()
{
itemlist = new Vector(0);
}
//Add element
public int addItem(RssItem item) {
itemlist.add(item);
itemcount++;
return itemcount;
}
//Get elements
public RssItem getItem(int location) {
return itemlist.get(location);
}
//Get all the information needed by the list and store it in the List
public List getAllItemsForListView()
{
List> data = new ArrayList>();
int size = itemlist.size();
for(int i=0; i item = new HashMap();
item.put(RssItem.TITLE, itemlist.get(i).getTitle());
item.put(RssItem.PUBDATE, itemlist.get(i).getPubDate());
data.add(item);
}

return data;
}
//Get the title
public String getTitle() {
return title;
}
//Set title
public void setTitle(String title) {
this.title = title;
}
//Get the date
public String getPubdate() {
return pubdate;
}
//Set the date
public void setPubdate(String pubdate) {
this.pubdate = pubdate;
}
//Get the quantity
public int getItemcount() {
return itemcount;
}
//Set the number
public void setItemcount(int itemcount) {
this.itemcount = itemcount;
}
//Get information array
public List getItemlist() {
return itemlist;
}
//Set the information array
public void setItemlist(List itemlist) {
this.itemlist = itemlist;
}
}

4. Create a processor class for RSS data SAX parsing

Use a series of factory methods to generate an XMLReader object, and then use the reader.setContentHandler method for this The reader sets up a processor. When using SAX, the parser will perform depth-first traversal of the XML document. When traversing, it will call the method in the processor according to the conditions. That is to say, when parsing, we can call our own methods.

Through this class, you can fill the RSS feed information into the RssFeed class object when parsing. Then get the RssFeed class object filled with data through the public RssFeed getFeed() method of this class.

//RSS data SAX analysis
public class RssHandler extends DefaultHandler
{
RssFeed rssFeed;
RssItem rssItem;
private static boolean a = false;
String lastElementName = "";
final int RSS_TITLE = 1;
final int RSS_LINK = 2;
final int RSS_DESCRIPTION = 3;
final int RSS_PUBDATE = 5;
int currentstate = 0;

public RssHandler() {

}
//Return information in the form of rssFeed
public RssFeed getFeed() {
return rssFeed;
}
//Start parsing the document
public void startDocument()throws SAXException {
System.out.println("startDocument");
//Instantiate RssFeed class and RssItem class
rssFeed = new RssFeed();
rssItem = new RssItem();
}
//End of document
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
//Start parsing tags
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
super.startElement(uri, localName, qName, attributes);
//channel label
if(localName.equals("channel")) {
currentstate = 0;
return;
}
//item tag
if(localName.equals("item")) {
rssItem = new RssItem();
return;
}
//title tag
if(localName.equals("title")) {
currentstate = RSS_TITLE;
return;
}
//Detailed information label
if(localName.equals("description")) {
//Skip the description tag encountered for the first time
if(a == true) {
currentstate = RSS_DESCRIPTION;
return;
} else {
a = true;
return;
}
}
		//Link
if(localName.equals("link")) {
currentstate = RSS_LINK;
return;
}
		//date
if(localName.equals("pubDate")) {
currentstate = RSS_PUBDATE;
return;
}
currentstate = 0;
}
//The end of the label
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
//Add information to rssFeed
if(localName.equals("item")) {
rssFeed.addItem(rssItem);
return;
}
}
//Analyze the text between the tags
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if(length <= 5) return;
String theString = new String(ch, start, length);
switch (currentstate) {
//Title
case RSS_TITLE:
rssItem.setTitle(theString);
Log.e("title",theString);
currentstate = 0;
break;
			//Link
case RSS_LINK:
rssItem.setLink(theString);
currentstate = 0;
break;
			//details
case RSS_DESCRIPTION:
System.out.println("RSS_DESCRIPTION=" + theString);
if(a == true) {
rssItem.setDescription(theString);
currentstate = 0;
}else {
a = true;
}
break;
			//date
case RSS_PUBDATE:
rssItem.setPubDate(theString);
currentstate = 0;
break;
default:
return;
}
}
}

5. Realize parsing

//Realize parsing based on URL
URL url = new URL(urlString);
//Instantiate SAX parsing factory class
SAXParserFactory factory = SAXParserFactory.newInstance();
//Create SAX parser based on class project
SAXParser parser = factory.newSAXParser();
//Get XML reader from SAX parser
XMLReader xmlReader = parser.getXMLReader();
    
//Hook event processing object to xmlReader
RssHandler rssHandler = new RssHandler();
xmlReader.setContentHandler(rssHandler);
    
//Get the content of url, the constructor parameter is byte stream, which is obtained by url.openStream()
InputSource is = new InputSource(url.openStream());
    
//Analyze the content of the url
xmlReader.parse(is);
//Return RSS information
RssFeed rssfeed = rssHandler.getFeed();

Leave a Comment

Your email address will not be published.