學習筆記(豆瓣客戶端)

一、splash界面檢查網絡

1.判斷網絡連接狀態:

    private boolean isNetworkConnected(){
        ConnectivityManager cm =    (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        
        NetworkInfo info =cm.getActiveNetworkInfo();
        if(info!=null&&info.isConnected()){
            return true;
        }else {
            return false ;
        }
        
    }

2. 獲取軟件版本:

     private String getVersion() {
        PackageManager pm = getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(getPackageName(), 0);
            return info.versionName;
        } catch (NameNotFoundException e) {

            e.printStackTrace();
            return  "";
        }
    }


二、主界面(TabActivity)

xml基本佈局,TabHost android:id="@android:id/tabhost"必須包括<TabWidget android:id="@android:id/tabs"....和<FrameLayout android:id="@android:id/tabcontent"...兩個組件

<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:id="@android:id/tabhost"
    android:layout_height="fill_parent" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="60dip"
            android:layout_alignParentBottom="true" >
        </TabWidget>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_marginBottom="60dip" >
        </FrameLayout>
    </RelativeLayout>

</TabHost>


java文件裏面添加tabView(關鍵類TabSpec)

        mTabHost = getTabHost();
        TabSpec myDoubanTab = mTabHost.newTabSpec("我的豆瓣");
        //指定要顯示的具體內容
        Intent intent = new Intent(this,MyDoubanActivity.class);
        myDoubanTab.setContent(intent);
        //設置顯示的標題內容
        myDoubanTab.setIndicator(getTabView(R.drawable.tab_main_nav_me, "我的豆瓣"));
        mTabHost.addTab(myDoubanTab);


三、tabView相關內容

1.listView

xml裏listview  divider設置listitem之間的間隔

    <ListView
        android:id="@+id/melistview"
        android:layout_width="fill_parent"
        android:layout_height="0.0dip"
        android:layout_marginLeft="5.0dip"
        android:layout_marginRight="3.0dip"
        android:layout_weight="1.0"
        android:cacheColorHint="#00000000"
        android:divider="@android:color/transparent"
        android:dividerHeight="5.0dip"
        android:listSelector="@android:color/transparent"
        android:paddingTop="5.0dip"
        android:scrollbarStyle="outsideInset" />


四、模擬網頁登陸、獲取驗證碼


public class NetUtil {
    private static final String loginserver = "http://www.douban.com/accounts/login";

    /**
     *
     * @param username
     *            用戶名
     * @param password
     *            用戶密碼
     * @return
     */
    public static List<String> getAccessToken(String username, String password,
            String captcha_id, String captcha_solution) {
        try {
            String apiKey = "078409f18961d372168c1dd49c257a56";
            String secret = "0dd3419e39fe4b2c";
            DoubanService myService = new DoubanService("黑馬6的小豆瓣", apiKey,
                    secret);
            // 1.模擬用戶登陸豆瓣官網的行爲->主要是爲了回去豆瓣登陸成功的cookie
            // httppost的請求 ,最方便的就是採用httpclient 開源的jar包
            DefaultHttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(loginserver);
            // 設置post信息對應的數據實體
            List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
            parameters.add(new BasicNameValuePair("source", "simple"));
            parameters.add(new BasicNameValuePair("redir",
                    "http://www.douban.com"));
            parameters.add(new BasicNameValuePair("form_email",
                    "[email protected]"));
            parameters.add(new BasicNameValuePair("form_password", "a11111"));
            if (TextUtils.isEmpty(captcha_solution)
                    || TextUtils.isEmpty(captcha_id)) {
                
            }else{
                parameters.add(new BasicNameValuePair("captcha-solution",
                        captcha_solution));
                parameters
                        .add(new BasicNameValuePair("captcha-id", captcha_id));
            }

            parameters.add(new BasicNameValuePair("user_login", "登陸"));
            post.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));
            HttpResponse response = client.execute(post);
            System.out.println(response.getStatusLine().getStatusCode());
            InputStream is = response.getEntity().getContent();
            // 把服務器返回回來的inputstream裏面的內容 包裝成一個html的對象
            Source source = new Source(is);
            System.out.println(source.toString());
            CookieStore cookies = client.getCookieStore();

