zoukankan      html  css  js  c++  java
  • Android 四大组件之Service

    四大组件之Service

    虽然项目中Service用的不算太多 但毕竟作为Android四大组件之一 有必要一探究竟
    Service
        onBind //返回IBinder 通信
        onCreate //第一次创建回调
        onDestroy //关闭之前回调
        onStartCommand //早期版本onStart startService启动时回调
        onUnbind //Service上绑定都断开时回调

        运行Service两种方式
            startService //访问者退出 Service仍然允许
            bindService //访问者退出 Service终止
        生命周期
            startService //onCreate onStartCommand onDestroy
            bindService //onCreate onBind onUnbind onDestroy
        特殊的生命周期
            startService启动 bindService绑定 unbindService解除绑定 bindService再次绑定
            //onCreate onStartCommand onBind onUnbind onRebind
     
    ServiceConnection 监听访问者与Service之间连接情况

    IntentService //可执行耗时任务
        Service与他所在应用属于同一进程 不可执行耗时任务

    Demo1 startService

    public class StartServiceTest extends Activity {
        Button start, stop;
         Intent intent = new Intent();
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            
            initTitle();
            initData();
            initView();
            
        }
        
        public void initTitle() {
    
        }
    
        public void initData() {
            intent.setAction("org.crazyit.service.FIRST_SERVICE");
        }
    
        public void initView() {
            start = (Button) findViewById(R.id.start);
            stop = (Button) findViewById(R.id.stop);
            
            start.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    // 启动 
                    startService(intent);
                }
            });
            stop.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    // 停止 
                    stopService(intent);
                }
            });
        }
    }
    public class FirstService extends Service {
        
        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            Log.i("TAG", "onCreate" + "创建");
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.i("TAG", "onStartCommand" + "启动");
            return START_STICKY;
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            Log.i("TAG", "onDestroy" + "关闭");
        }
    }

    Demo2 bindService

    public class BindServiceTest extends Activity implements View.OnClickListener {
        
        Intent intent = new Intent();
        Button bind, unbind, getServiceStatus;
        BindService.MyBinder binder;
        
        private ServiceConnection conn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                binder = (BindService.MyBinder) service;
            }
    
            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.i("TAG", "onServiceDisconnected" + "断开连接");
            }
        };
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            initTitle();
            initData();
            initView();
    
        }
    
        public void initTitle() {
    
        }
    
        public void initData() {
            intent.setAction("org.crazyit.service.BIND_SERVICE");
        }
    
        public void initView() {
            bind = (Button) findViewById(R.id.bind);
            unbind = (Button) findViewById(R.id.unbind);
            getServiceStatus = (Button) findViewById(R.id.getServiceStatus);
    
            bind.setOnClickListener(this);
            unbind.setOnClickListener(this);
            getServiceStatus.setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.bind:// 绑定
                bindService(intent, conn, Service.BIND_AUTO_CREATE);
    
                break;
            case R.id.unbind:// 解绑
                unbindService(conn);
                break;
            case R.id.getServiceStatus:// 获取状态
                Toast.makeText(BindServiceTest.this, "Serivce的count值为:" + binder.getCount(), Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
            }
        }
    }
    public class BindService extends Service {
    
        private int count;
        private boolean quit;
        private MyBinder binder = new MyBinder();
    
        public class MyBinder extends Binder {
            public int getCount() {
                return count;
            }
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            Log.i("TAG", "onBind" );
            // 返回IBinder对象
            return binder;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            Log.i("TAG", "onCreate" + "创建");
            
            new Thread() {
                @Override
                public void run() {
                    while (!quit) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                        }
                        count++;
                    }
                }
            }.start();
        }
    
        @Override
        public boolean onUnbind(Intent intent) {
            Log.i("TAG", "onUnbind");
            return true;
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            this.quit = true;
            Log.i("TAG", "onDestroy");
        }
    }

    Demo3 特殊生命周期 onRebind

    public class ReBindServiceTest extends Activity {
        BindService.MyBinder binder;
        Intent intent;
        private ServiceConnection conn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                System.out.println("--Service Connected--");
                binder = (BindService.MyBinder) service;
            }
    
            @Override
            public void onServiceDisconnected(ComponentName name) {
                System.out.println("--Service Disconnected--");
            }
        };
    
        public void start(View source) {
            startService(intent);
        }
    
        public void bind(View source) {
            bindService(intent, conn, Service.BIND_AUTO_CREATE);
        }
    
        public void unBind(View source) {
            unbindService(conn);
        }
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            intent = new Intent();
            intent.setAction("org.crazyit.service.BIND_SERVICE");
        }
    }
    public class BindService extends Service {
        private int count;
        private boolean quit;
        private MyBinder binder = new MyBinder();
    
        public class MyBinder extends Binder 
        {
            public int getCount() {
                return count;
            }
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            System.out.println("Service is Binded");
            return binder;
        }
        
        @Override
        public void onCreate() {
            super.onCreate();
            System.out.println("Service is Created");
            new Thread() {
                @Override
                public void run() {
                    while (!quit) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                        }
                        count++;
                    }
                }
            }.start();
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            System.out.println("Service is Started");
            return START_STICKY;
        }
    
        @Override
        public boolean onUnbind(Intent intent) {
            System.out.println("Service is Unbinded");
            return true;
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            this.quit = true;
            System.out.println("Service is Destroyed");
        }
    
        @Override
        public void onRebind(Intent intent) {
            super.onRebind(intent);
            this.quit = true;
            System.out.println("---Service is ReBinded---");
        }
    }

    Demo4 IntentService

    public class IntentServiceTest extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        }
    
        public void startService(View source) {
            Intent intent = new Intent(this, MyService.class);
            startService(intent);
        }
    
        public void startIntentService(View source) {
            Intent intent = new Intent(this, MyIntentService.class);
            startService(intent);
        }
    }
    public class MyIntentService extends IntentService {
        public MyIntentService() {
            super("MyIntentService");
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            long endTime = System.currentTimeMillis() + 20 * 1000;
            System.out.println("onStart");
            while (System.currentTimeMillis() < endTime) {
                synchronized (this) {
                    try {
                        wait(endTime - System.currentTimeMillis());
                    } catch (Exception e) {
                    }
                }
            }
            Log.i("TAG", "onHandleIntent");
        }
    }
    public class MyService extends Service {
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            long endTime = System.currentTimeMillis() + 20 * 1000;
            while (System.currentTimeMillis() < endTime) {
                synchronized (this) {
                    try {
                        wait(endTime - System.currentTimeMillis());
                    } catch (Exception e) {
                    }
                }
            }
            return START_STICKY;
        }
    }

     https://github.com/huanyi0723/ServiceDemo

  • 相关阅读:
    ubuntu无法关机,卡死
    Ubuntu16.04安装8821CE 无线网卡无驱动
    百度Apollo学习(一)
    如何在Virtualbox中对Ubuntu系统根分区扩容
    Ubuntu下安装Google浏览器
    ubuntu下安装Firefox中国版解决Ubuntu与Windows下Firefox账号同步问题(已解决)
    ubuntu 下Visual Studio Code 安装
    百度Apollo搭建步骤(待更新)
    Ubuntu系统下常用的新建、删除、拷贝文件命令
    Ubuntu 16.04下docker ce的安装(待完善)
  • 原文地址:https://www.cnblogs.com/huanyi0723/p/4997585.html
Copyright © 2011-2022 走看看