編輯:關於 Android 開發
很多人問過同一個問題:Android 上到底能不能做到「靜默安裝」?所謂靜默安裝,就是不彈出系統安裝介面,在使用者毫無感知的情況下把程式裝好。
聽起來很美好,但這件事本身就帶著矛盾。Android 的安裝介面之所以存在,是因為系統要把這個 App 申請了哪些權限攤在陽光下,讓使用者自己判斷要不要裝。一旦靜默安裝,這個把關環節就消失了,等於使用者被動接受了全部權限。在官方眼裡,這是相當危險的行為,所以這項能力並不對一般開發者開放。
有趣的是,Google 自己很清楚「一直彈對話框」是很差的體驗,於是替自家商店開了後門:從 Google Play 下載的應用無需確認。小米也在 MIUI 裡做了類似定制,讓小米商店的安裝流程無縫銜接。
結論是:如果你只是做一個普通 App,其實不需要煩惱靜默安裝——上架到商店之後,這能力自然就有了。
但如果你想做的是一個類似 360 手機助手那樣的「安裝平台」,它作為一個普通應用存在於五花八門的機型上,沒有 Google 或小米那種系統級特權,該怎麼辦?360 的做法是提供兩條路:秒裝(需要 ROOT)與智能安裝(藉助無障礙服務模擬點擊)。下面先把秒裝做出來。
原理其實一句話就講完了:呼叫系統的 pm install 指令。難點在於 pm 這個命令一般應用沒有權限執行,只能靠 ROOT 提權。
新建一個 SilentInstall 類別承載這段邏輯:
public class SilentInstall {
/**
* 執行靜默安裝,需要手機 ROOT。
* @param apkPath 要安裝的 apk 檔案路徑
* @return 成功回傳 true,失敗回傳 false
*/
public boolean install(String apkPath) {
boolean result = false;
DataOutputStream dataOutputStream = null;
BufferedReader errorStream = null;
try {
// 先申請 su 權限
Process process = Runtime.getRuntime().exec("su");
dataOutputStream = new DataOutputStream(process.getOutputStream());
// 執行 pm install 指令
String command = "pm install -r " + apkPath + "\n";
dataOutputStream.write(command.getBytes(Charset.forName("utf-8")));
dataOutputStream.flush();
dataOutputStream.writeBytes("exit\n");
dataOutputStream.flush();
process.waitFor();
errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String msg = "";
String line;
// 讀取指令的執行結果
while ((line = errorStream.readLine()) != null) {
msg += line;
}
Log.d("TAG", "install msg is " + msg);
// 結果中出現 Failure 就算失敗,否則視為成功
if (!msg.contains("Failure")) {
result = true;
}
} catch (Exception e) {
Log.e("TAG", e.getMessage(), e);
} finally {
try {
if (dataOutputStream != null) dataOutputStream.close();
if (errorStream != null) errorStream.close();
} catch (IOException e) {
Log.e("TAG", e.getMessage(), e);
}
}
return result;
}
}
逐步拆解:
Runtime.getRuntime().exec("su") 取得 ROOT shell,這步失敗後面全都白搭。pm install -r <apk 路徑>,-r 表示若已安裝則覆蓋安裝。process.waitFor() 等它跑完——裝多久就等多久。Failure,有就是失敗,沒有就是成功。finally 區塊負責關流,別偷懶。主介面放四顆按鈕:選擇安裝包、秒裝、開啟智能安裝服務、智能安裝。這裡先只實作前兩顆。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onChooseApkFile"
android:text="選擇安裝包" />
<TextView
android:id="@+id/apkPathText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_vertical" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@android:color/darker_gray" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onSilentInstall"
android:text="秒裝" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@android:color/darker_gray" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onForwardToAccessibility"
android:text="開啟智能安裝服務" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onSmartInstall"
android:text="智能安裝" />
</LinearLayout>
因為 install() 需要 apk 路徑,所以得先做一個簡陋的檔案瀏覽器。activity_file_explorer.xml 只放一個 ListView,list_item.xml 放一個圖示加一個文字標籤:
<!-- list_item.xml -->
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="4dp"
android:orientation="horizontal">
<ImageView
android:id="@+id/img"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_margin="4dp"
android:layout_gravity="center_vertical" />
<TextView
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="18sp"
android:gravity="center_vertical" />
</LinearLayout>
FileExplorerActivity 的核心是三件事:列出當前目錄、點進子目錄、按返回鍵回上一層。
public class FileExplorerActivity extends AppCompatActivity
implements AdapterView.OnItemClickListener {
ListView listView;
SimpleAdapter adapter;
String rootPath = Environment.getExternalStorageDirectory().getPath();
String currentPath = rootPath;
List<Map<String, Object>> list = new ArrayList<>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_explorer);
listView = (ListView) findViewById(R.id.list_view);
adapter = new SimpleAdapter(this, list, R.layout.list_item,
new String[]{"name", "img"}, new int[]{R.id.name, R.id.img});
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
refreshListItems(currentPath);
}
private void refreshListItems(String path) {
setTitle(path);
File[] files = new File(path).listFiles();
list.clear();
if (files != null) {
for (File file : files) {
Map<String, Object> map = new HashMap<>();
map.put("img", file.isDirectory() ? R.drawable.directory : R.drawable.file_doc);
map.put("name", file.getName());
map.put("currentPath", file.getPath());
list.add(map);
}
}
adapter.notifyDataSetChanged();
}
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
currentPath = (String) list.get(position).get("currentPath");
File file = new File(currentPath);
if (file.isDirectory()) {
refreshListItems(currentPath);
} else {
Intent intent = new Intent();
intent.putExtra("apk_path", file.getPath());
setResult(RESULT_OK, intent);
finish();
}
}
@Override
public void onBackPressed() {
if (rootPath.equals(currentPath)) {
super.onBackPressed();
} else {
currentPath = new File(currentPath).getParentFile().getPath();
refreshListItems(currentPath);
}
}
}
這段和主題無關,純粹是為了讓 demo 能跑起來,就不多解釋了。
public class MainActivity extends AppCompatActivity {
TextView apkPathText;
String apkPath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apkPathText = (TextView) findViewById(R.id.apkPathText);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == RESULT_OK) {
apkPath = data.getStringExtra("apk_path");
apkPathText.setText(apkPath);
}
}
public void onChooseApkFile(View view) {
startActivityForResult(new Intent(this, FileExplorerActivity.class), 0);
}
public void onSilentInstall(View view) {
if (!isRoot()) {
Toast.makeText(this, "沒有 ROOT 權限,不能使用秒裝", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(apkPath)) {
Toast.makeText(this, "請選擇安裝包!", Toast.LENGTH_SHORT).show();
return;
}
final Button button = (Button) view;
button.setText("安裝中");
new Thread(new Runnable() {
@Override
public void run() {
SilentInstall installHelper = new SilentInstall();
final boolean result = installHelper.install(apkPath);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,
result ? "安裝成功!" : "安裝失敗!",
Toast.LENGTH_SHORT).show();
button.setText("秒裝");
}
});
}
}).start();
}
public void onForwardToAccessibility(View view) { }
public void onSmartInstall(View view) { }
/** 判斷手機是否具備 ROOT 權限 */
public boolean isRoot() {
boolean bool = false;
try {
bool = new File("/system/bin/su").exists()
|| new File("/system/xbin/su").exists();
} catch (Exception e) {
e.printStackTrace();
}
return bool;
}
}
流程很直白:先檢查有沒有 ROOT,再檢查有沒有選檔,然後開一條新執行緒去跑安裝。之所以要開執行緒,是因為安裝過程可能好幾秒甚至更久,塞在主執行緒會直接 ANR。無論結果如何,最後都切回主執行緒跳 Toast。
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".FileExplorerActivity" />
因為要讀 SD 卡選擇 apk,所以必須宣告讀取外部儲存空間的權限。
還有一點要注意:Android 6.0 開始,讀寫外部儲存被歸類為危險權限,若 targetSdkVersion 設為 23 以上,就得做執行期授權的適配。這裡為了簡化,把 target 設成 22,6.0 的適配不在本文範圍內。
跑起來之後可以看到,選定的安裝包直接裝進了手機,全程沒有彈出系統安裝介面——秒裝成功。
這套方案的前提是 ROOT,而 ROOT 機型的比例早已大幅下滑,Android 也在後續版本持續收緊 pm install 的呼叫條件。因此今天回頭看,秒裝更適合成為「有 ROOT 時的加分項」,而真正能規模化落地的仍是無障礙服務模擬點擊那一條路。另外,無論哪種方式,繞過使用者知情同意而擅自安裝第三方應用,都可能觸碰商店政策與法律紅線,實作前請先確認自己的使用情境是否正當。
我的 Android 進階之旅:解決 Android 5.0 的「Service Intent must be explicit」錯誤
我的 Android 進階之旅:解決 Android 5.0 的「Service Intent must be explicit」錯誤 一、錯誤描述 同樣一段程式,在 A
Android Studio 如何同時打開多個項目
Android Studio 如何同時打開多個項目Android Studio 的默認行為是:當你打開第二個項目時,第一個項目會被自動關閉。如果想同時開啟多個項目進行對照
釋放 Android 的函數式能量(一):Kotlin Lambda 表達式入門
背景:為何要在 Android 上談函數式 Java 8 已內建若干函數式工具,但 Android 開發者過去很長一段時間無法立即使用。既然官方語言支援落後,社群便轉而尋
RecyclerView 完全解析:從基本使用到分隔線、點擊與增刪動畫
RecyclerView 完全解析:從基本使用到分隔線、點擊與增刪動畫 RecyclerView 是 Android 中常用於建立複雜列表的元件。它保留了 ListVie