採用BroadcastReceiver實現安卓應用開機自動啓動使用KeyguardManager解除屏幕鎖定。前面已經完成一個安卓OA,經過一個WebView訪問一個適應手機大小的web oa,而且自動檢測有消息時提醒。當用戶關機後再開機可能會忘記訪問OA,這樣會漏掉重要的審批文件。這裏採用BroadcastReceiver爲安卓OA增長開機自動啓動。android
用BroadcastReceiver實現開機自啓動web
(一)新建BroadcastReceiver類:New – class – Superclass選擇爲「android.content.BroadcastReceiver」—name我用「BootBroadcastReceive」。完成後BootBroadcastReceive重載onReceive方法app
Intent intent = new Intent(arg0, MainActivity.class);佈局
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);this
arg0.startActivity(intent);xml
其中arg0是onReceive第一個參數Context.blog
(二)、在mainifest.xml定義BootBroadcastReceiverget
<receiver android:name="BootBroadcastReceiver"> it
<intent-filter> io
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
(三)、在manifest.xml配置文件中增長權限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
讓用戶選擇是否開機自動啓動
(一)、在AlertDialog的自定義佈局裏增長CheckBox,
<CheckBox
android:id="@+id/checkBox_boot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="開機自動啓動" />
(二)、採用SharedPreferences保存配置
CheckBox checkBox_boot = (CheckBox)dialogLayout.findViewById(R.id.checkBox_boot);
SharedPreferences sharedPref = MainActivity.this.getSharedPreferences("oaapp",Context.MODE_PRIVATE);
Editor editor = sharedPref.edit();
editor.putBoolean("boot", checkBox_boot.isChecked());
editor.commit();
(三)、修改BootBroadcastReceiver的onReceive方法:
SharedPreferences sharedPref = arg0.getSharedPreferences("oaapp",
Context.MODE_PRIVATE);
boolean boot = sharedPref.getBoolean("boot", true);
if (boot) {
Intent intent = new Intent(arg0, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
arg0.startActivity(intent);
}
使用KeyguardManager解除屏幕鎖定
當開機時,若是設置了屏幕鎖定,只有解除鎖定才能看到啓動的應用。這裏再增長代碼解除屏幕鎖定:
(一)、在BootBroadcastReceiver的onReceive裏增長
//解除屏幕鎖定
KeyguardManager keyguardManager = (KeyguardManager)arg0.getSystemService(arg0.KEYGUARD_SERVICE);
KeyguardLock keyguardLock = keyguardManager.newKeyguardLock(arg0.KEYGUARD_SERVICE);
keyguardLock.disableKeyguard();
(二)、在manifest.xml裏增長權限
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />