zoukankan      html  css  js  c++  java
  • Service学习笔记

    一 什么是Service

      Service作为安卓四大组件之一,拥有重要的地位。Service和Activity级别相同,只是没有界面,是运行于后台的服务。这个运行“后台”是指不可见,不是指在后台线程中,事实上四大组件都是运行在UI线程中,都不能在各自的生命周期方法中执行耗时操作或者网络请求。

    二 如何使用Service

      Service主要可以分为两类:Local Service、Remote Service。这里以比较常用的Local Service为例,介绍Service的两种使用方法。

      (1)通过Context.startService()启动Service,通过Context.stopService()结束服务。

      新建一个MyService类继承Service,重写onCreate()、onStartCommand()、onDestroy()方法,然后在MainActivity中设置两个按钮,增加其各自点击事件用于启动和停止MyService。

    package com.example.haisun.myapplication3;
    
    import android.app.Service;
    import android.content.Intent;
    import android.os.Binder;
    import android.os.IBinder;
    import android.support.annotation.Nullable;
    import android.util.Log;
    
    /**
     * Created by HaiSun on 2015/10/10.
     */
    public class MyService extends Service {
    
     
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            Log.d("MyService","onCreate executed");
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.d("MyService","onStartCommand executed");
    //        new Thread(new Runnable() {
    //            @Override
    //            public void run() {
    //                //具体逻辑
    //                stopSelf();
    //            }
    //        }).start();
            return super.onStartCommand(intent, flags, startId);
        }
    
        @Override
        public void onDestroy() {
            Log.d("MyService","onDestroy executed");
            super.onDestroy();
        }
    }
    package com.example.haisun.myapplication3;
    
    import android.app.Activity;
    import android.content.ComponentName;
    import android.content.Intent;
    import android.content.ServiceConnection;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.view.View;
    import android.widget.Button;
    
    public class MainActivity extends Activity implements View.OnClickListener{
      
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Button start = (Button)findViewById(R.id.start_service);
            Button stop = (Button)findViewById(R.id.stop_service);
            start.setOnClickListener(this);
            stop.setOnClickListener(this);
            
        }
    
    
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.start_service:
                    Intent intent = new Intent(this,MyService.class);
                    startService(intent);
                    break;
                case R.id.stop_service:
                    Intent stopIntent = new Intent(this,MyService.class);
                    stopService(stopIntent);
                    break;
              
                default:
                    break;
    
            }
    
        }
    
    }

      (2)通过Context.bindService()来绑定一个service,通过Context.unbindService()解绑。

      这里只是在上面的例子上增加了一些内容即可。

      1.在MyService里面新建一个内部类DownBinder继承Binder

    class DownLoadBinder extends Binder {
        public void startDownLoad(){
            Log.d("MyService","startDownLoad executed");
        }
        public int getProgress(){
            Log.d("MyService","getProgress executed");
            return 0;
        }

      2.通过MyService中的onBind方法返回DownBinder的实例,供Activity绑定成功后的回调

    private DownLoadBinder mBinder = new DownLoadBinder();
    
        @Override
        public IBinder onBind(Intent intent) {
            return mBinder;
        }

      3.Activity中绑定,需要新建一个ServiceConnection对象,获得回调的Binder,进而得到DownBinder实例

    private MyService.DownLoadBinder downLoadBinder;
    
        private ServiceConnection connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                downLoadBinder = (MyService.DownLoadBinder)service;
                downLoadBinder.startDownLoad();
                downLoadBinder.getProgress();
            }
            @Override
            public void onServiceDisconnected(ComponentName name) {
            }
        };

      4.类似的,设置两个按钮,增加绑定和解绑的点击事件

        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;

    三 Service的生命周期

      下图为Google官方提供的配图

      

    附:完整的Demo地址:https://github.com/sunhai1992/ServiceTest

  • 相关阅读:
    C#生成图形验证码
    飞刀软件官网正式开通
    IIS7或者IIS7.5部署MVC项目时出现404错误
    office编程必不可少 [转]
    C# 利用 HttpWebRequest 和 HttpWebResponse 模拟登录有验证码的网站
    console方便用法
    24个解决实际问题的ES6代码段
    遍历对象的属性和对象的值
    前端图片处理
    Vue团队代码规范
  • 原文地址:https://www.cnblogs.com/halbertsun/p/4869554.html
Copyright © 2011-2022 走看看