編輯:關於 Android 程式設計
因公司專案需求,我研究了 Android 的自動關機與重啟。網路上方法百百種,本文把可行的方案統整在一起,並說明各自的權限前提與限制。
Broadcast 是 Android 四大元件之一。系統本身就內建了許多廣播,其中包含關機與重啟相關的 Intent.ACTION_REQUEST_SHUTDOWN 與 Intent.ACTION_REBOOT,發送這兩個廣播即可觸發對應操作。
public static final String ACTION_REBOOT = "android.intent.action.REBOOT";
public static final String ACTION_REQUEST_SHUTDOWN = "android.intent.action.ACTION_REQUEST_SHUTDOWN";
// 廣播方式關機/重啟
case R.id.shutdown_btn1:
Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false); // 改為 true 會彈出關機確認視窗
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
break;
case R.id.reboot_btn1:
Intent intent2 = new Intent(Intent.ACTION_REBOOT);
intent2.putExtra("nowait", 1);
intent2.putExtra("interval", 1);
intent2.putExtra("window", 0);
sendBroadcast(intent2);
break;
這方式有幾點要留意:第一,需將 App 提升為系統權限,在 AndroidManifest.xml 加上 android:sharedUserId="android.uid.system";第二,要加上關機權限;第三,Intent.ACTION_REQUEST_SHUTDOWN 與 Intent.EXTRA_KEY_CONFIRM 對上層不開放,在 IDE 中會報錯,但放到源碼中一起編譯就能通過;第四,需在專案根目錄加入 Android.mk:
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE_TAGS := optional LOCAL_SRC_FILES := $(call all-java-files-under, src) LOCAL_PACKAGE_NAME := PowerActionDemo LOCAL_CERTIFICATE := platform include $(BUILD_PACKAGE)
最後把編譯出的 apk 用 adb push 到機器上即可驗證。
Android 啟動後第一個執行的程式是 /init,它會解析 init.rc 並執行解析出的任務。利用這一點,可以寫簡單的關機/重啟 sh 腳本,交由系統 init 解析執行。
首先編寫重啟腳本 system_reboot.sh(內容為 reboot)與關機腳本 system_shutdown.sh(內容為 reboot -p)。注意:這裡的關機命令並不是 shutdown,而是 reboot -p。
接著寫 Android.mk,目的是編譯時把這兩個 sh 檔一起打包到 /system/bin:
LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_PREBUILT_EXECUTABLES := system_shutdown.sh system_reboot.sh LOCAL_MODULE_TAGS := optional include $(BUILD_MULTI_PREBUILT)
然後在 init.rc 最後加入服務定義:
service system_shutdown /system/bin/system_shutdown.sh
oneshot
disabled
service system_reboot /system/bin/system_reboot.sh
oneshot
disabled
oneshot 表示服務只啟動一次;disabled 表示開機時不自動啟動,但可在應用中手動觸發。把這些檔案放進同一目錄並複製到源碼(如 device 路徑下),編譯後檢查 out/.../system/bin 是否包含這兩個 sh 檔即可確認成功。最後用 SystemProperties.set("ctl.start", "system_shutdown") 啟動服務來關機或重啟。
Java 的 Runtime 類可用來執行 shell 命令,而 Android 虛擬機支援 Linux shell,因此可以透過 Runtime 執行關機或重啟命令,原理與方式二相近:
case R.id.shutdown_btn3:
try {
Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot -p"}); // 關機
proc.waitFor();
} catch (Exception e) { e.printStackTrace(); }
break;
case R.id.reboot_btn3:
try {
Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot"}); // 重啟
proc.waitFor();
} catch (Exception ex) { ex.printStackTrace(); }
break;
這方式的前提是裝置必須已 root——加上 su 就是為了取得管理員權限。另外要注意,system/bin 下必須存在對應的 reboot 或 shutdown 檔;有些系統偏偏沒有 shutdown 檔,這時就得改用 reboot -p 來關機。
PowerManager 提供了 reboot 介面,實作重啟很簡單:
PowerManager pManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
pManager.reboot("");
但 PowerManager 並未提供關機的 shutdown 介面。它透過 IBinder 與 PowerManagerService 通訊,而 IPowerManager 這個 AIDL 產生的類別實作了 shutdown。若能取得 Power 服務的 IBinder,就能用反射呼叫 shutdown 達成關機。ServiceManager 保存著所有服務的 IBinder,但它是 hide 的,也需要反射呼叫。因此藉由兩次反射即可完成:
try {
// 取得 ServiceManager 類別
Class> ServiceManager = Class.forName("android.os.ServiceManager");
Method getService = ServiceManager.getMethod("getService", java.lang.String.class);
// 取得 RemoteService
Object oRemoteService = getService.invoke(null, Context.POWER_SERVICE);
// 取得 IPowerManager.Stub 類別
Class> cStub = Class.forName("android.os.IPowerManager$Stub");
Method asInterface = cStub.getMethod("asInterface", android.os.IBinder.class);
Object oIPowerManager = asInterface.invoke(null, oRemoteService);
// 取得並呼叫 shutdown()
Method shutdown = oIPowerManager.getClass().getMethod("shutdown", boolean.class, boolean.class);
shutdown.invoke(oIPowerManager, false, true);
} catch (Exception e) {
Log.e(TAG, e.toString(), e);
}
利用 AlarmManager 搭配隱藏的 REQUEST_POWER_OFF action,就能設定計時關機:
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent("com.android.settings.action.REQUEST_POWER_OFF");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
它最終會走到 ShutdownActivity,送出 Intent.ACTION_REQUEST_SHUTDOWN 這個隱藏 action。
系統處理關機的核心在 frameworks/base/core/jni/android_os_Power.cpp 的 android_os_Power_shutdown 方法,其內部呼叫 reboot(RB_POWER_OFF)。只要給它傳入合適參數即可。可以自己寫一個 shutdown 命令:
#include#include #include #include #ifndef LOG_TAG #define LOG_TAG "dxyh" #endif int main(int argc, char** argv) { int retval; if ((retval = __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, RB_POWER_OFF, NULL)) < 0) { LOGE("Try to shutdown the machine failed!"); exit(EXIT_FAILURE); } return 0; }
搭配對應的 Android.mk 編譯後,把產生的 shutdown 可執行檔推到 /system/bin,就能像其他命令一樣用 adb shell shutdown 執行。
若裝置已 root,執行時會提示是否授予 root 權限,選擇允許即可關機:
private void shutdown() {
try {
Process process = Runtime.getRuntime().exec("su");
DataOutputStream out = new DataOutputStream(process.getOutputStream());
out.writeBytes("reboot -p\n");
out.writeBytes("exit\n");
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
總結來說,關機與重啟在 Android 上有諸多路徑:從發送廣播、啟動 Activity,到呼叫系統服務、編寫 native 命令。途徑雖多,但大多需要系統權限或 root。實作時可依裝置是否開放源碼編譯、是否已 root 等條件,挑選最合適的方案。
自定義 ViewGroup 實戰:手把手寫一個流式布局 FlowLayout
本文參考並總結了鴻神的 FlowLayout 文章,在此基礎上做了修正,也補充了一些自己的理解,文末附上原文地址。 什麼是流式布局 流式布局(FlowLayout)指的是
仿微信首頁左右滑動:自訂 TabIconView 實作漸變切換
微信首頁那個切換效果確實好看:左右滑動跟手、點一下底部 bar 瞬間切換、圖示與文字顏色還會隨滑動漸變。線上效果如下: 網路上已經有前人做過類似實作,我在其基礎上又調整
用 LayoutParams 在代碼中動態控制控件位置與尺寸
XML 布局能解決的問題不要用代碼去做,但有些場景——比如尺寸和位置來自服務端下發的配置——就必須在運行時動態設置。這時候 LayoutParams 是唯一的工具。 L
EditText 好搭檔:TextInputLayout 浮動標籤控制項用法
一、這是什麼 TextInputLayout 是 Design Support Library 提供的一個輔助控制項,作用是讓 EditText 的提示文字在獲得焦點、開