            /*
             * //新開了一個瀏覽器,把剛纔登陸成功的cookie信息設置給這個新開的瀏覽器 DefaultHttpClient client2
             * = new DefaultHttpClient(); client2.setCookieStore(cookies);
             */
            String path = myService.getAuthorizationUrl(null);
            // 模擬用戶的同意的點擊事件
            HttpPost agreePost = new HttpPost(path);
            List<BasicNameValuePair> agreeParameters = new ArrayList<BasicNameValuePair>();
            agreeParameters.add(new BasicNameValuePair("ck", "wViC"));
            int start = path.lastIndexOf("=") + 1;
            String oauth_token = path.substring(start, path.length());
            agreeParameters.add(new BasicNameValuePair("oauth_token",
                    oauth_token));
            agreeParameters.add(new BasicNameValuePair("oauth_callback", ""));
            agreeParameters.add(new BasicNameValuePair("ssid", "8e4a1f5b"));
            agreeParameters.add(new BasicNameValuePair("confirm", "同意"));
            agreePost.setEntity(new UrlEncodedFormEntity(agreeParameters,
                    "UTF-8"));
            client.execute(agreePost);
            ArrayList<String> tokens = myService.getAccessToken();
            // 3.授權成功後 返回兩把鑰匙, 後門的鑰匙
            System.out.println("accesstoken " + tokens.get(0));
            System.out.println("token secret " + tokens.get(1));
            return tokens;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 判斷是否需要輸入驗證碼
     *
     * @return
     * @throws Exception
     */
    public static boolean needCaptcha() throws Exception {
        boolean result = false;
        URL url = new URL("http://www.douban.com/accounts/login");
        URLConnection conn = url.openConnection();
        Source source = new Source(conn);
        List<Element> inputs = source.getAllElements("input");
        for (Element input : inputs) {
            // System.out.println(input.getAttributeValue("name"));
            if ("captcha-id".equals(input.getAttributeValue("name"))) {
                result = true;
                return result;
            }
        }

        return false;
    }

    /**
     * 獲取驗證碼對應的bitmap
     */
    public static CaptchaBean getCaptchaBitmap() throws Exception {
        URL url = new URL("http://www.douban.com/accounts/login");
        CaptchaBean bean = new CaptchaBean();
        URLConnection conn = url.openConnection();
        Source source = new Source(conn);
        List<Element> inputs = source.getAllElements("input");
        for (Element input : inputs) {
            // System.out.println(input.getAttributeValue("name"));
            if ("captcha-id".equals(input.getAttributeValue("name"))) {

                String id = input.getAttributeValue("value");

                String path = "http://www.douban.com/misc/captcha?id=" + id
                        + "&amp;size=s";
                URL iconurl = new URL(path);
                InputStream is = iconurl.openStream();
                bean.setBitmap(BitmapFactory.decodeStream(is));
                bean.setId(id);
                return bean;
            }
        }
        return null;
    }


五、獲取信息

異步

    /**
     * 完成數據和事件的處理
     */
    public void setupView() {
        new AsyncTask<Void, Void, UserEntry>(){
            /**在後臺任務執行之前被調用 運行在ui線程裏面的
             */
            @Override
            protected void onPreExecute() {
                loading.setVisibility(View.VISIBLE);
                super.onPreExecute();
            }
            /**
             * 在後臺任務執行完畢後調用,運行在ui線程裏面的
             */
            @Override
            protected void onPostExecute(UserEntry result) {
                super.onPostExecute(result);
                loading.setVisibility(View.INVISIBLE);
                
                if(result!=null){
                    
                    txtUserAddress.setText( result.getLocation());
                    txtUserDescription.setText( ((TextContent) result.getContent()).getContent().getPlainText());
                    txtUserName.setText( result.getTitle().getPlainText());
                }else{
                    MyToast.showToast(getApplicationContext(), "獲取數據失敗", 1);
                }
            }

            /**
             * 在子線程裏面執行的任務 可以運行一些耗時的操作
             */
            @Override
            protected UserEntry doInBackground(Void... params) {
                try {
                    String id = myService.getAuthorizedUser().getUid();        
                    UserEntry ue = myService.getUser(id);
                    return ue;
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
                
                
            }
            
            
        }.execute();
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章