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方法。