首页 > 代码库 > Android 开机自动启动服务
Android 开机自动启动服务
在前面的文章中提到了remote service 的创建过程,现在我们要让它开机自动启动
1.在前面代码的基础上添加 RemoteServiceBootReceiver.java ,实现一个intent的receiver
[java] view plaincopyprint?
- package com.fly;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.util.Log;
- public class RemoteServiceBootReceiver extends BroadcastReceiver {
- private static final String TAG = "U0fly RemoteServiceBootReceiver";
- static final String ACTION = "android.intent.action.BOOT_COMPLETED";
- @Override
- public void onReceive(Context arg0, Intent arg1) {
- Log.d(TAG, "Boot completed");
- // TODO Auto-generated method stub
- if (arg1.getAction().equals(ACTION)) {
- // service
- Intent myintent = new Intent(arg0, RemoteService.class);
- myintent.setAction("com.fly.RemoteService");
- arg0.startService(myintent);
- }
- }
- }
2.在AndroidManifast.xml中添加权限,并注册一个receiver
[java] view plaincopyprint?
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.fly" android:versionCode="1" android:versionName="1.0">
- <application android:icon="@drawable/icon" android:label="@string/app_name">
- <activity android:name=".RemoteServiceActivity"
- android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <service android:name="RemoteService">
- <intent-fliter>
- <action android:name="com.fly.RemoteService" />
- </intent-fliter>
- </service>
- <receiver android:name=".RemoteServiceBootReceiver">
- <intent-filter>
- <action android:name="android.intent.action.BOOT_COMPLETED" />
- </intent-filter>
- </receiver>
- </application>
- <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
- <uses-sdk android:minSdkVersion="7" />
- </manifest>
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。