zoukankan      html  css  js  c++  java
  • 2-AIII--Service服务的绑定

    零、前言

    1.在绑定时调用计时器,间隔打印时间
    2.解绑时解除计时器
    3.在Activity中调用Service的方法

    9414344-164d2e436ff02499.gif
    绑定服务.gif

    一、代码实现

    1.服务类:BindTestService
    public class BindTestService extends Service {
        private static final String TAG = "BindTestService";
        private TimerTask mRunTimerTask;
    
        @Override
        public void onCreate() {
            super.onCreate();
            Log.e(TAG, "onCreate: ");
        }
        
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.e(TAG, "onStartCommand: ");
            return super.onStartCommand(intent, flags, startId);
        }
    
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            Log.e(TAG, "onBind: ");
    
            //使用计时器间隔打印时间
            Timer timer = new Timer();
            mRunTimerTask = new TimerTask() {
                @Override
                public void run() {
                    System.out.println("scheduledExecutionTime:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                            .format(scheduledExecutionTime()));
                }
            };
            //延迟3秒,2秒周期执行
            timer.schedule(mRunTimerTask, 3000L,2 * 1000L);
            Log.e(TAG, "计时器已开启");
            return new MyBinder();
        }
    
        @Override
        public boolean onUnbind(Intent intent) {
            Log.e(TAG, "onUnbind: 成功解绑");
            mRunTimerTask.cancel();
            Log.e(TAG, "计时器已取消");
            return super.onUnbind(intent);
        }
    }
    
    2.MyBinder类
    /**
     * 作者:张风捷特烈
     * 时间:2018/8/25 0025:11:09
     * 邮箱:1981462002@qq.com
     * 说明:Service的onBind方法返回一个IBinder对象
     * 该对象在是Service与Activity的连接人,在Activity可以获取该对象
     */
    public class MyBinder extends Binder {
        public void methodInService() {
            System.out.println("我是服务里的方法");
        }
    }
    
    3.注册:app/src/main/AndroidManifest.xml
    <service android:name=".bind.BindTestService"/>
    
    4.Activity页:
    public class BindActivity extends AppCompatActivity {
    
        @BindView(R.id.id_btn_bind)
        Button mIdBtnBind;
        @BindView(R.id.id_btn_unbind)
        Button mIdBtnUnbind;
        private ServiceConnection mConn;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_bind);
            ButterKnife.bind(this);
        }
    
        @OnClick({R.id.id_btn_bind, R.id.id_btn_unbind})
        public void onViewClicked(View view) {
            switch (view.getId()) {
                case R.id.id_btn_bind:
                    // [0]启动服务
                    Intent intent = new Intent(this, BindTestService.class);
                    startService(intent);
                    //[1]创建连接对象
                    mConn = new ServiceConnection() {
                        // 当连接成功时候调用
                        @Override
                        public void onServiceConnected(ComponentName name, IBinder service) {
                            MyBinder binder = (MyBinder) service;
                            binder.methodInService();
                        }
                        // 当连接断开时候调用
                        @Override
                        public void onServiceDisconnected(ComponentName name) {
    
                        }
                    };
                    //[2]绑定服务启动
                    bindService(intent, mConn, BIND_AUTO_CREATE);
                    break;
                case R.id.id_btn_unbind:
                    //[3]解绑服务启动
                        unbindService(mConn);
                    break;
            }
        }
    }
    

    开启服务时:onCreate==>onStartCommand
    绑定时:onBind
    解绑时:onUnbind

    附录布局:
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".BindActivity">
    
        <Button
            android:id="@+id/id_btn_bind"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:text="绑定服务"
            app:layout_constraintEnd_toStartOf="@+id/id_btn_unbind"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>
    
        <Button
            android:id="@+id/id_btn_unbind"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="解绑服务"
            app:layout_constraintStart_toEndOf="@+id/id_btn_bind"
            app:layout_constraintTop_toTopOf="@+id/id_btn_bind"/>
    
    </android.support.constraint.ConstraintLayout>
    

    后记、

    1.声明:

    [1]本文由张风捷特烈原创,转载请注明
    [2]欢迎广大编程爱好者共同交流
    [3]个人能力有限,如有不正之处欢迎大家批评指证,必定虚心改正
    [4]你的喜欢与支持将是我最大的动力

    2.连接传送门:

    更多安卓技术欢迎访问:安卓技术栈
    我的github地址:欢迎star
    简书首发,腾讯云+社区同步更新
    张风捷特烈个人网站,编程笔记请访问:http://www.toly1994.com

    3.联系我

    QQ:1981462002
    邮箱:1981462002@qq.com
    微信:zdl1994328

    4.欢迎关注我的微信公众号,最新精彩文章,及时送达:
    9414344-c474349cd3bd4b82.jpg
    公众号.jpg
  • 相关阅读:
    第四章例4-5
    第四章例4-4
    修改oracle 客户端PL/SQL 的路径问题
    解决div float后,父div高度无法自适应的问题
    include与jsp:include与s:action与s:include与iframe用法汇总
    解决js中onMouseOut事件冒泡的问题
    strut2配置action class 问题
    html块级元素与行内元素
    Tomcat 启动不了的问题
    oracle远程导入导出
  • 原文地址:https://www.cnblogs.com/toly-top/p/9781943.html
Copyright © 2011-2022 走看看