OSCHINA客戶端完全剖析(一)

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

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

啟動頁
主界面

BaseApplication extends Application

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

  1. 已讀文章列表相關
/**
     * 放入已讀文章列表中
     *
     */
    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相關
@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相關
    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相關
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() {
        // 初始化網絡請求
        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";
    }

登錄信息相關:

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

還有就是代碼中封裝了Properties的使用,雖然使用SharedPreferences會占用內存,但個人認為這里數據量很少并不是很有必要,實際操作代碼封裝在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,實現啟動頁,方法是設置其style為全屏無ActionBar,延時跳轉:

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

        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) {}
        });
    }

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

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

/**
     * 跳轉到...
     */
    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

這里做的事就比較多了,只撿關鍵的講,上面的注一在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,而在注一中,其執行代碼正為發送目標為NoticeService的廣播:

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

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

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;
            }
        }
    };

主界面實現

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分割剩余空間,為實際內容頁:

實際內容頁

在initView()中進行了setup:

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

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

所以,實現上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;
        }
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容