开机自动启动Service,做这个烦恼我好几天了,是因为在服务中加了toast导致自启服务不成功

来源:互联网 发布:象过河软件怎么样 编辑:程序博客网 时间:2024/04/30 02:56

服务的代码

MyService.java

package com.lzy.bootservice;import android.app.Service;import android.content.Intent;import android.os.IBinder;public class MyService extends Service{@Overridepublic IBinder onBind(Intent arg0) {// TODO Auto-generated method stubreturn null;}@Overridepublic void onCreate() {// TODO Auto-generated method stubSystem.out.println("初始化service");super.onCreate();}@Overridepublic void onDestroy() {// TODO Auto-generated method stubSystem.out.println("service灭亡");super.onDestroy();}@Overridepublic void onStart(Intent intent, int startId) {// TODO Auto-generated method stubSystem.out.println("service 启动了");super.onStart(intent, startId);}}

注册广播监听

BootBroadcastReceiver.java

package com.lzy.bootservice;import android.content.BroadcastReceiver;  import android.content.Context;  import android.content.Intent;    public class BootBroadcastReceiver extends BroadcastReceiver {    static final String ACTION = "android.intent.action.BOOT_COMPLETED";      @Override   public void onReceive(Context context, Intent intent) {        if (intent.getAction().equals(ACTION)){    Intent i  = new Intent();i.setClass(context, MyService.class);context.startService(i);System.out.println("到这里?");  }  }  }  

最后最重要的是要在项目清单文件中加入service以及广播注册监听receiver

清单文件

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.lzy.bootservice"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk android:minSdkVersion="8" />    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>        <application        android:icon="@drawable/ic_launcher"        android:label="@string/app_name" >        <activity            android:label="@string/app_name"            android:name=".BootServiceActivity" >            <intent-filter >                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <receiver android:name=".BootBroadcastReceiver">    <intent-filter>      <action android:name="android.intent.action.BOOT_COMPLETED" />     </intent-filter>    </receiver>   <service android:name=".MyService" android:exported="true"></service>    </application></manifest>


0 0
原创粉丝点击