1.3.1版本之后谷歌为了安全性,新安装的程序必须启动过之后才可以接收广播。防止流氓软件。
2.3.1版本之后service开机自启动不在支持。必须通过其他方式如Activity启动。
3. The methods startForeground()
and stopForeground()
were introduced in Android 2.0 (API Level 5),Service的setForeground(boolean boolean)在2.0之后不再支持。换成相同功能换成Service的
startForeground(int, Notification);方法啦
4.参考资料http://www.cnblogs.com/ylligang/articles/2665181.html
5.http://blog.csdn.net/joychine/article/details/10947819.
6.以下代码经测试在android 4.1小米系统下开机重启不启动,说明开机不能直接启动系统广播服务。2.3是可以的。
package com.allenlee.bootstartService; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.SystemClock; import android.util.Log; public class BootBroadcast extends BroadcastReceiver { @Override public void onReceive(Context context, Intent mintent) { if (Intent.ACTION_BOOT_COMPLETED.equals(mintent.getAction())) { Log.i("------------------------------------", "开机自启动BootBroadcast"); // 启动完成 Intent intent = new Intent(context, Alarmreceiver.class); intent.setAction("arui.alarm.action"); PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0); long firstime = SystemClock.elapsedRealtime(); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // 10秒一个周期,不停的发送广播 am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstime,10 * 1000, sender); }else{ Log.i("**************************************", "开机未启动BootBroadcast"); } } }
7.开机启动Activity在2.3种测试成功,在小米4.1中没有启动成功。代码如下。
package com.allen.location; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class BootService extends BroadcastReceiver { String tag = BootService.class.getSimpleName(); @Override public void onReceive(Context context, Intent mintent) { if (mintent.getAction().equals("android.intent.action.BOOT_COMPLETED")) { Log.i(tag, "****** system boot completed ******"); Intent it = new Intent(context, MainActivity.class); it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(it); }else{ Log.i(tag, "--------------未接收-----------------"); } } }
8在百度云4.0系统下,当配置文件设置成同时加载启动广播和MainActivity时,开机自动启动MainActivity,在MainAcitity启动服务,并关闭MainActivity.测试成功。小米已经允许自启动了,可是还是开机启动不了。可能跟一个报错的权限有关系。但是朋友的小米4.1可以。配置如下
<!-- 开机自启动服务 --> <receiver android:name="com.allen.location.BootService" android:label="@string/app_name" android:permission="android.permission.RECEIVE_BOOT_COMPLETED" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </receiver> <activity android:name=".MainActivity" android:screenOrientation="portrait" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>