編輯:關於 Android 程式設計
本文把日常 Android 開發中反覆用到的幾組實用功能整理在一起,涵蓋定時與延時、資料加密、圓角按鈕、Android Studio 調試與 Logcat、雙擊退出、線程基礎,以及 APK 數字簽名,方便隨時查閱。
postDelayed(Runnable r, long delayMillis) 自 API level 1 就有了,作用是把 Runnable 加入訊息佇列,指定時間後再執行,執行在哪個線程取決於這個 Handler 綁定的線程。
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
// 你要做的事
System.out.println(Thread.currentThread().getName());
handler.postDelayed(runnable, 1000);
}
};
注意它的時間基準是 uptimeMillis(),也就是說裝置深度睡眠的時間不會計入,實際觸發會額外延後。啟動定時器只需呼叫一次 handler.post(runnable),取消則用 handler.removeCallbacks(runnable)。
從印出的線程名可以發現,它並沒有另開線程,而是跑在 UI 線程上。
實測會看到一個反直覺的現象:
原因在於:Activity 由前台轉到後台時線程仍在運行,但返回前台時會重新執行 onCreate,於是又 new 了一個新的 Runnable。此時 removeCallbacks 移除的物件,和當初加入佇列的根本不是同一個。
解法很簡單——把 Handler 與 Runnable 宣告為 static。靜態變數在記憶體中只有一份,類別載入時就完成配置,不會因 Activity 重建而產生新物件:
static Handler handler = new Handler();
static Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("update...");
handler.postDelayed(runnable, 1000);
}
};
第一步,定義定時器、定時任務與 Handler:
private final Timer timer = new Timer();
private TimerTask task;
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// 在這裡處理要做的事情
super.handleMessage(msg);
}
};
第二步,初始化定時任務,讓它在到點時向 Handler 發送訊息:
task = new TimerTask() {
@Override
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};
第三步,啟動定時器:
timer.schedule(task, 2000, 2000);
兩個關鍵方法:
schedule(task, delay):delay/1000 秒後執行一次。schedule(task, delay, period):delay 秒後首次執行,之後每隔 period 秒重複,適合循環任務;用 timer.cancel() 取消。
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
System.out.println("update...");
}
};
public class MyThread implements Runnable {
@Override
public void run() {
while (isLive) {
try {
Thread.sleep(1000); // 暫停 1 秒
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// 啟動
new Thread(new MyThread()).start();
// 停止:把 isLive 設為 false
思路與定時器異曲同工:
// 一、線程
new Thread(new Runnable() {
public void run() {
Thread.sleep(XXXX);
handler.sendMessage(); // 通知主線程執行任務
}
}).start();
// 二、延時器
TimerTask task = new TimerTask() {
public void run() { /* execute the task */ }
};
Timer timer = new Timer();
timer.schedule(task, delay);
// 三、Android 訊息處理
new Handler().postDelayed(new Runnable() {
public void run() { /* execute the task */ }
}, delay);
為了保障資料在傳輸與儲存環節的安全,可以透過特定算法把明文轉為密文。加密手段大致分為單向加密與雙向加密兩類。
幾個基本術語:明文是未加密資料,密文是加密後的資料;加密是明文轉密文的過程,解密則相反;加密演算法與解密演算法分別是兩個方向的轉換規則;加密密鑰與解密密鑰則是演算法操作時使用的鑰匙。
MD5(Message-Digest Algorithm 5)是最廣泛使用的雜湊演算法之一,前身為 MD2、MD3、MD4。它的作用是把任意長度的位元組串壓縮成固定長度的十六進位數字串,常用於確保資料傳輸的完整一致。除 MD5 外,SHA-1、RIPEMD、Haval 也相當有名。
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class EncrypMD5 {
public byte[] eccrypt(String info) throws NoSuchAlgorithmException {
// 依 MD5 演算法取得 MessageDigest 物件
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] srcBytes = info.getBytes();
md5.update(srcBytes);
return md5.digest();
}
public static void main(String[] args) throws NoSuchAlgorithmException {
String msg = "郭XX-精品相聲技術";
EncrypMD5 md5 = new EncrypMD5();
byte[] resultBytes = md5.eccrypt(msg);
System.out.println("密文是:" + new String(resultBytes));
System.out.println("明文是:" + msg);
}
}
SHA 是公認最安全的雜湊演算法之一。它的思想是接收一段明文,以不可逆的方式轉成一串長度固定的輸出(即散列值、訊息摘要),可視為明文的「指紋」;因此對散列值做數字簽名,等同於對這段明文簽名。
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class EncrypSHA {
public byte[] eccrypt(String info) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(info.getBytes());
return md.digest();
}
public static void main(String[] args) throws NoSuchAlgorithmException {
String msg = "郭XX-精品相聲技術";
EncrypSHA sha = new EncrypSHA();
System.out.println("明文是:" + msg);
System.out.println("密文是:" + new String(sha.eccrypt(msg)));
}
}
對稱加密又稱單鑰匙加密,加密與解密使用同一把密鑰,就像雙方事先約定好一組暗號。由於速度快,它特別適合大量資料加密的場景。缺點也很直接:演算法本身不提供安全性,鑰匙的管理與交換才是關鍵。
實作上通常在類中宣告四個成員:KeyGenerator(產生對稱密鑰)、SecretKey(保存密鑰)、Cipher(執行加解密)與一個用來暫存結果的位元組陣列。
// KeyGenerator 提供對稱密鑰生成器的功能,支援各種演算法 private KeyGenerator keygen; // SecretKey 負責保存對稱密鑰 private SecretKey deskey; // Cipher 負責完成加密或解密工作 private Cipher c; // 該位元組陣列負責保存加密的結果 private byte[] cipherByte;
在構造函式中完成初始化:
Security.addProvider(new com.sun.crypto.provider.SunJCE());
// 例項化支援 DES 的密鑰生成器(名稱需符合規定,否則拋異常)
keygen = KeyGenerator.getInstance("DES");
deskey = keygen.generateKey();
c = Cipher.getInstance("DES");
DES 是美國的數據加密標準,明文按 64 位分組、密鑰長 64 位(實際只有 56 位參與運算,其餘 8 位是奇偶檢查位)。完整實作如下:
import java.security.*;
import javax.crypto.*;
public class EncrypDES {
private KeyGenerator keygen;
private SecretKey deskey;
private Cipher c;
private byte[] cipherByte;
public EncrypDES() throws NoSuchAlgorithmException, NoSuchPaddingException {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
keygen = KeyGenerator.getInstance("DES");
deskey = keygen.generateKey();
c = Cipher.getInstance("DES");
}
/** 加密 */
public byte[] Encrytor(String str) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
c.init(Cipher.ENCRYPT_MODE, deskey);
return c.doFinal(str.getBytes());
}
/** 解密 */
public byte[] Decryptor(byte[] buff) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
c.init(Cipher.DECRYPT_MODE, deskey);
return c.doFinal(buff);
}
public static void main(String[] args) throws Exception {
EncrypDES de1 = new EncrypDES();
String msg = "郭XX-搞笑相聲全集";
byte[] encontent = de1.Encrytor(msg);
byte[] decontent = de1.Decryptor(encontent);
System.out.println("明文是:" + msg);
System.out.println("加密後:" + new String(encontent));
System.out.println("解密後:" + new String(decontent));
}
}
3DES(Triple DES)是 DES 向 AES 過渡的方案,1999 年被 NIST 指定為過渡加密標準。它以 DES 為基本模組,用三條 56 位密鑰做三次運算:
C = Ek3(Dk2(Ek1(P)))P = Dk1(Ek2(Dk3(C)))程式碼與 DES 幾乎一致,只要把演算法名稱換成 DESede:
public class EncrypDES3 {
private KeyGenerator keygen;
private SecretKey deskey;
private Cipher c;
private byte[] cipherByte;
public EncrypDES3() throws NoSuchAlgorithmException, NoSuchPaddingException {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
keygen = KeyGenerator.getInstance("DESede");
deskey = keygen.generateKey();
c = Cipher.getInstance("DESede");
}
public byte[] Encrytor(String str) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
c.init(Cipher.ENCRYPT_MODE, deskey);
return c.doFinal(str.getBytes());
}
public byte[] Decryptor(byte[] buff) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
c.init(Cipher.DECRYPT_MODE, deskey);
return c.doFinal(buff);
}
}
AES(Advanced Encryption Standard,高級加密標準)由比利時密碼學家 Joan Daemen 與 Vincent Rijmen 設計,演算法原名 Rijndael。它用來取代 DES,由美國 NIST 於 2001 年 11 月 26 日以 FIPS PUB 197 發布,2002 年 5 月 26 日正式生效,如今已成為對稱密鑰加密中最主流的演算法之一。
public class EncrypAES {
private KeyGenerator keygen;
private SecretKey deskey;
private Cipher c;
private byte[] cipherByte;
public EncrypAES() throws NoSuchAlgorithmException, NoSuchPaddingException {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
keygen = KeyGenerator.getInstance("AES");
deskey = keygen.generateKey();
c = Cipher.getInstance("AES");
}
public byte[] Encrytor(String str) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
c.init(Cipher.ENCRYPT_MODE, deskey);
return c.doFinal(str.getBytes());
}
public byte[] Decryptor(byte[] buff) throws InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
c.init(Cipher.DECRYPT_MODE, deskey);
return c.doFinal(buff);
}
}
1976 年,美國學者 Diffie 與 Hellman 為了解決訊息公開傳輸與密鑰管理的難題,提出了「公開密鑰系統」的概念,也稱非對稱加密演算法。它需要一對密鑰:公鑰與私鑰。用公鑰加密的資料只有對應私鑰能解,反之亦然。
RSA 由 Ron Rivest、Adi Shamir、Len Adleman 於 1977 年在 MIT 提出,名字取自三人姓氏。它的安全性建立在很清楚但也很有趣的數論事實上:兩個大質數相乘非常容易,但要把乘積因式分解回去卻極其困難——所以乘積可以公開作為加密密鑰。
import java.security.*;
import java.security.interfaces.*;
import javax.crypto.*;
public class EncrypRSA {
/** 以公鑰加密 */
protected byte[] encrypt(RSAPublicKey publicKey, byte[] srcBytes)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
if (publicKey != null) {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(srcBytes);
}
return null;
}
/** 以私鑰解密 */
protected byte[] decrypt(RSAPrivateKey privateKey, byte[] srcBytes)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
if (privateKey != null) {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(srcBytes);
}
return null;
}
public static void main(String[] args) throws Exception {
EncrypRSA rsa = new EncrypRSA();
String msg = "郭XX-精品相聲";
// KeyPairGenerator 用於產生公私立鑰對
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
byte[] resultBytes = rsa.encrypt(publicKey, msg.getBytes());
byte[] decBytes = rsa.decrypt(privateKey, resultBytes);
System.out.println("明文是:" + msg);
System.out.println("加密後是:" + new String(resultBytes));
System.out.println("解密後是:" + new String(decBytes));
}
}
DSA(Digital Signature Algorithm)是 Schnorr 與 ElGamal 簽名演算法的變種,被美國 NIST 收錄為數位簽章標準 DSS,主要用於簽名場景而非資料加密。
圓角按鈕能讓扁平化 UI 更有質感,實作並不難。在 res/drawable 下建立 shape.xml:
shapeone.xml(圓角)
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- 填充顏色 -->
<solid android:color="#FFFFFF" />
<!-- 四個角設為弧形,radius 為弧形半徑 -->
<corners android:radius="5dip" />
<!-- padding:按鈕內文字與邊界的間距 -->
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
</shape>
接著在佈局檔中用 android:background="@drawable/shape" 引用即可:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/roundButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/shape"
android:text=" 圓角按鈕 " />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, RoundButtonDemoActivity!</string>
<string name="app_name">RoundButtonDemo</string>
</resources>
現在 Android 開發工具基本已全面轉向 Android Studio,設定調試設備的方式也隨之改變。點擊工具列 App 右側的下拉箭頭,選擇「Edit Configurations...」。
Deployment Target 的四個選項:
程式運行後,點擊 Android Studio 底部的 Android 按鈕即可開啟調試視窗。
在 Device 欄位可以看到目前可調試的設備。有時 USB 接上了卻沒顯示,就可以在這裡確認。要查看 Logcat 時,點擊視窗右上角的 Android 圖示切換分頁。
Android 的日誌工具類是 android.util.Log,提供五個層級的方法:
Log.v():最瑣碎、意義最小的資訊,層級 verbose,最低。Log.d():調試資訊,層級 debug。Log.i():比較重要的資料,例如能幫助分析使用者行為的內容,層級 info。Log.w():警告資訊,提示潛在風險,層級 warn。Log.e():錯誤資訊,通常進入 catch 時使用,層級 error,最高。用法上傳入兩個參數即可:第一個是 tag(一般傳類名,用於過濾),第二個是 msg(要印出的內容)。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hello_world_layout);
Log.d("HelloWorldActivity", "onCreate execute");
}
透過時間差判斷即可:
private long mPressedTime = 0;
@Override
public void onBackPressed() {
long mNowTime = System.currentTimeMillis(); // 取得本次按鍵時間
if ((mNowTime - mPressedTime) > 2000) {
// 兩次按鍵間隔超過 2 秒,重新計時並提示
Toast.makeText(this, "再按一次退出程式", Toast.LENGTH_SHORT).show();
mPressedTime = mNowTime;
} else {
// 間隔在 2 秒內,退出程式
this.finish();
System.exit(0);
}
}
有人會說看線程名字,但那並不可靠——萬一系統哪天改了命名規則呢。更穩妥的做法是拿目前線程的 Looper 與主線程的 Looper 做比對:
start() 後進入就緒佇列,已具備運行條件但還沒拿到 CPU,隨時等待系統調度。此時線程是活著的。run()。若時間片用完仍未結束,會被換回就緒狀態。join()、sleep()、wait() 或資源被佔用時進入,線程仍然活著。run() 執行完畢、被中斷或因異常退出即進入死亡狀態,呼叫堆疊已解除,線程不再活著。
Thread.sleep(millis):當前線程睡眠指定毫秒數(這是最小不執行時間,睡醒後不保證立刻被調度)。它是 static 方法,不會讓其他線程也進入休眠;休眠期間不會釋放已持有的物件鎖。作用是把 CPU 讓出來,避免單一线程獨佔資源。Thread.yield():讓出 CPU 使用權給同等優先權的線程,但不保證自己會被重新調度;若沒有同等優先權的線程,這個方法等於沒作用。thread.join():呼叫它的線程會等目標線程執行完畢後才繼續往下走。object.wait():進入與該物件相關的等待池並暫時釋放物件鎖。呼叫前必須持有該物件的鎖,否則拋 IllegalMonitorStateException,因此只能在 synchronized 區塊中呼叫。notify() / notifyAll():喚醒等待池中的第一個/全部線程,同樣必須持有相同物件鎖。需要特別記住的是:Java 線程不可重啟。run() 執行到最後一行後該線程即結束,無法再用 start() 復活,只能重新建立一個 Thread 物件(對已 Dead 的線程呼叫 start() 會拋 runtime exception)。
線程建立後不會立刻執行,而是處於等待狀態,此時可以設定優先級(setPriority)、名稱(setName)、是否為守護線程(setDaemon)等屬性。呼叫 start() 後才進入運行狀態,可用 isAlive() 判斷是否仍在運行。
public class LifeCycle extends Thread {
public void run() {
int n = 0;
while ((++n) < 1000);
}
public static void main(String[] args) throws Exception {
LifeCycle thread1 = new LifeCycle();
System.out.println("isAlive: " + thread1.isAlive());
thread1.start();
System.out.println("isAlive: " + thread1.isAlive());
thread1.join(); // 等 thread1 結束後再繼續
System.out.println("thread1 已經結束!");
System.out.println("isAlive: " + thread1.isAlive());
}
}
輸出結果:
isAlive: false isAlive: true thread1 已經結束! isAlive: false
sleep 與 yield 的差異,實測很明顯。下面這個例子讓 t1 使用最高優先級、t2 使用最低優先級:
class TestThreadMethod extends Thread {
public static int shareVar = 0;
public TestThreadMethod(String name) {
super(name);
}
public void run() {
for (int i = 0; i < 4; i++) {
System.out.print(Thread.currentThread().getName());
System.out.println(" : " + i);
Thread.yield(); // (1)
try {
Thread.sleep(3000); // (2)
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
}
}
}
public class TestThread {
public static void main(String[] args) {
TestThreadMethod t1 = new TestThreadMethod("t1");
TestThreadMethod t2 = new TestThreadMethod("t2");
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
}
}
保留 sleep 時,低優先級的 t2 也能取得執行機會,輸出交錯出現。若註解掉 sleep、只留 yield,輸出則會變成 t1 連續跑完四次、t2 才開始——可見 yield() 只讓同等優先級的線程有機會,不同優先級之間永遠輪不到。
使用 sleep 時有四點要注意:
InterruptedException。當 run 方法中包含 while(true) 這類永不結束的迴圈(例如服務端的請求監聽),最直接的方式是設一個 boolean 標誌:
public class ThreadFlag extends Thread {
public volatile boolean exit = false;
public void run() {
while (!exit);
}
public static void main(String[] args) throws Exception {
ThreadFlag thread = new ThreadFlag();
thread.start();
sleep(5000); // 主線程延遲 5 秒
thread.exit = true; // 通知 thread 結束
thread.join();
System.out.println("線程退出!");
}
}
這裡的 volatile 關鍵字不可省略,它保證 exit 值的修改能立即對其他線程可見,避免因為 JVM 的快取優化導致迴圈永遠讀到舊值。
數字簽名就是替程式打上一個屬於你自己的標記。最直接的答案是:Android 系統強制要求,任何 APK 未經簽名都無法安裝,不論在模擬器還是真機上。
Android 透過簽名來標識應用作者並在應用之間建立信任關係,而非決定使用者能安裝哪些程式。這個簽名由開發者自行完成,不需要權威憑證機構認證,屬於自我認證性質。
簽名的三個實際價值:
Keytool 與 Jarsigner 產生憑證並簽名。zipalign 對程式做優化。這就解釋了一個常見疑問:日常開發中我們從沒手動簽名,程式卻能在模擬器與真機上運行。
debug.keystore 的檔案,位於使用者目錄下的 .android 資料夾。debug 簽名有兩個風險:一是 debug 簽名的應用無法上架 Google Play;二是不同機器產生的 debug.keystore 可能不同,換機器後做版本升級就會出現無法覆蓋安裝的問題。如果只是自己用,卸載重裝即可;但若已有大量使用者,這就等於程式不具備升級能力。所以正式專案一定要有自己的憑證。
步驟一:進入簽名打包介面
選擇選單「Build」→「Generate Signed APK...」。
步驟二:新建 Key 檔
若還沒有可用的 Key,點擊「Create new...」。
依提示填入別名、密碼、有效期、憑證資訊等內容,建立自己的 Key(例如 MyKey.jks)。
步驟三:匯入 Key 並打包
建立完成後會自動回到匯入介面,並預設載入剛剛建立的 Key。
按「Next」後確認 APK 輸出路徑與 Build Type。
看到「Signed APKs generated successfully.」提示即代表打包成功。
到輸出路徑找到 APK,這就是可以直接安裝的正式安裝包。
Android 取得應用程式資訊:查詢快取大小與套件統計
為何需要查詢應用程式快取 許多應用需要在設定頁或清理頁面顯示快取大小,讓使用者知道目前佔用空間並決定是否清理。Android 本身有相關 API,但直接呼叫方式較繁瑣,因
Android 繪圖入門:Canvas、Paint 與 Path 三兄弟
Android 的自繪圖功能建立在 View 元件之上,只要覆寫 onDraw(Canvas canvas) 就能作畫。核心只有三個類別: Canvas:依附於某個 V
MPAndroidChart 系列:玩轉 PieChart 餅圖
簡介MPAndroidChart 是 PhilJay 給 Android 開發者帶來的一份大禮。它功能強大、API 設計靈活,同時支持 Android 與 iOS,本文只
Android 實作:將系統進程與使用者進程分開顯示
在前一篇《殺死使用者選取的進程並優化》中,我介紹了如何改善使用者體驗;本篇則接續說明如何把系統進程與使用者進程分離顯示。本文同樣以前一篇的基礎加以改進,建議先閱讀前一篇。