原理:注册广播接受者收到开机启动信息,然后启动服务,服务做操作(例如从后台接收消息后显示在任务栏上面去,从而达到消息推送的效果)
1.创建广播接受者
<pre class="html" name="code" snippet_file_name="blog_20160312_3_9845105" code_snippet_id="1607321">public class BootBroadcastReceiver extends BroadcastReceiver {
@Override public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context,ServiceCrack.class);
context.startService(service); Log.d("test","开机自启动服务"); }
}
2.创建服务
<pre class="html" name="code" snippet_file_name="blog_20160312_9_8809520" code_snippet_id="1607321">public class ServiceCrack extends Service {
@Nullable @Override public IBinder onBind(Intent intent) {
return null;
}
@Override public void onCreate() {
super.onCreate();
new Thread(){
@Override public void run() {
super.run();
int i = 1;
while(true){
Log.d("test","收到消息"+i);
i++;
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start(); }}
3.在xml文件中添加权限以及描述广播和服务
<pre class="html" name="code"> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<service
android:name=".service.ServiceCrack"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
</service>
<receiver android:name=".broadcast.BootBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>