博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Android : 使一个Serviec 开机自启动!

Posted on 2011-03-24 17:22  nobile.amir  阅读(704)  评论(0编辑  收藏  举报

   想要实现一个自启动的功能,要扑捉系统的开机广播,我理解成时系统启动的广播通知:

   不说了,直接上代码:

  扑捉系统启动广播通知的类。 要继承系统  BroadcastReceiver类, 并且实现

public void onReceive(Context aContext, Intent aIntent),还是看下边的代码:
package com.amir.bootflag;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class BootMointor extends BroadcastReceiver {

	public void onReceive(Context aContext, Intent aIntent) {
		if (aIntent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
			Intent in = new Intent(aContext, BufferServices.class); 
			in.setAction("com.amir.bootflag.BUFFER_SERVICES");
			aContext.startService(in);
		}
	}

}


  实现要启动的Service 的类:

package com.amir.bootflag;

import com.amir.dbbuf.service.Md_0XEECMD_;
import com.amir.dbbuf.service.OX_ECMD_Service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class BufferServices extends Service{

	public IBinder onBind(Intent arg0) {
		return null;
	}

	public void onCreate() {
		super.onCreate();
		Log.v("<====>", "onCreate");
	}

	public void onDestroy() {
		super.onDestroy();
		Log.v("<====>", "onDestroy");
	}

	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		System.out.println("OnStart Service");
		OX_ECMD_Service ecmd = new OX_ECMD_Service(this.getBaseContext());
		Md_0XEECMD_ o1 = new Md_0XEECMD_();
		System.out.println("databases object");
		o1.setiCmdTypeField(0);
		o1.setiPrimaryKeyField(1);
		o1.setiReasonField(0);
		o1.setiYnField(1);
		
		ecmd.InsertL(o1);
	}

	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.v("<====>", "onStartCommand");
		return super.onStartCommand(intent, flags, startId);
	}

}


  咱们再看看 AndroidManifest.xml 里,要写一些什么:

<service android:name="com.amir.bootflag.BufferServices">
			<intent-filter>
				<action android:name="com.amir.bootflag.BUFFER_SERVICES" />
				<category android:name="android.intent.category.DEFAULT" />
			</intent-filter>
		</service>

		<receiver android:name="BootMointor">
			<intent-filter>
				<action android:name="android.intent.action.BOOT_COMPLETED" />
			</intent-filter>
		</receiver>


要想扑捉系统启动的广播通知,需要添加下边的权限:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />