前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >2-AIII--Service服务的绑定

2-AIII--Service服务的绑定

作者头像
张风捷特烈
发布2018-09-26 16:44:57
3840
发布2018-09-26 16:44:57
举报
零、前言

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

绑定服务.gif

一、代码实现
1.服务类:BindTestService
代码语言:javascript
复制
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类
代码语言:javascript
复制
/**
 * 作者:张风捷特烈
 * 时间: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
代码语言:javascript
复制
<service android:name=".bind.BindTestService"/>
4.Activity页:
代码语言:javascript
复制
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

附录布局:
代码语言:javascript
复制
<?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 你的喜欢与支持将是我最大的动力

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.08.25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 零、前言
  • 一、代码实现
    • 1.服务类:BindTestService
      • 2.MyBinder类
        • 3.注册:app/src/main/AndroidManifest.xml
          • 4.Activity页:
            • 附录布局:
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档