service生命周期及使用

 service的原理在这里就不在复述了,下面直接介绍service的两种启动方式及生命周期。

           首先建立一个serviceDemo,如图所示。

           

       然后修改main.xml布局文件:

    

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:id="@+id/text"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="@string/hello" />  
  12.   
  13.     <Button  
  14.         android:id="@+id/startservice"  
  15.         android:layout_width="fill_parent"  
  16.         android:layout_height="wrap_content"  
  17.         android:text="startService" />  
  18.   
  19.     <Button  
  20.         android:id="@+id/stopservice"  
  21.         android:layout_width="fill_parent"  
  22.         android:layout_height="wrap_content"  
  23.         android:text="stopService" />  
  24.   
  25.     <Button  
  26.         android:id="@+id/bindservice"  
  27.         android:layout_width="fill_parent"  
  28.         android:layout_height="wrap_content"  
  29.         android:text="bindService" />  
  30.   
  31.     <Button  
  32.         android:id="@+id/unbindservice"  
  33.         android:layout_width="fill_parent"  
  34.         android:layout_height="wrap_content"  
  35.         android:text="unbindService" />  
  36.   
  37. </LinearLayout>  
         接下来 建立一个MyService来继承service

       

[java]  view plain copy
  1. public class MyService extends Service {  
  2.      private static final String TAG = "MyService";    
  3.      private MyBinder mBinder=new MyBinder();  
  4.     @Override  
  5.     public IBinder onBind(Intent arg0) {  
  6.         // TODO Auto-generated method stub  
  7.           Log.e(TAG, "start IBinder~~~");    
  8.         return mBinder;  
  9.     }  
  10.     @Override  
  11.     public void onCreate() {  
  12.         // TODO Auto-generated method stub  
  13.          Log.e(TAG, "start onCreate~~~");    
  14.         super.onCreate();  
  15.     }  
  16.     @Override  
  17.     public void onDestroy() {  
  18.         // TODO Auto-generated method stub  
  19.           Log.e(TAG, "start onDestroy~~~");    
  20.         super.onDestroy();  
  21.     }  
  22.     @Override  
  23.     public int onStartCommand(Intent intent, int flags, int startId) {  
  24.         // TODO Auto-generated method stub  
  25.          Log.e(TAG, "start onStartCommand~~~");    
  26.         return super.onStartCommand(intent, flags, startId);  
  27.     }  
  28.     @Override  
  29.     public boolean onUnbind(Intent intent) {  
  30.         // TODO Auto-generated method stub  
  31.          Log.e(TAG, "start onUnbind~~~");    
  32.         return super.onUnbind(intent);  
  33.     }  
  34.     public String getSystemTime(){    
  35.           /*Time t=new Time(); 
  36.           t.setToNow();*/  
  37.           SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  38.           return format.format(new Date());  
  39.     }  
  40.      public class MyBinder extends Binder{  
  41.             public MyService getService(){  
  42.                 return MyService.this;  
  43.             }  
  44.      }  
  45.         
  46. }  
    分别实现了他的相应的生命周期方法,然后修改主activity为:

[java]  view plain copy
  1. public class ServiceDemoActivity extends Activity implements OnClickListener{  
  2.     /** Called when the activity is first created. */  
  3.      private MyService mMyService;  
  4.      private TextView mTextView;  
  5.      private Context mContext;  
  6.      private Button startServiceButton;    
  7.      private Button stopServiceButton;    
  8.      private Button bindServiceButton;    
  9.      private Button unbindServiceButton;    
  10.        
  11.     //这里需要用到ServiceConnection在Context.bindService和context.unBindService()里用到    
  12.     private ServiceConnection mServiceConnection = new ServiceConnection() {    
  13.         //当我bindService时,让TextView显示MyService里getSystemTime()方法的返回值     
  14.   
  15.         @Override  
  16.         public void onServiceConnected(ComponentName name, IBinder service) {  
  17.             // TODO Auto-generated method stub  
  18.              mMyService = ((MyService.MyBinder)service).getService();    
  19.             mTextView.setText("I am frome Service :" + mMyService.getSystemTime());    
  20.        
  21.         }  
  22.   
  23.         @Override  
  24.         public void onServiceDisconnected(ComponentName name) {  
  25.             // TODO Auto-generated method stub  
  26.               
  27.         }    
  28.     };  
  29.     @Override  
  30.     public void onCreate(Bundle savedInstanceState) {  
  31.         super.onCreate(savedInstanceState);  
  32.         setContentView(R.layout.main);  
  33.         setupViews();    
  34.     }  
  35.     private void setupViews(){  
  36.         mContext=this;  
  37.         mTextView=(TextView) this.findViewById(R.id.text);  
  38.            
  39.           startServiceButton = (Button)findViewById(R.id.startservice);    
  40.           stopServiceButton = (Button)findViewById(R.id.stopservice);    
  41.           bindServiceButton = (Button)findViewById(R.id.bindservice);    
  42.           unbindServiceButton = (Button)findViewById(R.id.unbindservice);    
  43.     
  44.           startServiceButton.setOnClickListener(this);    
  45.           stopServiceButton.setOnClickListener(this);    
  46.           bindServiceButton.setOnClickListener(this);    
  47.           unbindServiceButton.setOnClickListener(this);    
  48.     }  
  49.     @Override  
  50.     public void onClick(View v) {  
  51.         // TODO Auto-generated method stub  
  52.          if(v == startServiceButton){    
  53.                 Intent i  = new Intent();    
  54.                 i.setClass(ServiceDemoActivity.this, MyService.class);    
  55.                 mContext.startService(i);    
  56.             }else if(v == stopServiceButton){    
  57.                 Intent i  = new Intent();    
  58.                 i.setClass(ServiceDemoActivity.this, MyService.class);    
  59.                 mContext.stopService(i);    
  60.             }else if(v == bindServiceButton){    
  61.                 Intent i  = new Intent();    
  62.                 i.setClass(ServiceDemoActivity.this, MyService.class);    
  63.                 mContext.bindService(i, mServiceConnection, BIND_AUTO_CREATE);    
  64.             }else{    
  65.                 mContext.unbindService(mServiceConnection);    
  66.             }    
  67.     }  
  68. }  
      在这里不要忘记在AndroidManifest.xml里注册service

      下面看一下运行效果:

      

      点击startService按钮看一下打印的log日志:

      

     首先开启一个start服务先是执行了onCreate方法和onStartCommand方法,然后点击stopService按钮:

     

    执行了onDestroy方法,知道了这些生命周期方法后我们就可以在这些生命周期方法里做一些相应的事件了。

    下面点击一下bindService按钮看会出现什么效果吧:

   

    在最上方打印出了系统时间,绑定服务其实就是让服务执行完后,返回一些数据给启动它的组件比如activity。

     这是后台打印的log:


     最后点击unbindService取消绑定:

    

   绑定服务 生命周期结束 。

   下面让我们再看一下官方给出的两种服务的生命周期图:

     

        这样是不是一眼就看明白了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值