OSCHINA客戶端完全剖析(一)

首先感謝開源中國為我們帶來了學(xué)習(xí)資源:http://www.oschina.net/p/oschina-android-app
這份代碼雖然存在不少小瑕疵,但總體上是一個功能齊備的應(yīng)用,而且關(guān)鍵是其代碼非常易讀

今天先分析一下啟動及主界面

啟動頁
主界面

BaseApplication extends Application

這個類中主要是做了一些功能封裝:

  1. 已讀文章列表相關(guān)
/**
     * 放入已讀文章列表中
     *
     */
    public static void putReadedPostList(String prefFileName, String key,
                                         String value) {
        SharedPreferences preferences = getPreferences(prefFileName);
        int size = preferences.getAll().size();
        Editor editor = preferences.edit();
        if (size >= 100) {
            editor.clear();
        }
        editor.putString(key, value);
        apply(editor);
    }
  1. SharedPreferences相關(guān)
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static void apply(SharedPreferences.Editor editor) {
        if (sIsAtLeastGB) {
            editor.apply();
        } else {
            editor.commit();
        }
    }

    public static void set(String key, int value) {
        Editor editor = getPreferences().edit();
        editor.putInt(key, value);
        apply(editor);
    }
  1. 獲取String相關(guān)
    public static String string(int id) {
        return _resource.getString(id);
    }

    public static String string(int id, Object... args) {
        return _resource.getString(id, args);
    }
  1. Toast相關(guān)
public static void showToast(String message, int icon) {
        showToast(message, Toast.LENGTH_LONG, icon, Gravity.BOTTOM);
    }

    public static void showToastShort(int message) {
        showToast(message, Toast.LENGTH_SHORT, 0);
    }

AppContext extends BaseApplication

正式的自定義Application了,所做的事很簡單,看如下代碼:

@Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        init();
        initLogin();

        UIHelper.sendBroadcastForNotice(this); // 注一,其后會對這里進行說明
    }
private void init() {
        // 初始化網(wǎng)絡(luò)請求
        AsyncHttpClient client = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
        client.setCookieStore(myCookieStore);
        ApiHttpClient.setHttpClient(client);
        ApiHttpClient.setCookie(ApiHttpClient.getCookie(this));

        // Log控制器
        KJLoger.openDebutLog(true);
        TLog.DEBUG = BuildConfig.DEBUG;

        // Bitmap緩存地址
        HttpConfig.CACHEPATH = "OSChina/imagecache";
    }

登錄信息相關(guān):

private void initLogin() {
        User user = getLoginUser();
        if (null != user && user.getId() > 0) {
            login = true;
            loginUid = user.getId();
        } else {
            this.cleanLoginInfo();
        }
    }

還有就是代碼中封裝了Properties的使用,雖然使用SharedPreferences會占用內(nèi)存,但個人認為這里數(shù)據(jù)量很少并不是很有必要,實際操作代碼封裝在AppConfig中:

    public Properties getProperties() {
        return AppConfig.getAppConfig(this).get();
    }

    public void setProperty(String key, String value) {
        AppConfig.getAppConfig(this).set(key, value);
    }

AppStart extends Activity

入口Activity,實現(xiàn)啟動頁,方法是設(shè)置其style為全屏無ActionBar,延時跳轉(zhuǎn):

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 防止第三方跳轉(zhuǎn)時出現(xiàn)雙實例
        Activity aty = AppManager.getActivity(MainActivity.class);
        if (aty != null && !aty.isFinishing()) {
            finish();
        }
        // SystemTool.gc(this); //針對性能好的手機使用,加快應(yīng)用相應(yīng)速度

        final View view = View.inflate(this, R.layout.app_start, null);
        setContentView(view);
        // 漸變展示啟動屏
        AlphaAnimation aa = new AlphaAnimation(0.5f, 1.0f);
        aa.setDuration(800);
        view.startAnimation(aa);
        aa.setAnimationListener(new AnimationListener() {
            @Override
            public void onAnimationEnd(Animation arg0) {
                redirectTo();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {}

            @Override
            public void onAnimationStart(Animation animation) {}
        });
    }

另外說一句,該應(yīng)用使用了一個AppManager來對所有Activity進行堆棧式管理,實現(xiàn)完全退出應(yīng)用。

而跳轉(zhuǎn)到主Activity之前,則先開啟了一個用來上傳Log的Service:

