zoukankan      html  css  js  c++  java
  • 使用scala trait 自动 绑定service 到 Activity 或其他service

    得益于 scala trait 的链式操作

    假设你有一个UtilService 内容如下

    class UtilService extends Service {
      utilService =>               // UtilService.this 别名 
       
      def doSomething(xx: Any) = {
    	//  your code 
      }
    			
      def onBind(p1: Intent) = new UtilServiceBinder
    
      class UtilServiceBinder extends Binder {
        def getService = utilService
      }
    
    }


    添加一个 base trait MixinUtilServiceBase

    protected trait MixinUtilServiceBase {
    
      lazy val utilService = {
        assert(utilServiceHolder != null); utilServiceHolder
      }    // utilService 将混入(mixin) 到 activity 或 service
      private var utilServiceHolder: UtilService = null
      protected val utilServiceConnection = new ServiceConnection {
        def onServiceConnected(className: ComponentName, binder: IBinder) {
          utilServiceHolder = binder.asInstanceOf[UtilService#UtilServiceBinder].getService
        }
    
        def onServiceDisconnected(className: ComponentName) {
    	// do something 
        }
      }
    
    }


    添加一个trait ActivityMixinUtilService

    trait ActivityMixinUtilService extends Activity with MixinUtilServiceBase {
      context =>
    
      abstract override def onCreate(savedInstanceState: Bundle) {
        super.onCreate(savedInstanceState)
        bindService(new Intent(context, classOf[UtilService]), utilServiceConnection, Context.BIND_AUTO_CREATE)
      }
    
      abstract override def onDestroy() {
        unbindService(utilServiceConnection)
        super.onDestroy()
      }
    }



    现在你可以在你自己的Activity 内使用 ActivityMixinUtilService trait 了, 想下面这样

    class Main extends Activity with ActivityMixinUtilService {
      context =>
      
      def doSome() {
        utilService.doSomething() // 现在 utilService 混合(mixin) 到了main Activity  
      }
    }


    extends Activity 可以省略掉

    class Main extends ActivityMixinUtilService 


    像Activity一样 ServiceMixinUtilService

    trait ServiceMixinUtilService extends Service with MixinUtilServiceBase {
      context =>
    
      abstract override def onCreate() {
        super.onCreate()
        bindService(new Intent(context, classOf[UtilService]), utilServiceConnection, Context.BIND_AUTO_CREATE)
      }
    
      abstract override def onDestroy() {
        unbindService(utilServiceConnection)
        super.onDestroy()
      }
    }



    确保添加UtilService 到AndroidManifest.xml

    <service android:name=".services.UtilService"/>

  • 相关阅读:
    实现多项式相加或相减
    Node.js对28181的管理
    mssql版本对应的版本号
    Asp.net移除Server, XPoweredBy, 和XAspNetVersion头
    开源的图表控制,winform
    .NET 4.0里异常处理的新机制
    asp.net windows 域账号登录
    SpringCloud2.0 Zuul 网关路由 基础教程(十)
    SpringCloud2.0 Hystrix Dashboard 断路器指标看板 基础教程(八)
    SpringCloud2.0 Turbine 断路器集群监控 基础教程(九)
  • 原文地址:https://www.cnblogs.com/ricardo/p/2275028.html
Copyright © 2011-2022 走看看