Android-Earthquake(地震顯示器)項(xiàng)目詳解

Earthquake(地震顯示器) 項(xiàng)目 詳解


我們注重客戶(hù)提出的每個(gè)要求,我們充分考慮每一個(gè)細(xì)節(jié),我們積極的做好成都做網(wǎng)站、成都網(wǎng)站設(shè)計(jì)、成都外貿(mào)網(wǎng)站建設(shè)服務(wù),我們努力開(kāi)拓更好的視野,通過(guò)不懈的努力,成都創(chuàng)新互聯(lián)公司贏得了業(yè)內(nèi)的良好聲譽(yù),這一切,也不斷的激勵(lì)著我們更好的服務(wù)客戶(hù)。 主要業(yè)務(wù):網(wǎng)站建設(shè),網(wǎng)站制作,網(wǎng)站設(shè)計(jì),微信小程序定制開(kāi)發(fā),網(wǎng)站開(kāi)發(fā),技術(shù)開(kāi)發(fā)實(shí)力,DIV+CSS,PHP及ASP,ASP.Net,SQL數(shù)據(jù)庫(kù)的技術(shù)開(kāi)發(fā)工程師。

本文地址: http://blog.csdn.net/caroline_wendy/article/details/21976997


環(huán)境: Android Studio 0.5.2, Gradle 1.11, kindle fire

時(shí)間: 2014-3-24


Earthquake項(xiàng)目, 主要是讀取USGS(United States Geological Survey, 美國(guó)地址勘探局)提供的feeds(訂閱源), 進(jìn)行顯示數(shù)據(jù);

需要讀取互聯(lián)網(wǎng)的數(shù)據(jù), 進(jìn)行格式解析(parse), 數(shù)據(jù)類(lèi)型是atom類(lèi)型, 類(lèi)似XML.

訂閱源地址: http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.atom

格式:

<feed xmlns="http://www.w3.org/2005/Atom" xmlns:georss="http://www.georss.org/georss"> <title>USGS Magnitude 2.5+ Earthquakes, Past Day</title> <updated>2014-03-24T07:56:39Z</updated> <author> <name>U.S. Geological Survey</name> <uri>http://earthquake.usgs.gov/</uri> </author> <id> http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.atom </id> <link rel="self" href="http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.atom"/> <icon>http://earthquake.usgs.gov/favicon.ico</icon> <entry> <id>urn:earthquake-usgs-gov:ci:15479569</id> <title>M 2.9 - 9km W of Alberto Oviedo Mota, Mexico</title> <updated>2014-03-24T07:48:34.609Z</updated> <link rel="alternate" type="text/html" href="http://earthquake.usgs.gov/earthquakes/eventpage/ci15479569"/> <summary type="html"> <![CDATA[ <p class="quicksummary"><a href="http://earthquake.usgs.gov/earthquakes/eventpage/ci15479569#dyfi" class="mmi-I" title="Did You Feel It? maximum reported intensity (0 reports)">DYFI? - <strong class="roman">I</strong></a></p><dl><dt>Time</dt><dd>2014-03-24 07:38:10 UTC</dd><dd>2014-03-23 23:38:10 -08:00 at epicenter</dd><dt>Location</dt><dd>32.222°N 115.274°W</dd><dt>Depth</dt><dd>14.10 km (8.76 mi)</dd></dl> ]]> </summary> <georss:point>32.2215 -115.274</georss:point> <georss:elev>-14100</georss:elev> <category label="Age" term="Past Hour"/> <category label="Magnitude" term="Magnitude 2"/> </entry> ...... ......

Earthquake的具體設(shè)計(jì):

新建項(xiàng)目: Earthquake


1. 新建Quake(Quake.java)類(lèi), 顯示地震數(shù)據(jù).

位置: java->package->Quake

package mzx.spike.earthquake.app;  import android.location.Location;  import java.text.SimpleDateFormat; import java.util.Date;  public class Quake {     private Date date;     private String details;     private Location location;     private double magnitude;     private String link;      public Date getDate() { return date; }     public String getDetails() { return details; }     public Location getLocation() { return location; }     public double getMagnitude() { return magnitude; }     public String getLink() { return link; }      public Quake(Date _d, String _det, Location _loc, double _mag, String _link) {         date = _d;         details = _det;         location = _loc;         magnitude = _mag;         link = _link;     }      @Override     public String toString() {         SimpleDateFormat sdf = new SimpleDateFormat("HH.mm");         String dateString = sdf.format(date);         return dateString + ": " + magnitude + " " + details;     }  }

