2-AIII--Service服务的绑定

作者: e4e52c116681 | 来源:发表于2018-08-25 12:02 被阅读6次

    零、前言

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

    绑定服务.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>
    

    本文由张风捷特烈原创,转载请注明
    更多安卓技术欢迎访问:https://www.jianshu.com/c/004f3fe34c94
    张风捷特烈个人网站,编程笔记请访问:http://www.toly1994.com
    你的喜欢与支持将是我最大的动力

    相关文章

      网友评论

        本文标题:2-AIII--Service服务的绑定

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