1. 程式人生 > >Android 斷開電源10秒後自動關機

Android 斷開電源10秒後自動關機

最近在做行車記錄儀的事情,由於車載裝置上的鋰電池容量比較小,所以在停車熄火,儲存資料後需要自動關機,由於Shutdown的許可權不對普通應用開放,所以需要在原始碼下編譯程式碼。可以自己寫個BroadcastReceiver放到Setting原始碼裡,也可以是獨立應用。

manifest節點需要宣告系統級uid:

android:sharedUserId="android.uid.system"

以及關機許可權:

<uses-permission android:name="android.permission.SHUTDOWN"/>

以上這兩點在Setting的AndroidManifest裡都有,所以就不用我們手動添加了。
然後我在Application裡聲明瞭兩個全域性變數,用來儲存當前的電源狀態和已經斷開電源的秒數:


    /**
     * 電源是否連線
     */
    public static boolean isPowerConnect = true;

    /**
     * 電源斷開的秒數
     */
    public static int OffSecond = 0;

接著就是PowerStateChangeReceiver:

package com.android.settings;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import
android.os.Handler; import android.os.Message; import android.widget.Toast; public class PowerStateChangeReceiver extends BroadcastReceiver { private Context context; @Override public void onReceive(Context context, Intent intent) { this.context = context; Screenshot.OffSecond = 0
; if ("android.intent.action.ACTION_POWER_CONNECTED".equals(intent .getAction())) { Screenshot.isPowerConnect = true; //Toast.makeText(context, "CONNECTED", Toast.LENGTH_SHORT).show(); } else if ("android.intent.action.ACTION_POWER_DISCONNECTED" .equals(intent.getAction())) { Screenshot.isPowerConnect = false; //Toast.makeText(context, "DISCONNECTED", Toast.LENGTH_SHORT).show(); new Thread(new shutdownThread()).start(); } } /** * Shutdown * * @param context */ public void shutdown(Context context) { try { Intent intent = new Intent( "android.intent.action.ACTION_REQUEST_SHUTDOWN"); intent.putExtra("android.intent.extra.KEY_CONFIRM", false); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } catch (Exception e) { } Toast.makeText(context, context.getResources().getString(R.string.shutdown_now), Toast.LENGTH_SHORT).show(); } public class shutdownThread implements Runnable { @Override public void run() { synchronized (shutdownHandler) { while (!Screenshot.isPowerConnect) { try { Thread.sleep(1000); Message message = new Message(); message.what = 1; shutdownHandler.sendMessage(message); } catch (InterruptedException e) { e.printStackTrace(); } } } } } final Handler shutdownHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 1: if (!Screenshot.isPowerConnect) { Screenshot.OffSecond++; } else { Screenshot.OffSecond = 0; } if (Screenshot.OffSecond == 10 && !Screenshot.isPowerConnect) { shutdown(context); } break; default: break; } } }; }

另外是在setting的AndroidManifest.xml對reveiver的宣告:

<receiver android:name=".PowerStateChangeReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
            </intent-filter>
        </receiver>

okay,大功告成。