詳解:

1. 顯示的類(lèi)型: date, 日期; details, 詳細(xì)信息, 地點(diǎn); location, 位置; magnitude, 震級(jí); link, 鏈接;

2. get()方法, 返回信息; 構(gòu)造函數(shù), 賦初值; toString(), 默認(rèn)輸出信息;


2. 修改activity_main.xml, 添加fragment.

位置: res->layout->activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin"     android:paddingBottom="@dimen/activity_vertical_margin"     tools:context="mzx.spike.earthquake.app.MainActivity">      <fragment android:name="mzx.spike.earthquake.app.EarthquakeListFragment"         android:id="@+id/EarthquakeListFragment"         android:layout_width="match_parent"         android:layout_height="match_parent"     /> </RelativeLayout> 

添加Fragment, 指定實(shí)現(xiàn)(.java)文件位置.


3. 新建EarthquakeListFragment.java

位置: java->package->EarthquakeListFragment.java

package mzx.spike.earthquake.app;  import android.app.ListFragment; import android.location.Location; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.widget.ArrayAdapter;  import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException;  import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.GregorianCalendar;  import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException;  public class EarthquakeListFragment extends ListFragment {      ArrayAdapter<Quake> aa;     ArrayList<Quake> earthquakes = new ArrayList<Quake>();      @Override     public void onActivityCreated(Bundle savedInstanceState) {         super.onActivityCreated(savedInstanceState);          int layoutID = android.R.layout.simple_list_item_1;         aa = new ArrayAdapter<Quake>(getActivity(), layoutID , earthquakes);         setListAdapter(aa);          Thread t = new Thread(new Runnable() {             @Override             public void run() {                 refreshEarthquakes();             }         });          t.start();     }      private static final String TAG = "EARTHQUAKE";     private Handler handler = new Handler();        private void refreshEarthquakes() {         // Get the XML         URL url;         try {              String quakeFeed = getString(R.string.quake_feed);             url = new URL(quakeFeed);              URLConnection connection;             connection = url.openConnection();              HttpURLConnection httpConnection = (HttpURLConnection)connection;             int responseCode = httpConnection.getResponseCode();              if (responseCode == HttpURLConnection.HTTP_OK) {                 InputStream in = httpConnection.getInputStream();                  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();                 DocumentBuilder db = dbf.newDocumentBuilder();                  // Parse the earthquake feed.                 Document dom = db.parse(in);                 Element docEle = dom.getDocumentElement();                  // Clear the old earthquakes                 earthquakes.clear();                  // Get a list of each earthquake entry.                 NodeList nl = docEle.getElementsByTagName("entry");                 if (nl != null && nl.getLength() > 0) {                     for (int i = 0 ; i < nl.getLength(); i++) {                          Element entry = (Element)nl.item(i);                         Element title = (Element)entry.getElementsByTagName("title").item(0);                         Element g = (Element)entry.getElementsByTagName("georss:point").item(0);                         Element when = (Element)entry.getElementsByTagName("updated").item(0);                         Element link = (Element)entry.getElementsByTagName("link").item(0);                          String details = title.getFirstChild().getNodeValue();                         String hostname = "http://earthquake.usgs.gov";                         String linkString = hostname + link.getAttribute("href");                          String point = g.getFirstChild().getNodeValue();                         String dt = when.getFirstChild().getNodeValue();                         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS'Z'");                         Date qdate = new GregorianCalendar(0,0,0).getTime();                         try {                            qdate = sdf.parse(dt);                         } catch (ParseException e) {                             Log.d(TAG, "Date parsing exception.", e);                         }                          String[] location = point.split(" ");                         Location l = new Location("dummyGPS");                         l.setLatitude(Double.parseDouble(location[0]));                         l.setLongitude(Double.parseDouble(location[1]));                          String magnitudeString = details.split(" ")[1];                         int end =  magnitudeString.length()-1;                         double magnitude = Double.parseDouble(magnitudeString.substring(0, end));                          details = details.split(",")[1].trim();                          final Quake quake = new Quake(qdate, details, l, magnitude, linkString);                          // Process a newly found earthquake                         handler.post(new Runnable() {                             @Override                             public void run() {                                 addNewQuake(quake);                             }                         });                      }                 }             }         } catch (MalformedURLException e) {             Log.d(TAG, "MalformedURLException", e);         } catch (IOException e) {             Log.d(TAG, "IOException", e);         } catch (ParserConfigurationException e) {             Log.d(TAG, "Parser Configuration Exception", e);         } catch (SAXException e) {             Log.d(TAG, "SAX Exception", e);         }         finally {         }     }      private void addNewQuake(Quake _quake) {         // Add the new quake to our list of earthquakes.         earthquakes.add(_quake);          // Notify the array adapter of a change.         aa.notifyDataSetChanged();     }  }

詳解:

1. 重寫(xiě)onActivityCreated()方法, 綁定適配器, 在線(xiàn)程(thread)中刷新地震信息(refreshEarthquakes);

2. 刷新地震信息refreshEarthquakes()方法, 根據(jù)訂閱源(feed), 創(chuàng)建HTTP鏈接;

3. 解析文檔(parse), 清空數(shù)據(jù)(clear);

4. 解析atom格式的標(biāo)簽, 根據(jù)標(biāo)簽屬性, 輸出相應(yīng)的信息;

5. 實(shí)例化(new)Quake類(lèi), 在handler(句柄)中, 運(yùn)行添加地震信息的方法(addNewQuake);

6. 注意鏈接需要相應(yīng)的異常捕獲(catch)方式, 否則報(bào)錯(cuò);

7. 網(wǎng)絡(luò)調(diào)用(network call)在主Activity調(diào)用, 會(huì)報(bào)錯(cuò), 需要在線(xiàn)程,后臺(tái)(asynctask)運(yùn)行;

8. Handler會(huì)產(chǎn)生歧義, 注意使用Android的相應(yīng)類(lèi), 不是java的, 否則無(wú)法實(shí)例化(initialized)

9. 日期格式(SimpleDateFormat)解析, 需要匹配相應(yīng)的字符串, 否則拋出異常, 無(wú)法解析(parse);

10 添加新的地震信息(addNewQuake), 通知適配器(notifyDataSetChanged), 進(jìn)行改變.


4. 修改strings信息

位置: res->values->strings

<?xml version="1.0" encoding="utf-8"?> <resources>      <string name="app_name">Earthquake</string>     <string name="hello_world">Hello world!</string>     <string name="action_settings">Settings</string>     <string name="quake_feed">http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.atom</string> </resources> 

添加相應(yīng)的訂閱源(feeds).


5. 修改AndroidManifest.xml

位置: root->AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="mzx.spike.earthquake.app" >      <uses-permission android:name="android.permission.INTERNET"/>      <application         android:allowBackup="true"         android:icon="@drawable/ic_launcher"         android:label="@string/app_name"         android:theme="@style/AppTheme" >         <activity             android:name="mzx.spike.earthquake.app.MainActivity"             android:label="@string/app_name" >             <intent-filter>                 <action android:name="android.intent.action.MAIN" />                  <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>     </application>  </manifest> 

提供網(wǎng)絡(luò)訪(fǎng)問(wèn)權(quán)限(permission), <uses-permission android:name="android.permission.INTERNET"/>.


6. 運(yùn)行程序.


下載地址: http://download.csdn.net/detail/u012515223/7091879



Android - Earthquake(地震顯示器) 項(xiàng)目 詳解


網(wǎng)頁(yè)標(biāo)題:Android-Earthquake(地震顯示器)項(xiàng)目詳解
URL鏈接:http://bm7419.com/article46/iipjeg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號(hào)、關(guān)鍵詞優(yōu)化商城網(wǎng)站、網(wǎng)站設(shè)計(jì)、標(biāo)簽優(yōu)化、搜索引擎優(yōu)化

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站網(wǎng)頁(yè)設(shè)計(jì)