標籤:des android style http io color ar os 使用
前面把主要的東西講完了,之後就是資料的擷取和解析顯示出來了,那接下來我們就負責抓取資料的這塊吧,首先我們需要
在資訊清單檔裡載入服務和活動
添加:、
<activity android:name="com.neweriweibo.activity.OAuthActivity"/> <activity android:name=".MainActivity"/> <activity android:name="com.neweriweibo.activity.SendMessageActivity"/> <!-- 擷取自己微博資訊 --> <service android:name="com.neweriweibo.service.UserService"/> <!-- 擷取所有微博的資訊 --> <service android:name="com.neweriweibo.service.WeiBoService"/>
下面看看使用者個人資訊的抓取:
package com.neweriweibo.service;/** * 個人資訊資料抓取、 * @author Engineer-Jsp * @date 2014.10.28 * */import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import org.json.JSONArray;import org.json.JSONObject;import com.neweriweibo.model.User;import com.neweriweibo.utils.TencentAPI;import android.app.IntentService;import android.content.Intent;import android.os.Bundle;import android.os.Environment;import android.preference.PreferenceManager;import android.util.Log;public class UserService extends IntentService {public final static String UPDATA = "com.neweriweibo.service.UPDATA";public final static String NOW_WEATHER = "UserWeiBo" ;private StringBuffer _buff;private File weibousercurrentFile;private BufferedWriter write;private BufferedWriter writefour;private static BufferedReader reader ;private String access_token;private String openid;private String openkey;public UserService(){super("WeatherService") ;}@Overridepublic void onCreate() {super.onCreate();weibousercurrentFile = new File(Environment.getExternalStorageDirectory(), "weiinfo");if (!weibousercurrentFile.exists()) {try {weibousercurrentFile.createNewFile();// 建立} catch (IOException e) {e.printStackTrace();} }access_token = PreferenceManager.getDefaultSharedPreferences(this).getString("access_token", "access_token");openid = PreferenceManager.getDefaultSharedPreferences(this).getString("openid", "openid");openkey = PreferenceManager.getDefaultSharedPreferences(this).getString("openkey", "openkey");}@Overridepublic void onDestroy() {super.onDestroy();}/** * https://open.t.qq.com/api/user/info * ?oauth_consumer_key=801506473 * &access_token=789a7d5284d0c3e608f8e384c993d04b * &openid=0027BC08DB5B45D7461E9A0F16F527E7 * &clientip=CLIENTIP&oauth_version=2.a&scope=all */@Overrideprotected void onHandleIntent(Intent intent) {// oauth_consumer_key=801506545&access_token=c63ed52ee874eff6e61dfe66d2c7b396&openid=0027BC08DB5B45D7461E9A0F16F527E7&clientip=CLIENTIP&oauth_version=2.a&scope=all // oauth_consumer_key=xx&access_token=xx&openid=xx&clientip=xx&oauth_version=2.a&scope=xxUser weibouser = new User();StringBuffer buff = new StringBuffer(TencentAPI.userInfo) ;buff.append("?").append("oauth_consumer_key="+TencentAPI.client_id ).append("&access_token="+access_token).append("&openid="+openid).append("&clientip=CLIENTIP&oauth_version=2.a&scope=all") ;Log.i("擷取當前登入賬戶個人資訊的請求地址:", buff.toString()+"") ; try {URL _url = new URL(buff.toString());HttpURLConnection conn = (HttpURLConnection) _url.openConnection();conn.setConnectTimeout(8000);conn.setReadTimeout(8000);conn.setDoOutput(false);conn.setRequestMethod("GET");if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {InputStream in = conn.getInputStream();InputStreamReader reader = new InputStreamReader(in, "utf-8");BufferedReader buffere = new BufferedReader(reader);StringBuilder builder = new StringBuilder();String line = null;while (null != (line = buffere.readLine())) {builder.append(line);}String json = builder.toString();Log.i("擷取當前登入賬戶個人資訊的資料:", json.toString()+"\n") ;// 解析資料 JSONObject root = new JSONObject(json).getJSONObject("data") ; JSONArray tweetinfo = root.getJSONArray("tweetinfo"); Log.d("使用者最近的一條原創微博:", tweetinfo.toString()); JSONObject zero = tweetinfo.getJSONObject(0); String nearinfo = zero.getString("text"); Log.d("原創微博資訊:", nearinfo.toString()); String nick = root.getString("nick") ; String idolnum = root.getString("idolnum") ; String location = root.getString("location") ; String brithyear = root.getString("birth_year") ; String brithmonth = root.getString("birth_month") ; String brithday = root.getString("birth_day") ; String introduction = root.getString("introduction") ; String headimg = root.getString("head")+"/40"; String fansnum = root.getString("fansnum"); String tweetnum = root.getString("tweetnum"); String sex = root.getString("sex"); Log.d("sex內容測試,剛取得:", sex); if(sex.equals("1")){ sex = "男"; }else if(sex.equals("2")){ sex = "女"; }else{ sex = ""; } Log.d("sex內容測試,判斷後:", sex); write = new BufferedWriter(new FileWriter(weibousercurrentFile));write.write(nick + "*" + idolnum + "*" + location+ "*" + brithyear+"/"+brithmonth+"/"+brithday+"*"+introduction+"*"+headimg+"*"+fansnum+"*"+tweetnum+"*"+sex+"*"+nearinfo);write.close(); weibouser.setNick(nick) ;weibouser.setIdonum(idolnum);weibouser.setLoacation(location) ;weibouser.setBirthyeaer(brithyear);weibouser.setBirthmonth(brithmonth);weibouser.setBirthday(brithday) ; weibouser.setHeadimg(headimg);weibouser.setInfo(introduction) ;weibouser.setFansnum(fansnum);weibouser.setTweetnum(tweetnum);weibouser.setSex(sex);weibouser.setNearinfo(nearinfo);conn.disconnect();}} catch (Exception e) {e.printStackTrace();} Intent _intent = new Intent(UPDATA);Bundle mBundle = new Bundle();mBundle.putParcelable(UserService.NOW_WEATHER, weibouser);_intent.putExtras(mBundle);sendBroadcast(_intent) ;}}
常規的網路請求抓取資料,將解析到的資料存在User對象裡,並且在本地用BuffereWriter儲存了一份,方便下登入,且考慮在沒有網路的情況下或者資料抓取失敗的情況下不至於介面因沒有資料而顯得空洞,不美觀
將擷取的資料意圖發送至應用程式,其他活動接收,並擷取資料,顯示在介面
User:
package com.neweriweibo.model;/** * 使用者資訊對象 * @author Engineer-Jsp * @date 2014.10.28 * */import android.os.Parcel;import android.os.Parcelable;public class User implements Parcelable{private String nick ;// 暱稱private String info ;// 自我介紹private String loacation ;// 所在地private String idonum ; //關注的人數private String birthyeaer ;// 生日年private String birthmonth ;// 生日月private String birthday ;// 生日天private String headimg;// 頭像private String fansnum;// 被關注數private String tweetnum; // 發表的微博數private String sex; // 性別 private String nearinfo; //使用者最近的一條原創微博public String getNearinfo() {return nearinfo;}public void setNearinfo(String nearinfo) {this.nearinfo = nearinfo;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public String getFansnum() {return fansnum;}public void setFansnum(String fansnum) {this.fansnum = fansnum;}public String getTweetnum() {return tweetnum;}public void setTweetnum(String tweetnum) {this.tweetnum = tweetnum;}public String getHeadimg() {return headimg;}public void setHeadimg(String headimg) {this.headimg = headimg;}public String getNick() {return nick;}public void setNick(String nick) {this.nick = nick;}public String getInfo() {return info;}public void setInfo(String info) {this.info = info;}public String getLoacation() {return loacation;}public void setLoacation(String loacation) {this.loacation = loacation;}public String getIdonum() {return idonum;}public void setIdonum(String idonum) {this.idonum = idonum;}public String getBirthyeaer() {return birthyeaer;}public void setBirthyeaer(String birthyeaer) {this.birthyeaer = birthyeaer;}public String getBirthmonth() {return birthmonth;}public void setBirthmonth(String birthmonth) {this.birthmonth = birthmonth;}public String getBirthday() {return birthday;}public void setBirthday(String birthday) {this.birthday = birthday;}public User(String nick, String info, String loacation, String idonum,String birthyeaer, String birthmonth, String birthday,String headimg,String fansnum , String tweetnum,String sex,String nearinfo) {super();this.nick = nick;this.info = info;this.loacation = loacation;this.idonum = idonum;this.birthyeaer = birthyeaer;this.birthmonth = birthmonth;this.birthday = birthday;this.headimg = headimg;this.fansnum = fansnum;this.tweetnum = tweetnum;this.sex = sex;this.nearinfo = nearinfo;}public User() {super();// TODO Auto-generated constructor stub}@Overridepublic String toString() {return "User [暱稱=" + nick + ", 自我介紹=" + info + ", 城市="+ loacation + ", 關注數=" + idonum + ", 年="+ birthyeaer + ", 月=" + birthmonth + ", 日="+ birthday + ",頭像地址="+headimg+",聽眾="+fansnum+",發表微博數="+tweetnum+",性別="+sex+",最近動態="+nearinfo+"]";}public static final Parcelable.Creator<User> CREATOR = new Creator<User>() {@Overridepublic User createFromParcel(Parcel source) {// TODO Auto-generated method stubUser user = new User() ;user.nick = source.readString() ;user.info = source.readString() ;user.loacation = source.readString() ;user.idonum = source.readString() ;user.birthyeaer = source.readString() ;user.birthmonth = source.readString() ;user.birthday = source.readString() ;user.headimg = source.readString();user.fansnum = source.readString();user.tweetnum = source.readString();user.sex = source.readString();user.nearinfo = source.readString();return user;}@Overridepublic User[] newArray(int size) {// TODO Auto-generated method stubreturn new User[size];}};@Overridepublic int describeContents() {// TODO Auto-generated method stubreturn 0;}@Overridepublic void writeToParcel(Parcel dest, int flags) {// TODO Auto-generated method stubdest.writeString(nick);dest.writeString(info);dest.writeString(loacation);dest.writeString(idonum);dest.writeString(birthyeaer);dest.writeString(birthmonth);dest.writeString(birthday);dest.writeString(headimg);dest.writeString(fansnum);dest.writeString(tweetnum);dest.writeString(sex);dest.writeString(nearinfo);}}
UserService extends IntentService 重寫onHandleIntent(Intent intent) ,其實就相當於開啟了一個子線程,來對網路請求進行處理,IntentService使用隊列的方式將請求的Intent排入佇列,然後開啟一個worker thread(線程)來處理隊列中的Intent,對於非同步startService請求,IntentService會處理完成一個之後再處理第二個,每一個請求都會在一個單獨的worker thread中處理,不會阻塞應用程式的主線程,這裡就給我們提供了一個思路,如果有耗時的操作與其在Service裡面開啟新線程還不如使用IntentService來處理耗時操作
Android MaoZhuaWeiBo開發Service抓取個人資訊-2