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

    创建一个服务,并与活动绑定

    作为安卓四大组件之一的服务,毫无例外也要在manifast中进行注册

    • 新建服务类继承于Service,并覆盖onBind( )方法,用于与活动绑定
    public class MySevice extends Service {
    
        //创建DownloadBinder对象mBinder
        private DownloadBinder mBinder = new DownloadBinder();
    
        //创建DownloadBinder类,实现服务中需要等待活动指示来执行的方法
        class DownloadBinder extends Binder {
      //必须是pubilc修饰的方法
    public int getProcess() { return 0; } } @Nullable @Override //返回DownloadBinder对象mBinder public IBinder onBind(Intent intent) { return mBinder; } @Override //创建服务时执行 public void onCreate() { Toast.makeText(this, "服务创建成功", Toast.LENGTH_LONG).show(); super.onCreate(); } @Override //启动服务时执行 public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, "服务启动成功", Toast.LENGTH_LONG).show(); return super.onStartCommand(intent, flags, startId); } @Override //关闭服务时执行 public void onDestroy() { Toast.makeText(this, "服务关闭成功", Toast.LENGTH_LONG).show(); super.onDestroy(); } }
    • 在Activity中找到传递过来的mBinder对象
        private MySevice.DownloadBinder mDownloadBinder;
        //创建匿名内部类ServiceConnection(),重写方法onServiceConnected(),onServiceDisconnected()分别在绑定和取消绑定时调用
        private ServiceConnection mConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                //向下转型,找到mDownloadBinder对象,并调用对象中的public方法
                mDownloadBinder = (MySevice.DownloadBinder) service;
                mDownloadBinder.getProcess();
            }
    
            @Override
            public void onServiceDisconnected(ComponentName name) {
    
            }
        };
    • 绑定服务与活动
        Intent thread_bind_service = new Intent(ThreadDemoActivity.this, MySevice.class);
        bindService(thread_bind_service,mConnection,BIND_AUTO_CREATE);
        /* bindService()方法接收三个参数,第一个参数就是刚刚构建出的 Intent 对象,
        *  第二个参数是前面创建出的 ServiceConnection 的实例,
        *  第三个参数则是一个标志位,这里传入 BIND_AUTO_CREATE 表示在活动和服务进行绑定后自动创建服务
        */
    •  解除绑定
      unbindService(mConnection);
  • 相关阅读:
    APIO2019游记
    ZJOI2019赛季回顾
    「HNOI 2019」白兔之舞
    LOJ #6539 奇妙数论题
    BZOJ4314 倍数?倍数!
    伯努利数学习笔记&&Luogu P3711 仓鼠的数学题
    BZOJ 5093[Lydsy1711月赛]图的价值 线性做法
    AtCoder Grand Contest 030题解
    Codeforces Round #542 (Div. 1) 题解
    Codeforces Round #541 (Div. 2)题解
  • 原文地址:https://www.cnblogs.com/cenzhongman/p/6399178.html
Copyright © 2011-2022 走看看