說明: 我們的app有時候有設置開機是否自啓動的需求。開機自啓動其實很簡單。
要設置自啓動,首先,我們要讓app能夠自己啓動:
第一步實現自啓動
1、權限不能沒有:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
2、我們需要一個廣播:這裏的MainActivity.class是你想要啓動的Activity
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Intent intent2 = new Intent(context, MainActivity.class);
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent2);
}
}
}
3、還要註冊這個廣播,這裏要說的是,開機完成的廣播是系統廣播,不允許在代碼裏面註冊:
<receiver android:name=".BootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
到這裏,自啓動就能實現了。
第二步控制是否自啓動:
之前一直覺得,用SharedPreferences存一個標誌就能實現,比如
public class BootReceiver extends BroadcastReceiver {
public final static String AUTO_START = "AUTO_START";
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
SharedPreferences settings = context.getSharedPreferences(AUTO_START,Context.MODE_PRIVATE);
if(settings.getBoolean("AUTO_START", false)){
Intent intent2 = new Intent(context, MainActivity.class);
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent2);
}
}
}
}
然而發現,並沒有什麼用,這裏都取不到這個SharedPreferences存的值,我也不知爲毛,那就只能找其他方法了;
在互聯網的世界遊蕩,終於看到了這個標題。“Android禁用和開啓四大組件的方法”原文:http://blog.csdn.net/mingli198611/article/details/17269355,當時就懵逼了,四大組件還能禁用?
看了這篇文章還真找到了完成我們需求的方法:
當我們設置開機禁止自啓動的時候:只要把我們的BootReceiver幹掉就行了;
具體如下:
private void setComponentEnabled(Class<?> clazz, boolean enabled) {
final ComponentName c = new ComponentName(this, clazz.getName());
getPackageManager().setComponentEnabledSetting(c,
enabled ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
: PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
先說下這兩個參數。第一個:BootReceiver.class,第二個:就是你的開機是否自啓動boolean值了;
再說一下這個方法:
setComponentEnabledSetting (ComponentName componentName, int newState, int flags)
componentName:組件名稱
newState:組件新的狀態,可以設置三個值,分別是如下:
不可用狀態:COMPONENT_ENABLED_STATE_DISABLED
可用狀態:COMPONENT_ENABLED_STATE_ENABLED
默認狀態:COMPONENT_ENABLED_STATE_DEFAULT
flags:行爲標籤,值可以是DONT_KILL_APP或者0。 0說明殺死包含該組件的app。
到這裏app設置開機是否自啓動就完工了;
不過我還是想囉嗦一句:希望大家還是看一看
大家都知道,現在的手機,有自帶內存的,還有可以插SD卡的,在Android API Level大於8的時候,程序是可以安裝在SD卡上的。那麼問題又來了,很不幸的,你的app被用戶安裝在SD卡,可是SD卡掛載是在BOOT_COMPLETED這廣播發送之後纔開始的,So,你的app一樣不能啓動。但是別擔心啊:Android框架說:Don’t call me, I’ll call you back。SD掛載完成了,一樣是有廣播的。去監聽這個廣播就行了。