work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Android Service使用

Posted on 2013-06-14 11:30  work hard work smart  阅读(1598)  评论(0编辑  收藏  举报

Android开发中,当需要创建在后台运行的程序的时,就要用到Service。

Service跟Activities是不同的(可以理解为后台与前台的区别),

启动Service过程如下:

context.startService()  ->onCreate()- >onStart()->Service running

其中onCreate()可以进行一些服务的初始化工作.

停止Service过程如下:

context.stopService() | ->onDestroy() ->Service stop

示例:

 

public class myservice extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override 
	public void onCreate(){
		Toast.makeText(this, "My Service Create", Toast.LENGTH_SHORT).show();
	}
	
	@Override
	public void onDestroy(){
		 Toast.makeText(this, "My Service Destroy", Toast.LENGTH_SHORT).show();
	}
	
	@Override
	public void onStart(Intent intent, int startId)
	{
		 Toast.makeText(this, "My Service Started", Toast.LENGTH_SHORT).show();

	}

}

 

 调用:

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.StartSevice:
			startService(new Intent(this, myservice.class));
			break;
		case R.id.StopService:
			stopService(new Intent(this, myservice.class));
			break;
		}
	}

 调用startService方法时,执行myservice中的onCreate方法和onDestroy方法。

 调用stopService方法时,执行onDestroy方法。

 

Android服务总结

Android服务使用

Android中Service的使用详解和注意点(LocalService)

Android 使用AIDL调用外部服务 (RemoteService)