美文网首页
Service知识

Service知识

作者: eagleif | 来源:发表于2018-08-10 11:00 被阅读12次
    1. Service的两种启动模式
    • startService()
    Intent intent = new Intent(this, MyService.class);
    startService(intent);
    
    • bindService
            Intent  intent = new Intent(this, MyService.class);
            startService(intent);
            ServiceConnection conn = new ServiceConnection() {
                @Override
                public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                    Log.d("TAG", "onServiceConnected");
                    MyService.MyBinder myBinder = (MyService.MyBinder) iBinder;
                    service = myBinder.getService();
                    isBind = true;
                }
    
                @Override
                public void onServiceDisconnected(ComponentName componentName) {
                    Log.d("TAG", "onServiceDisconnected");
                }
            };
            bindService(intent, conn, Service.BIND_AUTO_CREATE);
    
    1. 自定义Service
    public class MyService extends Service {
        public MyService() {
        }
    
        @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");
            return super.onStartCommand(intent, flags, startId);
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            Log.d("TAG", "MyService---->onBind");
            return new MyBinder();
        }
    
        @Override
        public boolean onUnbind(Intent intent) {
            Log.d("TAG","MyService---->onUnbind");
            return super.onUnbind(intent);
        }
    
        public class MyBinder extends Binder {
            public MyService getService() {
                return MyService.this;
            }
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            Log.d("TAG", "MyService---->onDestroy");
        }
    }
    
    
    既startService又bindService

    从中可以看出onCreate只执行一次,onCreate不管startService或者bindService多少次都只执行一次onCreate()

    1. startService和bindService的区别
      startService没有和Activity绑定,Activity销毁了之后service还是能够运行;bindService启动时Service和Activity进行了绑定,如果Activity销毁了,那么Service会自动进行解绑和调用Service的onDestroy()方法
    2. IntentService
    • IntentService的定义
    package com.example.ulabor.testproject;
    
    import android.app.IntentService;
    import android.content.Intent;
    import android.content.Context;
    import android.util.Log;
    
    import java.util.concurrent.Executors;
    
    /**
     * An {@link IntentService} subclass for handling asynchronous task requests in
     * a service on a separate handler thread.
     * <p>
     * helper methods.
     */
    public class MyIntentService extends IntentService {
        private static final String ACTION_FOO = "com.example.ulabor.testproject.action.FOO";
        private static final String ACTION_BAZ = "com.example.ulabor.testproject.action.BAZ";
    
        private static final String EXTRA_PARAM1 = "com.example.ulabor.testproject.extra.PARAM1";
        private static final String EXTRA_PARAM2 = "com.example.ulabor.testproject.extra.PARAM2";
    
        public MyIntentService() {
            super("MyIntentService");
        }
    
        /**
         * Starts this service to perform action Foo with the given parameters. If
         * the service is already performing a task this action will be queued.
         *
         * @see IntentService
         */
        public static void startActionFoo(Context context, String param1, String param2) {
            Intent intent = new Intent(context, MyIntentService.class);
            intent.setAction(ACTION_FOO);
            intent.putExtra(EXTRA_PARAM1, param1);
            intent.putExtra(EXTRA_PARAM2, param2);
            context.startService(intent);
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            Log.d("TAG", "onDestroy");
        }
    
    
        /**
         * Starts this service to perform action Baz with the given parameters. If
         * the service is already performing a task this action will be queued.
         *
         * @see IntentService
         */
        public static void startActionBaz(Context context, String param1, String param2) {
            Intent intent = new Intent(context, MyIntentService.class);
            intent.setAction(ACTION_BAZ);
            intent.putExtra(EXTRA_PARAM1, param1);
            intent.putExtra(EXTRA_PARAM2, param2);
            context.startService(intent);
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            if (intent != null) {
                final String action = intent.getAction();
                if (ACTION_FOO.equals(action)) {
                    final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                    final String param2 = intent.getStringExtra(EXTRA_PARAM2);
                    handleActionFoo(param1, param2);
                } else if (ACTION_BAZ.equals(action)) {
                    final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                    final String param2 = intent.getStringExtra(EXTRA_PARAM2);
                    handleActionBaz(param1, param2);
                }
            }
        }
    
        /**
         * Handle action Foo in the provided background thread with the provided
         * parameters.
         */
        private void handleActionFoo(String param1, String param2) {
            try {
                try {
                    for (int i = 0; i < 10; i++) {
                        Thread.sleep(1000);
                        Log.d("TAG", "i---》" + i);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /**
         * Handle action Baz in the provided background thread with the provided
         * parameters.
         */
        private void handleActionBaz(String param1, String param2) {
            // TODO: Handle action Baz
            throw new UnsupportedOperationException("Not yet implemented");
        }
    }
    
    

    最主要的就是onHandleIntent()方法对传入的参数进行处理;从中可以看出在handleActionFoo方法中,调用 Thread.sleep(1000);来进行耗时操作模拟,Service自己循环了10次之后自动销毁。能够在onHandleIntent()方法中进行耗时操作。因为Service的onCreate()和onStartCommand方法是在主线程运行的,所以不能够在这里进行耗时操作。IntentService是窜行操作,不是并行操作,也就是任务是一步一步完成的,如下图

    执行如下代码:

            for (int j = 0; j < 2; j++) {
                MyIntentService.startActionFoo(this, "a", "b");
            }
    

    运行结果

    image.png

    相关文章

      网友评论

          本文标题:Service知识

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