Service

作者: MA木易YA | 来源:发表于2019-06-23 12:12 被阅读1次

    分类

    1. Started Service

    启动的Activity与Service无太大联系之间无法进行方法调用

    image.png

    Started Service的生命周期

    image.png

    基本用法

    1. 创建与配置Service

    new -> Service -> Service

    • 通常会重写onCreate()、onStartCommand()、onBind()、onDestroy()几个方法。
    public class MyService extends Service {
        private final static String TAG = "MyService";
    
        public MyService() {
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            // TODO: Return the communication channel to the service.
    //        throw new UnsupportedOperationException("Not yet implemented");
            Log.d(TAG, "********* onBind *********");
            Log.d(TAG, "onBind is called");
            Log.d(TAG, "********* onBind *********");
            return null;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
            Log.d(TAG, "********* onCreate *********");
            Log.d(TAG, "onCreate is called");
            Log.d(TAG, "********* onCreate *********");
            Log.d(TAG, " ");
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.d(TAG, "********* onStart *********");
            Log.d(TAG, "onStart is called");
            Log.d(TAG, "********* onStart *********");
            Log.d(TAG, " ");
            return super.onStartCommand(intent, flags, startId);
    
        }
    
        @Override
        public void onDestroy() {
            Log.d(TAG, "********* onDestory *********");
            Log.d(TAG, "onDestory is called");
            Log.d(TAG, "********* onDestory *********");
            Log.d(TAG, " ");
            super.onDestroy();
        }
    
        @Override
        public boolean onUnbind(Intent intent) {
            Log.d(TAG, "********* onUnbind *********");
            Log.d(TAG, "onUnbind is called");
            Log.d(TAG, "********* onUnbind *********");
            Log.d(TAG, " ");
            return super.onUnbind(intent);
        }
    
        @Override
        public void onRebind(Intent intent) {
            Log.d(TAG, "********* onRebind *********");
            Log.d(TAG, "onRebind is called");
            Log.d(TAG, "********* onRebind *********");
            Log.d(TAG, " ");
            super.onRebind(intent);
        }
    }
    

    配置在AndroidManifest.xml中进行

    • enabled指定是否可以实例化
    • exported指定是否能被其他应用程序组件调用或者交互
    <service
                android:name=".MyService"
                android:enabled="true"
                android:exported="true" />
    

    2. 启动与停止Service

    image.png
    ---启动---
    Intent intent = new Intent(MainActivity.this, MyService.class);
    startService(intent);
    
    ---停止---
    stopService(intent);
    
    

    实例 - 控制背景音乐的播放

    I. 创建MediaPlayer对像并加载播放的音乐文件

       @Override
        public void onCreate() {
            player = MediaPlayer.create(this, R.raw.music);   //创建MediaPlayer对像并加载播放的音乐文件
        }
    

    II. 实现音乐的播放

    @Override
        public int onStartCommand(Intent intent, int flags, int startId) { //实现音乐的播放
            if (!player.isPlaying()) {  //如果没有播放音乐
                player.start();  //播放音乐
                isplay = player.isPlaying();  //当前状态正在播放音乐
            }
            return super.onStartCommand(intent, flags, startId);
        }
    

    III. 停止音乐的播放

    @Override
        public void onDestroy() {  //停止音乐的播放
            player.stop();   //停止音频的播放
            isplay = player.isPlaying();  //当前状态没有播放音乐
            player.release();  //释放资源
            super.onDestroy();
        }
    

    IV. 启动服务与停止服务,实现播放背景音乐与停止播放背景音乐

    ImageButton btn_play = (ImageButton) findViewById(R.id.btn_play);//获取“播放/停止”按钮
    
            //启动服务与停止服务,实现播放背景音乐与停止播放背景音乐
            btn_play.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (MusicService.isplay == false) {   //判断音乐播放的状态
                        startService(new Intent(MainActivity.this, MusicService.class));  //启动服务,从而实现播放背景音乐
                        //更换播放背景音乐图标
                        ((ImageButton) v).setImageDrawable(getResources().getDrawable(R.drawable.play, null));
                    } else {
                        stopService(new Intent(MainActivity.this, MusicService.class));  //停止服务,从而实现停止播放背景音乐
                        //更换停止背景音乐图标
                        ((ImageButton) v).setImageDrawable(getResources().getDrawable(R.drawable.stop, null));
                    }
                }
            });
    

    V. 实现进入界面时,启动背景音乐服务

     @Override
        protected void onStart() {  //实现进入界面时,启动背景音乐服务
            startService(new Intent(MainActivity.this, MusicService.class));  //启动服务,从而实现播放背景音乐
            super.onStart();
        }
    
    image.png

    2. Bound Service

    Activity与Service绑定在一起,一方关闭则另一方也停止

    image.png

    Bound Service生命周期

    image.png

    实现步骤

    服务器端

    1. 创建Service并重写onBind()方法,返回一个IBinder对象,用于和绑定它的组件之间通信
    2. 在Service中创建一个MyBinder的内部类(继承自Binder类)
      客户端
    3. 在Activity中创建ServiceConnection对象,用于获取onBind()返回的IBinder对象
    4. 在Activity的onStart()中调用bindService()绑定Service
    5. 在onStop()方法中调用UNbindService()解除绑定

    实例 - 双色球随机选号

    I. 创建MyBinder内部类并获取服务对象与Service状态

    public class MyBinder extends Binder {  //创建MyBinder内部类并获取服务对象与Service状态
            public BinderService getService() {  //创建获取Service的方法
                return BinderService.this;       //返回当前Service类
            }
        }
    

    II. 创建获取随机号码的方法

    public List getRandomNumber() {  //创建获取随机号码的方法
            List resArr = new ArrayList();   //创建ArrayList数组
            String strNumber="";
            for (int i = 0; i < 7; i++) {  //将随机获取的数字转换为字符串添加到ArrayList数组中
                int number = new Random().nextInt(33) + 1;
                //把生成的随机数格式化为两位的字符串
                if (number<10) {  //在数字1~9前加0
                    strNumber = "0" + String.valueOf(number);
                } else {
                    strNumber=String.valueOf(number);
                }
                resArr.add(strNumber);
            }
            return resArr;  //将数组返回
        }
    

    III. 设置单击事件获取BinderService中的随机数并显示

    @Override
                public void onClick(View v) {
                    List number = binderService.getRandomNumber();  //获取BinderService类中的随机数数组
                    for (int i = 0; i < number.size(); i++) {  //遍历数组并显示
                        TextView tv = (TextView) findViewById(tvid[i]);  //获取文本框组件对象
                        String strNumber = number.get(i).toString();     //将获取的号码转为String类型
                        tv.setText(strNumber);  //显示生成的随机号码
                    }
                }
    

    IV. 设置启动Activity时与后台Service进行绑定

      @Override
        protected void onStart() {  //设置启动Activity时与后台Service进行绑定
            super.onStart();
            Intent intent = new Intent(this, BinderService.class);  //创建启动Service的Intent
            bindService(intent, conn, BIND_AUTO_CREATE);           //绑定指定Service
        }
    

    V. 设置关闭Activity时解除与后台Service的绑定

    @Override
        protected void onStop() {  //设置关闭Activity时解除与后台Service的绑定
            super.onStop();
            unbindService(conn);    //解除绑定Service
        }
    
    image.png

    Intent Service

    Intent Service是Service的子类,它能自动开启线程并停止服务

    image.png

    相关文章

      网友评论

        本文标题:Service

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