編輯:關於 Android 程式設計
項目做到一定規模後,代碼開始互相纏繞、Activity 越寫越胖,這時候就需要重構。本文從項目結構、Activity 生命週期、事件編程模型、實體化編程、Adapter 模板和類型安全轉換六個方面,記錄一套可落地的重構方案。
第一步是抽出一個 AndroidLib 類庫,把與業務無關的邏輯全部下沉,至少包含五個部分:
activity —— Activity 基類 net —— 網絡底層封裝 cache —— 數據與圖片緩存 ui —— 自定義控件 utils —— 與業務無關的公共方法
Activity 基類的層級設計如下:
public abstract class BaseActivity extends Activity { }
public abstract class AppBaseActivity extends BaseActivity { }
// 具體的 Activity 直接繼承 AppBaseActivity
第二步是把主項目中的類按職責分門別類:
activity —— Activity adapter —— 適配器 entity —— 所有實體 db —— SQLite 相關邏輯封裝 engine —— 業務相關的類 ui —— 自定義控件 utils —— 共用方法 interfaces —— 真正的接口,以 I 命名 listener —— 基於 Listener 的接口,以 On 開頭
設計模式裡有一條單一職責原則:一個類或方法只做一件事。拿它來審視 onCreate,就會發現我們通常在裡面塞了初始化變量、初始化視圖、加載數據好幾件事。借鑑 JavaScript 的習慣,把 onCreate 拆細:
public abstract class BaseActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initVariables();
initViews(savedInstanceState);
loadData();
}
protected abstract void initVariables();
protected abstract void initViews(Bundle savedInstanceState);
protected abstract void loadData();
}
子類只需要填空:
public class LoginNewActivity extends AppBaseActivity implements View.OnClickListener {
private int loginTimes;
private String strEmail;
private EditText etPassword;
private EditText etEmail;
private Button btnLogin;
@Override
protected void initVariables() {
loginTimes = -1;
Bundle bundle = getIntent().getExtras();
strEmail = bundle.getString(AppConstants.Email);
}
@Override
protected void initViews(Bundle savedInstanceState) {
setContentView(R.layout.activity_login);
etEmail = (EditText) findViewById(R.id.email);
etEmail.setText(strEmail);
etPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.sign_in_button);
btnLogin.setOnClickListener(this);
}
@Override
protected void loadData() {
loadWeatherData();
loadCityData();
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.sign_in_button:
gotoLoginActivity();
break;
}
}
private void gotoLoginActivity() {
startActivity(new Intent(LoginNewActivity.this, PersonCenterActivity.class));
}
private void loadWeatherData() { /* 發起網絡請求,從略 */ }
private void loadCityData() { /* 發起網絡請求,從略 */ }
}
常見寫法是實現 onClick 接口,再在 switch...case 裡用 R.id 篩選。但按面向對象的思路,initViews 之後就不該再出現 R.id。更好的做法是在初始化控件時直接綁定事件:
Button btnLogin = (Button) findViewById(R.id.sign_in_button);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
gotoLoginActivity();
}
});
兩個好處很直接:一是直接在控件對象上掛事件,符合面向對象的表達;二是把事件實現收攏成獨立方法,代碼不再臃腫。
JSONObject 和 JSONArray 不支持序列化,跨頁面傳遞時只能掛全局變量,這並不明智。傳統的字典取值法有兩個痛點:鍵值對比實體晦澀、易出 bug;每次都要手動從 JSON 裡逐個取,非常繁瑣。
// 寫法一:直接操作 JSONObject
try {
JSONObject jsonResponse = new JSONObject(result);
JSONObject weatherinfo = jsonResponse.getJSONObject("weatherinfo");
String city = weatherinfo.getString("city");
int cityId = weatherinfo.getInt("cityid");
tvCity.setText(city);
tvCityId.setText(String.valueOf(cityId));
} catch (JSONException e) {
e.printStackTrace();
}
引入 fastJSON 或 Gson(記得先加對應的 jar 包),事情就清爽了:
public class WeatherInfo {
private String city;
private String cityid;
private String temp;
private String WD;
private String WS;
private String SD;
private String WSE;
private String time;
private String isRadar;
private String Radar;
private String njd;
private String qy;
// getter / setter 省略
}
public class WeatherEntity {
private WeatherInfo weatherinfo;
public WeatherInfo getWeatherInfo() { return weatherinfo; }
public void setWeatherInfo(WeatherInfo weatherinfo) { this.weatherinfo = weatherinfo; }
}
// 寫法二:fastJSON
WeatherEntity weatherEntity = JSON.parseObject(content, WeatherEntity.class);
WeatherInfo weatherInfo = weatherEntity.getWeatherInfo();
if (weatherInfo != null) {
tvCity.setText(weatherInfo.getCity());
tvCityId.setText(weatherInfo.getCityid());
}
// 寫法三:Gson
Gson gson = new Gson();
WeatherEntity weatherEntity = gson.fromJson(content, WeatherEntity.class);
WeatherInfo weatherInfo = weatherEntity.getWeatherInfo();
if (weatherInfo != null) {
tvCity.setText(weatherInfo.getCity());
tvCityId.setText(weatherInfo.getCityid());
}
這裡踩過一個坑值得記住:用了 fastJSON 之後,帶註解的實體屬性一用就崩,帶泛型的屬性一用也崩,調試時正常,但打簽名混淆包就必然出問題。解法是在混淆文件里保留相關信息:
-keepattributes Signature // 避免泛型被混淆 -keepattributes *Annotation* // 不混淆註解
另外推薦 Json Class Generator 這類實體生成工具,能一次生成 Android、iOS、Windows Phone 的實體類,省掉大量重複勞動。
偷懶的做法是全局變量:
CinemaBean cinema = new CinemaBean();
cinema.setCinemaId("1");
cinema.setCinemaName("星美");
GlobalVariables.Cinema = cinema; // 來源頁設置
CinemaBean cinema = GlobalVariables.Cinema; // 目標頁取值
if (cinema != null) {
cinemaName = cinema.getCinemaName();
} else {
cinemaName = "";
}
不建議這麼做:App 切到後台後,內存緊張時這些全局變量會被回收,回到前台再用就是空指針崩潰。如果非用不可,一定要把它們序列化到本地,這樣即使全局變量丟了也能從文件恢復。
更推薦用 Intent 掛載可序列化實體:
public class AppConstants {
public final static String Email = "Email";
public final static String Cinema = "Cinema";
}
// 傳遞
Intent intent = new Intent(MainActivity.this, LoginNewActivity.class);
intent.putExtra(AppConstants.Email, "jianqiang.bao@qq.com");
CinemaBean cinema = new CinemaBean();
cinema.setCinemaId("1");
cinema.setCinemaName("星美");
intent.putExtra(AppConstants.Cinema, cinema);
startActivity(intent);
// 接收
Bundle bundle = getIntent().getExtras();
strEmail = bundle.getString(AppConstants.Email);
CinemaBean cinema = (CinemaBean) getIntent().getSerializableExtra(AppConstants.Cinema);
if (cinema != null) {
cinemaName = cinema.getCinemaName();
} else {
cinemaName = "";
}
// CinemaBean 需實現 Serializable
public class CinemaBean implements Serializable {
private static final long serialVersionUID = 1L;
}
約定所有 Adapter 都繼承 BaseAdapter,並通過構造函數注入 List<自定義實體>:
public class CinemaAdapter extends BaseAdapter {
private final ArrayList<CinemaBean> cinemaList;
private final AppBaseActivity context;
public CinemaAdapter(ArrayList<CinemaBean> cinemaList, AppBaseActivity context) {
this.cinemaList = cinemaList;
this.context = context;
}
public int getCount() {
return cinemaList.size();
}
public CinemaBean getItem(final int position) {
return cinemaList.get(position);
}
public long getItemId(final int position) {
return position;
}
public View getView(final int position, View convertView, final ViewGroup parent) {
final Holder holder;
if (convertView == null) {
holder = new Holder();
convertView = context.getLayoutInflater().inflate(R.layout.item_cinemalist, null);
holder.tvCinemaName = (TextView) convertView.findViewById(R.id.tvCinemaName);
holder.tvCinemaId = (TextView) convertView.findViewById(R.id.tvCinemaId);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
CinemaBean cinema = cinemaList.get(position);
holder.tvCinemaName.setText(cinema.getCinemaName());
holder.tvCinemaId.setText(cinema.getCinemaId());
return convertView;
}
class Holder {
TextView tvCinemaName;
TextView tvCinemaId;
}
}
四個必須實現的方法是 getCount、getItem、getItemId、getView;內部 Holder 嵌套類用來緩存行內控件,避免反覆 findViewById 與重複創建對象,能顯著降低內存與 GC 壓力。Activity 側的使用方式:
public class ListDemoActivity extends AppBaseActivity {
ListView lvCinemaList;
ArrayList<CinemaBean> cinemaList;
@Override
protected void initVariables() {
cinemaList = new ArrayList<CinemaBean>();
CinemaBean cinema1 = new CinemaBean();
cinema1.setCinemaId("1");
cinema1.setCinemaName("星美");
CinemaBean cinema2 = new CinemaBean();
cinema2.setCinemaId("2");
cinema2.setCinemaName("萬達");
cinemaList.add(cinema1);
cinemaList.add(cinema2);
}
@Override
protected void initViews(Bundle savedInstanceState) {
setContentView(R.layout.activity_listdemo);
lvCinemaList = (ListView) findViewById(R.id.lvCinemalist);
CinemaAdapter adapter = new CinemaAdapter(cinemaList, ListDemoActivity.this);
lvCinemaList.setAdapter(adapter);
lvCinemaList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
// do something
}
});
}
@Override
protected void loadData() { }
}
統計線上崩潰會發現,類型轉換不當佔了很大比例,主要集中在兩處。
其一,Object 直接 toString,為 null 就崩。封裝一個工具方法即可:
public class Utils {
/**
* 對象轉化為整數類型
*/
public final static int convertToInt(Object value, int defaultValue) {
if (value == null || "".equals(value.toString().trim())) {
return defaultValue;
}
try {
return Integer.valueOf(value.toString());
} catch (Exception e) {
try {
return Double.valueOf(value.toString()).intValue();
} catch (Exception e1) {
return defaultValue;
}
}
}
}
// 使用
int result = Utils.convertToInt(obj, 0);
其二,字符串長度不夠時調 substring 會拋 StringIndexOutOfBoundsException。先判斷長度:
String cityName = "T";
String firstLetter = "";
if (cityName.length() > 1) {
firstLetter = cityName.substring(1, 2);
}
這兩類問題的根源都在接口返回數據上,由此引出另一個更嚴肅的結論:對待接口數據要分級。不需要加工就能直接展示的數據,即使為空只要頁面不顯示即可,不影響邏輯;而涉及金額、支付等關鍵判斷的數據一旦為空,就必須彈框提示服務暫不可用並中止後續流程,而不是帶着髒數據繼續往下跑。
Android 技巧:如何開啟應用程式的「詳細資訊」頁面
在 Android 系統的設定功能裡,進入應用程式列表後,點擊某個項目就會進入該應用的詳細資訊頁。那麼,我們能否自己寫一個程式來開啟這個頁面呢?答案是可行的,下面就一起來
Qt on Android 實踐:通過 JNI 調用系統原生分享菜單
原文《Sharing with Qt on Android》發表於 2014 年 12 月 12 日。當時我寫的遊戲 GiraffPanic(一款用 Qt & Q
Android 圖形渲染全路徑:從像素誕生到 SurfaceFlinger 合成上屏
在 UI 的畫圖流程中,我們先暫且不糾結「要畫的數據是怎麼填充的」,而是聚焦另一個問題:這些已經畫好的數據,究竟經歷了怎樣的旅程,最終抵達屏幕? 整條鏈路大致是:UI 獲
Android RSA 加解密實作:金鑰、分段與填充方式
RSA 加密的基本概念RSA 是一種非對稱加密演算法,使用公鑰與私鑰配對。公鑰可以公開,用於加密;私鑰由持有者保存,用於解密。RSA 的安全性建立在「大數分解很難」的數學