美文网首页
Service基本解析

Service基本解析

作者: lxbnjupt | 来源:发表于2017-04-08 23:33 被阅读0次

Service是Android系统中的四大组件之一,其主要功能是在后台执行需要长期运行的任务,或者处理一些耗时操作。有时,甚至可以在程序退出的情况下,让Service在后台继续保持运行状态。

1.MainActivity代码

public class MainActivity extends Activity implements OnClickListener {  
  
    private Button startService;  
    private Button stopService;  
    private Button bindService;  
    private Button unbindService; 
    private MyService.MyBinder myBinder;  

    private ServiceConnection connection = new ServiceConnection() {  
        @Override  
        public void onServiceConnected(ComponentName name, IBinder service) {  
            myBinder = (MyService.MyBinder) service;  
            myBinder.doSomething();  
        } 
 
        @Override  
        public void onServiceDisconnected(ComponentName name) {  
        } 
    };  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        initViews();
    }  

    public void initViews() {
        startService = (Button) findViewById(R.id.start_service);  
        stopService = (Button) findViewById(R.id.stop_service);  
        bindService = (Button) findViewById(R.id.bind_service);  
        unbindService = (Button) findViewById(R.id.unbind_service);  

        startService.setOnClickListener(this);  
        stopService.setOnClickListener(this);  
        bindService.setOnClickListener(this);  
        unbindService.setOnClickListener(this); 
    }
  
    @Override  
    public void onClick(View v) {  
        switch (v.getId()) {  
        case R.id.start_service:  
            Intent startIntent = new Intent(this, MyService.class);  
            startService(startIntent);  
            break;  
        case R.id.stop_service:  
            Intent stopIntent = new Intent(this, MyService.class);  
            stopService(stopIntent);  
            break;  
        case R.id.bind_service:  
            Intent bindIntent = new Intent(this, MyService.class);  
            bindService(bindIntent, connection, BIND_AUTO_CREATE);  
            break;  
        case R.id.unbind_service:  
            unbindService(connection);  
            break;  
        default:  
            break;  
        }  
    }  
}   

2.Service代码

public class MyService extends Service {  
  
    public static final String TAG = MyService.class.getSimpleName();  
    private MyBinder myBinder = new MyBinder();  
  
    @Override  
    public void onCreate() {  
        super.onCreate();  
        Log.d(TAG, "MyService onCreate()");  
    }  
  
    @Override  
    public int onStartCommand(Intent intent, int flags, int startId) {  
        Log.d(TAG, "MyService onStartCommand()");  
        new Thread(new Runnable() {  
             @Override  
             public void run() {  
                 // 执行后台任务  
             }  
        }).start();   
        return super.onStartCommand(intent, flags, startId);  
    }  
  
    @Override  
    public void onDestroy() {  
        super.onDestroy();  
        Log.d(TAG, "MyService onDestroy()");  
    }  
  
    @Override  
    public IBinder onBind(Intent intent) {  
        return myBinder;  
    }  
  
    class MyBinder extends Binder {  
        public void doSomething() {  
            new Thread(new Runnable() {  
                @Override  
                public void run() {  
                    // 执行具体任务  
                }  
            }).start();   
        }  
    }  
}

3.启动Service
在MainActivity中可以看到,在startService按钮的点击事件里,通过构建Intent对象,并调用startService()方法来启动MyService;在stopSerivce按钮的点击事件里,同样通过构建出Intent对象,并调用stopService()方法来停止MyService。

当我们第一次启动一个Service的时候,会调用该Service中的onCreate()和onStartCommand()方法,当再次启动该Service时只有onStartCommand()方法会被执行,原因是onCreate()方法只会在Service第一次被创建的时候调用。启动Service之后,就可以在onCreate()或onStartCommand()方法中执行具体的操作了。

4.绑定Service
通过绑定Service,可以让MainActivity和MyService之间建立关联,即在Activity中指定让Service执行具体的任务,如后台播放音乐等等。

在MyService中,我们可以看到有一个onBind()方法,这个方法其实就是用于和Activity建立关联的。在MainActivity中,创建了ServiceConnection的匿名类,并重写onServiceConnected()方法和onServiceDisconnected()方法,这两个方法分别会在Activity与Service建立绑定和解除绑定的时候调用。bindService(bindIntent, connection, BIND_AUTO_CREATE)方法用来完成Activity与Service的绑定。在onServiceConnected()方法中,得到了MyBinder的实例,我们可以在Activity中根据具体的场景来调用MyBinder中的任何public方法,即实现了Activity指定Service执行相关的具体操作。如果想解除绑定,只需要调用unbindService(connection)方法即可。

5.销毁Service
如果通过startService()方法启动Service,则stopService()方法可以停止Service,这样Service就被销毁了;如果通过bindService()方法绑定Service,并且指定的标志位是BIND_AUTO_CREATE,则通过unbindService()方法可以将Activity和Service解除绑定;如果既调用了startService()方法启动Service,又调用了bindService()方法绑定Service,则必须通过调用stopService()方法和unbindService()方法才可以将Service销毁,因为一个Service必须要在既没有和任何Activity关联又处于停止状态的时候才会被销毁。

相关文章

  • Service基本解析

    Service是Android系统中的四大组件之一,其主要功能是在后台执行需要长期运行的任务,或者处理一些耗时操作...

  • Android Service学习笔记

    参考:Android Service完全解析,关于服务你所需知道的一切(上)Android Service完全解析...

  • Service相关

    Service基本用法、Service生命周期、service与Activity通信 一、Service基本用法 ...

  • 【面试题】请描述一下Service 的生命周期

    参考:Service 生命周期Android:Service生命周期 完全解析

  • Service解析

    什么是服务? Service是一个应用程序组件,它能够在后台执行一些耗时较长的操作,并且不提供用户界面。服务能被其...

  • Service基本

    从这个文章开始,我就使用kotlin来进行编写,锻炼下自己对kotlin的熟悉程度,好啦,开始正文:Service...

  • IaaS、PaaS、SaaS理解

    首先名词解析:IaaS:Infrastructure as a Service;PaaS:Platform as ...

  • Dubbo源码研究

    一、Dubbo服务暴露前奏 读取解析Spring Bean,的解析利用的...

  • kube-proxy 源码分析

    上篇文章 kubernetes service 原理解析 已经分析了 service 原理以 kube-proxy...

  • Service的使用解析:

    Service的使用解析:1,2,当启动一个Service的时候,会调用该Service中的onCreate()o...

网友评论

      本文标题:Service基本解析

      本文链接:https://www.haomeiwen.com/subject/cnerattx.html