好记性不如铅笔头

android, 编程

Android应用开发笔记:Service的相关知识

android的service是一个使用的非常频繁的组件,这里简单的备忘下使用代码:

public class LocationService extends Service
{
	public static void startLocationService(Context context)
	{
		if (null == context)
		{
			return;
		}
		context = context.getApplicationContext();
		context.startService(new Intent(context, LocationService.class));
	}
	public static void stopLocationService(Context context)
	{
		if (null == context)
		{
			return;
		}
		context = context.getApplicationContext();
		context.stopService(new Intent(context, LocationService.class));
	}
	
	private LocationBinder binder = new LocationBinder();
	public class LocationBinder extends Binder
	{
		public void sendWeatherReq()
		{
			LocationService.this.sendWeatherReq();
		}
	}
	
	private static final String TAG = "LocationService";
	
	@Override
	public IBinder onBind(Intent intent) {
		return binder;
	}

	@Override
	public void onCreate() 
	{
		Log.e(TAG, "The LocationService Is onCreate");
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
//		return super.onStartCommand(intent, flags, startId);
		Log.e(TAG, "The LocationService Is onStartCommand");
		return START_NOT_STICKY;
	}

	@Override
	public void onDestroy() 
	{
		Log.e(TAG, "The LocationService Is onDestroy");
		super.onDestroy();
	}
	    
	private static final int MSG_WEATHER = 0;
	public void handleMessage(Message msg) 
	{
		switch (msg.what) {
		case MSG_WEATHER:
		{
			sendWeatherReq();
			break;
		}
		default:
			break;
		}
		
	}   
	private LocationSerHandler handler = new LocationSerHandler(this);
    private static class LocationSerHandler extends Handler
    {
    	private WeakReference<LocationService> service = null;
    	private LocationSerHandler(LocationService ls) {
			super();
			this.service = new WeakReference<LocationService>(ls);
		}
    	@Override
		public void handleMessage(Message msg) 
		{
    		LocationService ls = service.get();
    		if (ls != null)
    		{
    			ls.handleMessage(msg);
    		}
    }    
}

 备注:

1)关于onstartcommand方法的返回值,有个【 文章 】写得不错,转一下:

从Android官方文档中,我们知道onStartCommand有4种返回值:

START_STICKY:如果service进程被kill掉,保留service的状态为开始状态,但不保留递送的intent对象。随后系统会尝试重新创建service,由于服务状态为开始状态,所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。如果在此期间没有任何启动命令被传递到service,那么参数Intent将为null。

START_NOT_STICKY:“非粘性的”。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统不会自动重启该服务。

START_REDELIVER_INTENT:重传Intent。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入。

START_STICKY_COMPATIBILITY:START_STICKY的兼容版本,但不保证服务被kill后一定能重启。

 2)其他参考

http://android.blog.51cto.com/268543/527314 】

http://www.cnblogs.com/newcj/archive/2011/05/30/2061370.html 】

http://blog.csdn.net/android_tutor/article/details/5789203 】

发表评论

17 + 2 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据