編輯:關於 Android 程式設計
靜默安裝聽起來很誘人,但一般做法很難實現:Android 並沒有開放對外的 Intent 直接完成安裝,最常見的寫法其實會跳出安裝介面。
Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); startActivity(intent);
使用者看得到、按得下去,這顯然不叫「靜默」。要真正做到背景安裝,只能回頭研究系統自己是怎麼裝 APK 的。
Android 依風險把權限分為 normal、dangerous、signature、signatureOrSystem 四級。安裝 APK 對應的 INSTALL_PACKAGES 屬於後兩者,一般應用根本拿不到。也就是說,要實現靜默安裝,執行安裝的那個行程必須是系統行程——這是整個方案的前提。
安裝指令是 pm install,對應到源碼的 frameworks/base/cmds/pm/src/com/android/commands/pm/Pm.java,其中 runInstall() 就是安裝流程:
private void runInstall() {
int installFlags = 0;
int userId = UserHandle.USER_ALL;
String installerPackageName = null;
String opt;
String originatingUriString = null;
String referrer = null;
String abi = null;
while ((opt = nextOption()) != null) {
if (opt.equals("-l")) {
installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
} else if (opt.equals("-r")) {
installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
} else if (opt.equals("-i")) {
installerPackageName = nextOptionData();
} else if (opt.equals("-t")) {
installFlags |= PackageManager.INSTALL_ALLOW_TEST;
} else if (opt.equals("-s")) {
installFlags |= PackageManager.INSTALL_EXTERNAL;
} else if (opt.equals("-f")) {
installFlags |= PackageManager.INSTALL_INTERNAL;
} else if (opt.equals("-d")) {
installFlags |= PackageManager.INSTALL_ALLOW_DOWNGRADE;
} else if (opt.equals("--user")) {
userId = Integer.parseInt(nextOptionData());
}
// 其餘參數略
}
final String apkFilePath = nextArg();
LocalPackageInstallObserver obs = new LocalPackageInstallObserver();
try {
VerificationParams verificationParams = new VerificationParams(
verificationURI, originatingURI, referrerURI, VerificationParams.NO_UID, null);
// 真正執行安裝的就是這一行
mPm.installPackageAsUser(apkFilePath, obs.getBinder(), installFlags,
installerPackageName, verificationParams, abi, userId);
synchronized (obs) {
while (!obs.finished) {
try { obs.wait(); } catch (InterruptedException e) { }
}
if (obs.result == PackageManager.INSTALL_SUCCEEDED) {
System.out.println("Success");
} else {
System.err.println("Failure [" + installFailureToString(obs) + "]");
}
}
} catch (RemoteException e) {
System.err.println(e.toString());
}
}
既然底層把 API 藏起來了,那就想辦法繞過去用。做法是把 IPackageManager 相關的 AIDL 檔從源碼目錄 frameworks/base/core/java/android/content/pm 複製進專案,包名不能改,缺的那些相依 AIDL 也要一起補齊。Android 5.0 的 AIDL 變動幅度不小,需要複製的檔案相當多,還得逐一修正編譯錯誤。

android.os.ServiceManager 及其方法。getService("package") 拿到 IBinder,再轉成介面。
package com.example.autoinstall;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.IPackageInstallObserver2;
import android.content.pm.IPackageManager;
import android.content.pm.VerificationParams;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void install(View view) {
String path = FileUtils.isSdcardReady()
? FileUtils.getSdcardPath()
: FileUtils.getCachePath(this);
String fileName = path + "/AidlServerDemo.apk";
File file = new File(fileName);
try {
if (!file.exists()) copyAPK2SD(fileName);
// 以反射取得隱藏的 ServiceManager
Class<?> clazz = Class.forName("android.os.ServiceManager");
Method method = clazz.getMethod("getService", String.class);
IBinder iBinder = (IBinder) method.invoke(null, "package");
IPackageManager ipm = IPackageManager.Stub.asInterface(iBinder);
VerificationParams verificationParams =
new VerificationParams(null, null, null, VerificationParams.NO_UID, null);
// 執行安裝(方法簽章隨系統版本而異)
ipm.installPackage(fileName, new PackageInstallObserver(),
2, null, verificationParams, "");
} catch (Exception e) {
e.printStackTrace();
}
}
// 安裝結果回呼
class PackageInstallObserver extends IPackageInstallObserver2.Stub {
@Override
public void onUserActionRequired(Intent intent) throws RemoteException { }
@Override
public void onPackageInstalled(String basePackageName, int returnCode,
String msg, Bundle extras) throws RemoteException {
// returnCode 為 1 代表安裝成功
}
}
// 把 assets 中的 APK 複製到外部儲存
private void copyAPK2SD(String strOutFileName) throws IOException {
FileUtils.createDipPath(strOutFileName);
InputStream myInput = this.getAssets().open("AidlServerDemo.apk");
OutputStream myOutput = new FileOutputStream(strOutFileName);
byte[] buffer = new byte[1024];
int length = myInput.read(buffer);
while (length > 0) {
myOutput.write(buffer, 0, length);
length = myInput.read(buffer);
}
myOutput.flush();
myInput.close();
myOutput.close();
}
}
不同系統版本的 AIDL 內容有差異,實際要複製的檔案與呼叫的方法都必須對照該版本的 Pm.java 逐一確認。部分版本只需要複製 PackageManager.java 與 IPackageDeleteObserver.aidl、IPackagerInstallObserver.aidl、IPackageMoveObserver.aidl 這幾個檔案。
接著在清單中加入權限:
<uses-permission android:name="android.permission.INSTALL_PACKAGES"/>
再把應用自身的 UID 提昇到系統層級:
android:sharedUserId="android.uid.system"
但只做到這裡仍然不算系統應用,所以還必須對「執行安裝的這支 APK」做系統簽名(注意不是被安裝的那支)。需要三個檔案:
%源碼%/out/host/linux-x86/framework/signapk.jar%源碼%/build/target/product/security/platform.x509.pem%源碼%/build/target/product/security/platform.pk8開啟終端機執行:
java -jar SignApk.jar platform.x509.pem platform.pk8 未簽名APK 簽名後APK
例如:
java -jar SignApk.jar platform.x509.pem platform.pk8 AutoInstall.apk AutoInstall_new.apk
把簽好名的 APK 裝進機器、執行靜默安裝,回到程式列表就會看到目標應用已經出現在那裡。


本文提供的是一條可行的思路。要注意這套做法高度依賴平台簽名,只適用於自己有系統源碼、能自行簽章的定制機或企業內部裝置;一般商店上架的應用沒有 platform 簽名,是完全無法靜默安裝的。至於如何相容各版本、如何举一反三,就得依各自專案的目標機型逐一驗證了。
Android 细节:手把手实作弹出式菜单动画(一)
先上效果图,直观感受一下我们要做的东西: 先写 Layout 文件: 这三个 ImageView 都贴在屏幕底部,其中 clone_item 需要固定在球
wpa_supplicant 啟動剖析(一):網路介面是怎麼完成初始化的
wpa_supplicant 結構體與網路介面 在手機 adb 環境下執行 netcfg 或 ifconfig,可以看到各網路介面的 IP、掩碼、MAC 位址等資訊。
Fedora 14 下 Eclipse 開發 Android 時 ibus 無法彈出輸入法視窗的解決方案
好不容易把開發環境架設完成,卻遇到一個惱人的問題:無論怎麼按 Ctrl + Space,ibus 輸入法就是不出來,用滑鼠點擊還會跳出「沒有輸入窗口」的提示。上網搜尋一圈
Android 事件處理機制詳解:回呼、監聽器與完整實例
一、Android 事件 現代的用戶介面,都是以事件來驅動,藉此實現人機互動。而 Android 上的一整套 UI 控件,無非就是派發滑鼠與鍵盤事件,然後每個控件收到相應