onCreate()>onstart()>onDestroy()
startService(Intent intent);
public boolean bindService(Intent intent,ServiceConnection conn;int flags);
*MainActivity
............................
public Button.onClickListener startService=new Button.OnClickListener(){
public void onClick(View view){
Intent intent=new Intent(MainActivity.this,CountService.class);
startService(intent);
Log.v();}
};
public Button.OnClickListener shutdownService=new Button.OnClickListener(){
public void onClick(View view){
Intent intent=new Intent(MainActivity.this,CountService.class);
stopServicce(intent);
...............
*Service
public class CountService extends Service{
boolean threadDisable;
int count;
public IBinder onBind(Intent intent){
return null;
}
public void onCreate(){
super.onCreate();
//创建一个线程,每秒计数器加1,输出Log
new Thread(new Runable(){
public void run(){
while(!threadDisable){
try{
Thread.sleep(1000);
}catch(InterruptedExeption e){
}
count++;
Log.v("CountSerevice","Count is"+count);
}}
}).start();
}
public void onDestroy(){
super.onDestroy();
//服务停止时,终止计数进程
this。threadDisable=true;
}
public int getConunt(){
return count;
}
//此方法为了可以在Activity中获得服务的实例
class ServiceBinder extends Binder{
public CountService getService(){
return CountService.this;
}
*binderService
public class UseBrider extends Activity{
//参数设置
CountService countService;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(new useBriderFace(this));
Intent intent=new Intent(UseBrider.this,CountService.class);
//进入Activity开始服务
bindService(intent,conn,Context.BIND_AUTO_CREATE);
}
private ServiceConnection conn=new ServiceConnection(){
//获取Service对象
public void onServiceConneted(ConponentName,IBinder service){
countService=({CountService.ServiceBinder}service).getServie();
}
//无法获取服务对象时的操作
public void onServiceDisconnected(ConponentName name){
countService=null;
}
};
protected void onDestory(){
super.onDestroy();
this.unbindService(conn);
loy.v("MainStadyService","out");
}}
public IBinder onBind(Intent intent){
System.out.ptintln("onBind....");
IBinder result=null;
if(null==result)
result=new MyBinder();
Toast.makeText(this,"onBind",Toast.LENGTH_LONG);
return result;
}
thinking between bindService&startService
原文:http://www.cnblogs.com/gentspy/p/5251197.html