前面把主要的东西讲完了,之后就是数据的获取和解析显示出来了,那接下来我们就负责抓取数据的这块吧,首先我们需要
在清单文件里加载服务和活动
添加:、
<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") ; } @Override public 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"); } @Override public 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 */ @Override protected 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=xx User 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 } @Override public 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>() { @Override public User createFromParcel(Parcel source) { // TODO Auto-generated method stub User 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; } @Override public User[] newArray(int size) { // TODO Auto-generated method stub return new User[size]; } }; @Override public int describeContents() { // TODO Auto-generated method stub return 0; } @Override public void writeToParcel(Parcel dest, int flags) { // TODO Auto-generated method stub dest.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来处理耗时操作
时间: 2024-11-08 01:23:03