zoukankan      html  css  js  c++  java
  • Android Service基本知识总结(一)

    一、简介

    Service是Android系统的后台服务组件,适用于开发无界面、长时间运行的应用功能
    Service特点如下:
    没有用户界面
    不会轻易被Android系统终止
    在系统资源恢复后Service也将自动恢复
    运行状态
    可用于进程间通信

    二、生命周期

    创建MyService extends Service

    清单文件中注册:

    <service android:name=".MyService"/>

    两种启动方式:

    1.startService(Intent service) 

    1.调用startService()启动MyService,

      Intent startIntent=new Intent(this,MyService.class);
      startService(startIntent);
    2.多次调用startService并不会多次执行MySercice中的onCreate()方法,会多次执行onStartCommand()方法
    3.调用stopService()销毁MyService
      Intent stopIntent=new Intent(this,MyService.class);
      stopService(stopIntent);

    2.bindService(Intent service, ServiceConnection conn,int flags)

    1.调用startService()启动MyService,
    Intent startIntent=new Intent(this,MyService.class);
    startService(startIntent);
    2.多次调用startService并不会多次执行MySercice中的onCreate()方法,会多次执行onStartCommand()方法
    3.调用stopService()销毁MyService
    Intent stopIntent=new Intent(this,MyService.class);
    stopService(stopIntent);


    bindService(Intent service, ServiceConnection conn,int flags)
    1)在MyService中创建并声明MyBinder ,MyBinder中封装可能会执行的任务
      private MyBinder mBinder=new MyBinder();

      

    class MyBinder extends Binder {
            public void downLoad(){
                Log.e(TAG, "downLoad: " );
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // 执行具体的下载任务
                    }
                }).start();
            }
    
        }

    2)声明ServiceConnection,并在onServiceConnected中获取MyService.MyBinder

      

     private ServiceConnection connection=new ServiceConnection() {
    
            //activity和service创建连接时调用
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                Log.e(TAG, "onServiceConnected: " );
                //这里可以获取myBinder  通过myBinder里的方法 和service交互
                myBinder= (MyService.MyBinder) service;
                myBinder.downLoad();
            }
            //unbind()调用时不会调用此方法  不是解除关联的时候调用,而是发生异常时调用的
            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.e(TAG, "onServiceDisconnected: " );
    
            }
        };

    3)在MyService的onBind()方法中返回mBinder;

      

    @Override
        public IBinder onBind(Intent intent) {
            Log.e(TAG, "onBind: " );
            return mBinder;
        }

    4)调用onBind()绑定Service和Activity,启动MyService

      

    Intent bindIntent = new Intent(this, MyService.class);
                    bindService(bindIntent, connection, BIND_AUTO_CREATE);

    5)调用 unbindService(connection) 销毁MyService

    unbindService(connection);

    在activty中拿到mBinder后,就可以进行activity和service之间的交互了。

    若一个Service先通过startService启动 再通过bindService启动。单独stopService()或者unbindService()都不能销毁Service,先stopService(),再unBindService()销毁MyService。

    6)注意事项

      1.Service是运行在主线程中的,不能直接执行耗时操作。可以在Service中创建一个子线程进行耗时操作

      2.既然要在Service里也创建一个子线程,那为什么不直接在Activity里创建呢?

      这是因为Activity很难对Thread进行控制,当Activity被销毁之后,就没有任何其它的办法可以再重新获取到之前创建的子线程的实例。

    而且在一个Activity中创建的子线程,另一个Activity无法对其进行操作。但是Service就不同了,所有的Activity都可以与Service进行关联,
    然后可以很方便地操作其中的方法,即使Activity被销毁了,之后只要重新与Service建立关联,就又能够获取到原有的Service中Binder的实例。

      3.标准的Service常用格式:

      

    @Override  
    public int onStartCommand(Intent intent, int flags, int startId) {  
        new Thread(new Runnable() {  
            @Override  
            public void run() {  
                // 开始执行后台任务  
            }  
        }).start();  
        return super.onStartCommand(intent, flags, startId);  
    }  
      
    class MyBinder extends Binder {  
      
        public void startDownload() {  
            new Thread(new Runnable() {  
                @Override  
                public void run() {  
                    // 执行具体的下载任务  
                }  
            }).start();  
        }  
      
    }  

     三、代码

     

      1.MyService

    public class MyService extends Service {
    
        private String TAG="333";
        private MyBinder mBinder=new MyBinder();
        @Override
        public void onCreate() {
            super.onCreate();
            Log.e(TAG, "onCreate: " );
        }
    
        @Override
        public int onStartCommand(Intent intent,  int flags, int startId) {
            Log.e(TAG, "onStartCommand: " );
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // 开始执行后台任务
                }
            }).start();
            return super.onStartCommand(intent, flags, startId);
        }
    
    
    
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            Log.e(TAG, "onBind: " );
            return mBinder;
        }
        @Override
        public void onDestroy() {
            Log.e(TAG, "onDestroy: " );
            super.onDestroy();
        }
    
    
    
        class MyBinder extends Binder {
            public void downLoad(){
                Log.e(TAG, "downLoad: " );
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // 执行具体的下载任务
                    }
                }).start();
            }
    
        }
    }

    2.activity

    public class MainActivity extends AppCompatActivity {
    
        private String TAG="333";
        private MyService.MyBinder myBinder;
        private ServiceConnection connection=new ServiceConnection() {
    
            //activity和service创建连接时调用
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                Log.e(TAG, "onServiceConnected: " );
                //这里可以获取myBinder  通过myBinder里的方法 和service交互
                myBinder= (MyService.MyBinder) service;
                myBinder.downLoad();
            }
            //unbind()调用时不会调用此方法  不是解除关联的时候调用,而是发生异常时调用的
            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.e(TAG, "onServiceDisconnected: " );
    
            }
        };
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        public void click(View v){
            switch (v.getId()){
                case R.id.button://startService
                    Intent startIntent=new Intent(this,MyService.class);
                    startService(startIntent);
                    break;
                case R.id.button2://stopService
                    Intent stopIntent=new Intent(this,MyService.class);
                    stopService(stopIntent);
                    break;
                case R.id.button3:
                    Intent bindIntent = new Intent(this, MyService.class);
                    bindService(bindIntent, connection, BIND_AUTO_CREATE);
    
                    break;
                case R.id.button4:
                    unbindService(connection);
                    break;
            }
        }
    }

    参考:

        

       

  • 相关阅读:
    LintCode "Maximum Gap"
    LintCode "Wood Cut"
    LintCode "Expression Evaluation"
    LintCode "Find Peak Element II"
    LintCode "Remove Node in Binary Search Tree"
    LintCode "Delete Digits"
    LintCode "Binary Representation"
    LeetCode "Game of Life"
    LintCode "Coins in a Line"
    LintCode "Word Break"
  • 原文地址:https://www.cnblogs.com/wangjiaghe/p/7069574.html
Copyright © 2011-2022 走看看