zoukankan      html  css  js  c++  java
  • Service的启动与停止、绑定与解绑

    ---恢复内容开始---

      Service的意义就在于当软件停止之后还可以在背景中进行运行,换句话也就是说,比如一个音乐播放器,当我们退出音乐播放器的时候,还是希望它在背景中运行,也就是一直播放着音乐,这时候Service就派上了大的用途。

      Service的生命周期和Activity的生命周期差不多。也有开启和停止。onCreate()方法是初始化配置,onDestroy()是释放所有剩余的资源。Service周期是发生在onCreate()onDestroy()之间的。

        startService()方法是启动Service

        StopService()方法是停止Service

        bindService()方法是启动Service的激活生命周期始于onBind()调用,在onUnbind()返回时结束。

      当一个组件启动Service时,是通过startService()进行启动Service,Service被启动之后,onStartCommand()方法被调用,并且接收startService()方法中传递的Intent值。

      onStartServiceCommand()方法必修返回一个整形值。这个整形值是说明了Service在系统中如何执行。其中三个比较常用的解释如下:

        START_NOT_STICKY:如果系统在onStartServiceCommand()返回后杀死Service,那么不会重新创建Service,除非有等待的Intent要传递。

        START_STICKY 如果系统在onStartServiceCommand()返回后杀死Service,重启Service,并且重新调用onStartServiceCommand(),但不重新传递最新的Intent

        START_REDELIVER_INTENT 如果系统在onStartServiceCommand()返回后杀死Service,那么重新创建Service,并且最近传给ServiceIntent调用onStartServiceCommand()

      创建一个Service启动周期的实例

      

     1 public class MyService extends Service{
     2     
     3     //必须实现的方法,作用是用来返回binder对象
     4     
     5     
     6     //重写onBind()方法,返回Service实例,使Service支持绑定,实现onBind()方法,并且返回MyService实例
     7     @Override
     8     public IBinder onBind(Intent intent) {
     9         // TODO Auto-generated method stub
    10         System.out.println("--onBind--");
    11         return null;
    12     }
    13     
    14     
    15     //用于创建Service的方法,只能调用一次
    16     public void onCreate(){
    17         super.onCreate();
    18         System.out.println("--onCreate--");
    19 
    20     //每次启动Service时都会调用这个方法
    21     @Override
    22     public int onStartCommand(Intent intent, int flags, int startId) {
    23         // TODO Auto-generated method stub
    24         System.out.println("--onStartCommand--");
    25         return super.onStartCommand(intent, flags, startId);
    26     }
    27     
    28     //解绑的时候使用的这个方法
    29     @Override
    30     public boolean onUnbind(Intent intent) {
    31         // TODO Auto-generated method stub
    32         System.out.println("--onUnbind--");
    33         return super.onUnbind(intent);
    34     }
    35     
    36     //退出或者销毁的时候使用这个方法
    37     @Override
    38     public void onDestroy() {
    39         // TODO Auto-generated method stub
    40         serviceRunning = false;
    41         System.out.println("--onDestroy--");
    42         super.onDestroy();
    43         
    44     }
    45 
    46 }

    注意:在测试的时候一定要在onCreate()方法中写一个多线程,以便输出,让我们更加的明白。如下:

     1 //用于创建Service的方法,只能调用一次
     2     public void onCreate(){
     3         super.onCreate();
     4         System.out.println("--onCreate--");
     5         serviceRunning = true;
     6         new Thread(){
     7             public void run(){
     8                 while(serviceRunning){
     9                     System.out.println("--Service运行中--");
    10                     try{
    11                         sleep(1000);
    12                     }catch(Exception e){
    13                         e.printStackTrace();
    14                     }
    15                 }
    16             }
    17         }.start();
    18     }

    绑定Service

      绑定Service的时候会比较的复杂,其中,看绑定方法bindService(Intent service, ServiceConnection conn, int flags)时大家就可以看出。其中Intent需要传递Intent的值,connServiceConnection的实例,flags是所需要的一个标示。下面就为大家解析绑定Service所需要的三个步骤:

     

      第一步:需要在Service中创建一个Binder接口,并且实现:

     

    1. 包含客户端可以调用public方法

    2. 或返回当前Service的实例--也包含客户端可以调用的Public方法

    3. 或返回Service持有的其他类型的实例--也包含客户端可以调用的Public方法

      代码如下:

     

    public class MyBinder extends Binder{
    		MyService getService(){
    			return MyService.this;
    		}
    	}
    

     

      

       第二步:在onBind()中返回Binder实例。

      代码如下:

     

    1 //必须实现的方法,作用是用来返回binder对象
    2 //重写onBind()方法,返回Service实例,使Service支持绑定,实现onBind()方法,并且返回MyService实例
    3     @Override
    4     public IBinder onBind(Intent intent) {
    5         // TODO Auto-generated method stub
    6         System.out.println("--onBind--");
    7         return null;
    8     }

     

      第三步:在客户端中,从onServiceConnected()回调方法中接收这个Binder,并且使用Binder包含的Service提供的方法。

      比如:

     

     1 public class MyServiceConn implements ServiceConnection{
     2 
     3     MyService.MyBinder binder = null;
     4     
     5     @Override
     6     public void onServiceConnected(ComponentName name, IBinder service) {
     7         // TODO Auto-generated method stub
     8         binder = (MyService.MyBinder)service;
     9     }
    10 
    11     @Override
    12     public void onServiceDisconnected(ComponentName name) {
    13         // TODO Auto-generated method stub
    14         binder = null;
    15     }
    16 
    17 }

     

      注意:一定要在客户端中声明这个实例:

     1 final MyServiceConn myserviceconn = new MyServiceConn(); 

     

      客户端在合适的时候也可以进行解绑:

     

    1 //解除绑定的Service
    2         unbind.setOnClickListener(new OnClickListener() {
    3             
    4             @Override
    5             public void onClick(View v) {
    6                 // TODO Auto-generated method stub
    7                 unbindService(myserviceconn);
    8             }
    9         });

     

      上述就把Service的启动、停止、绑定、解绑就完成了,下面的则是客户端的一些的代码:

      

     1 import android.app.Activity;
     2 import android.content.ComponentName;
     3 import android.content.Context;
     4 import android.content.Intent;
     5 import android.content.ServiceConnection;
     6 import android.os.Bundle;
     7 import android.os.IBinder;
     8 import android.view.View;
     9 import android.view.View.OnClickListener;
    10 import android.widget.Button;
    11 
    12 public class MainActivity extends Activity {
    13 
    14     private Button start;
    15     private Button stop;
    16     private Button bind;
    17     private Button unbind;
    18     private Intent intent;
    19     
    20     @Override
    21     protected void onCreate(Bundle savedInstanceState) {
    22         super.onCreate(savedInstanceState);
    23         setContentView(R.layout.activity_main);
    24         start = (Button)findViewById(R.id.btn1);
    25         stop = (Button)findViewById(R.id.btn2);
    26         bind = (Button)findViewById(R.id.btn3);
    27         unbind = (Button)findViewById(R.id.btn4);
    28         
    29         final MyServiceConn myserviceconn = new MyServiceConn();
    30         
    31         //给按钮设置事件,以便监听Service中的变化
    32         //开启service
    33         start.setOnClickListener(new OnClickListener() {
    34             
    35             @Override
    36             public void onClick(View v) {
    37                 // TODO Auto-generated method stub
    38                 intent = new Intent(getApplicationContext(),MyService.class);
    39                 startService(intent);
    40             }
    41         });
    42         
    43         //结束Service
    44         stop.setOnClickListener(new OnClickListener() {
    45             
    46             @Override
    47             public void onClick(View v) {
    48                 // TODO Auto-generated method stub
    49                 stopService(intent);
    50             }
    51         });
    52         
    53         //绑定service服务
    54         bind.setOnClickListener(new OnClickListener() {
    55             
    56             @Override
    57             public void onClick(View v) {
    58                 // TODO Auto-generated method stub
    59                 bindService(intent,myserviceconn,Context.BIND_AUTO_CREATE);
    60             }
    61         });
    62         
    63         //解除绑定的Service
    64         unbind.setOnClickListener(new OnClickListener() {
    65             
    66             @Override
    67             public void onClick(View v) {
    68                 // TODO Auto-generated method stub
    69                 unbindService(myserviceconn);
    70             }
    71         });
    72     }
    73 
    74 
    75 }

     

    XML文件的代码(只是一些简单的按钮,就不解释了):

      

     1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     2     xmlns:tools="http://schemas.android.com/tools"
     3     android:id="@+id/LinearLayout1"
     4     android:layout_width="match_parent"
     5     android:layout_height="match_parent"
     6     android:orientation="vertical"
     7     tools:context=".MainActivity" >
     8 
     9     <TextView
    10         android:layout_width="wrap_content"
    11         android:layout_height="wrap_content"
    12         android:text="@string/service" />
    13 
    14     <Button
    15         android:id="@+id/btn1"
    16         android:layout_width="wrap_content"
    17         android:layout_height="wrap_content"
    18         android:text="StartService" />
    19 
    20     <Button
    21         android:id="@+id/btn2"
    22         android:layout_width="wrap_content"
    23         android:layout_height="wrap_content"
    24         android:text="StopService" />
    25 
    26     <Button
    27         android:id="@+id/btn3"
    28         android:layout_width="wrap_content"
    29         android:layout_height="wrap_content"
    30         android:text="bindService" />
    31 
    32     <Button
    33         android:id="@+id/btn4"
    34         android:layout_width="wrap_content"
    35 android:layout_height="wrap_content" 36 android:text="unBindService" /> 37 38 </LinearLayout>

     

    一定要注意在AndroidManifest.xml文件中加上权限:

     

    1 <service            android:name="com.example.servicetest.MyService">   
    2  </service>

     

      到这里就完了,有什么不懂或者不对的地方可以留言,至于截图,上述的代码比较详细,我这里就不贴出了。

     

     

     

     

     

     

     

     

     

    ---恢复内容结束---

  • 相关阅读:
    apscheduler 踩坑
    fastapi 导出excel文件
    python flask 使用日志
    git 头指针游离问题
    C# 连接mysql填坑
    前端项目proxy小问题
    需完善--日志框架
    依赖<dependency>的scope了解
    git 退回到指定tag版本
    git切换远程仓库地址
  • 原文地址:https://www.cnblogs.com/bingbingliang-xiaomonv/p/5204680.html
Copyright © 2011-2022 走看看