Service模板代码 How To Use 注册 manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.sq.net" application service android:name=".NetService"/ /application /manifest 主类 class NetSe
Service模板代码
- How To Use
注册
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.sq.net">
<application >
<service android:name=".NetService"/>
</application>
</manifest>
主类
class NetService : Service() {inner class CustomBinder : Binder() {
val service: NetService
get() = this@NetService
}
//region #生命周期
override fun onCreate() {
super.onCreate()
//逻辑
//init()
}
override fun onBind(intent: Intent?): IBinder = CustomBinder()
override fun onDestroy() {
...
super.onDestroy()
}
//endregion
//region #初始化
...
//endregion
//一些回调放这里
public interface IGetResultCallback {
void setResult(String code);
}
private IGetResultCallback iGetResultCallback;
public void setIGetResultCallback(IGetResultCallback iGetResultCallback) {
this.iGetResultCallback = iGetResultCallback;
}
}
实现
private var mIntent: Intent? = nullprivate var binder: NetService.CustomBinder? = null
private fun initService() {
mIntent = Intent(this, NetService::class.java)
bindService(mIntent, serviceConnection, BIND_AUTO_CREATE)
}
private val serviceConnectionCard = object : ServiceConnection {
override fun onServiceDisconnected(p0: ComponentName?) {}
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
binderCard = service as CardService.CustomBinder
val mService = binderCard!!.service
mService.setIGetResultCallback {
it?.let {
//逻辑
}
}
}
}