/**
     * 跳轉(zhuǎn)到...
     */
    private void redirectTo() {
        Intent uploadLog = new Intent(this, LogUploadService.class);
        startService(uploadLog);
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

MainActivity extends ActionBarActivity

這里做的事就比較多了,只撿關(guān)鍵的講,上面的注一在initView()中有了眉目:

IntentFilter filter = new IntentFilter(Constants.INTENT_ACTION_NOTICE);
        filter.addAction(Constants.INTENT_ACTION_LOGOUT);
        registerReceiver(mReceiver, filter); // 注二
        NoticeUtils.bindToService(this);

NoticeUtils中:

public static boolean bindToService(Context context) {
        return bindToService(context, null);
    }

    public static boolean bindToService(Context context,
            ServiceConnection callback) {
        context.startService(new Intent(context, NoticeService.class));
        ServiceBinder sb = new ServiceBinder(callback);
        sConnectionMap.put(context, sb);
        return context.bindService(
                (new Intent()).setClass(context, NoticeService.class), sb, 0);
    }

最終是綁定了一個NoticeService,而在注一中,其執(zhí)行代碼正為發(fā)送目標為NoticeService的廣播:

    /**
     * 發(fā)送通知廣播
     * 
     * @param context
     */
    public static void sendBroadcastForNotice(Context context) {
        Intent intent = new Intent(NoticeService.INTENT_ACTION_BROADCAST);
        context.sendBroadcast(intent);
    }

而在NoticeService之中,其后續(xù)動作為發(fā)送Action為Constants.INTENT_ACTION_NOTICE的廣播,該廣播許多地方都會監(jiān)聽,而在MainActivity中也有注冊監(jiān)聽(見注二),最后會有一個BadgeView 控件發(fā)生改變:

private BadgeView mBvNotice;

    public static Notice mNotice;

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Constants.INTENT_ACTION_NOTICE)) {
                mNotice = (Notice) intent.getSerializableExtra("notice_bean");
                int atmeCount = mNotice.getAtmeCount();// @我
                int msgCount = mNotice.getMsgCount();// 留言
                int reviewCount = mNotice.getReviewCount();// 評論
                int newFansCount = mNotice.getNewFansCount();// 新粉絲
                int newLikeCount = mNotice.getNewLikeCount();// 收到贊
                int activeCount = atmeCount + reviewCount + msgCount
                        + newFansCount + newLikeCount;

                Fragment fragment = getCurrentFragment();
                if (fragment instanceof MyInformationFragment) {
                    ((MyInformationFragment) fragment).setNotice();
                } else {
                    if (activeCount > 0) {
                        mBvNotice.setText(activeCount + "");
                        mBvNotice.show();
                    } else {
                        mBvNotice.hide();
                        mNotice = null;
                    }
                }
            } else if (intent.getAction()
                    .equals(Constants.INTENT_ACTION_LOGOUT)) {
                mBvNotice.hide();
                mNotice = null;
            }
        }
    };

主界面實現(xiàn)

FragmentTabHost即可,布局片段如下:

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <FrameLayout
            android:id="@+id/realtabcontent"
            android:layout_width="match_parent"
            android:layout_height="0dip"
            android:layout_weight="1" />

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/windows_bg" >

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="4dip" >

                <net.oschina.app.widget.MyFragmentTabHost
                    android:id="@android:id/tabhost"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="4dip" />
                <View
                    android:layout_width="match_parent"
                    android:layout_height="1px"
                    android:background="?attr/lineColor" />

            </RelativeLayout>

            <!-- 快速操作按鈕 -->

            <ImageView
                android:id="@+id/quick_option_iv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:contentDescription="@null"
                android:src="@drawable/btn_quickoption_selector" />
        </FrameLayout>
    </LinearLayout>

realtabcontent分割剩余空間,為實際內(nèi)容頁:

實際內(nèi)容頁

在initView()中進行了setup:

mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

中鍵點擊的效果不一樣,不是Fragment頁面,而是一個自定義Dialog了:

所以,實現(xiàn)上quick_option_iv這個ImageView在布局中對第三個Tab進行了遮擋。
而第三個Tab也需要特殊處理:它在點擊時不切換頁面。
在MyFragmentTabHost extends FragmentTabHost中:

@Override
    public void onTabChanged(String tag) {
        
        if (tag.equals(mNoTabChangedTag)) {// 對第三個Tab特殊處理
            setCurrentTabByTag(mCurrentTag);
        } else {
            super.onTabChanged(tag);
            mCurrentTag = tag;
        }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,030評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,310評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,951評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,796評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,566評論 6 407
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,055評論 1 322
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,142評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,303評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,799評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,683評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,899評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,409評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,135評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,520評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,757評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,528評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,844評論 2 372

推薦閱讀更多精彩內(nèi)容

  • ¥開啟¥ 【iAPP實現(xiàn)進入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 6,482評論 0 17
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,781評論 18 139
  • #Android 基礎(chǔ)知識點總結(jié) ---------- ##1.adb - android debug bridg...
    Mythqian閱讀 3,324評論 2 11
  • 流量管理的位置在com.oneplus.security.network下面 包含 calibrate 校準功能包...
    panberglee閱讀 1,188評論 2 2
  • 第一行代碼-第二版的酷歐天氣 首先創(chuàng)建數(shù)據(jù)庫類繼承LitePal,用來存儲城市數(shù)據(jù)Province.java p...
    A_Coder閱讀 2,127評論 0 0