標籤:源碼 android 自動關機 shutdown uid-system
最近在做行車記錄儀的事情,由於車載裝置上的鋰電池容量比較小,所以在停車熄火,儲存資料後需要自動關機,由於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; 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() { while (true) { try { Thread.sleep(1000); Message message = new Message(); message.what = 1; shutdownHandler.sendMessage(message); if (!Screenshot.isPowerConnect) { Screenshot.OffSecond++; } else { Screenshot.OffSecond = 0; } } catch (InterruptedException e) { e.printStackTrace(); } } } } final Handler shutdownHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 1: if (Screenshot.OffSecond == 5 && !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,大功告成。
著作權聲明:本文原創,轉載請註明出處:http://blog.csdn.net/zhoumushui
Android 斷開電源5秒後自動關機