Android Service使用

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)

作者:Work Hard Work Smart
出处:http://www.cnblogs.com/linlf03/
欢迎任何形式的转载,未经作者同意,请保留此段声明!

原文地址:https://www.cnblogs.com/linlf03/p/3135273.html