学习android service记录
来源:互联网 发布:云计算怎么实现 编辑:程序博客网 时间:2024/06/06 17:26
看了一会书,总结下安卓service,加深下印象
MyService 类:
package com.example.com.binderservicedemo;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.util.Log;public class MyService extends Service { private binder Mybinder = new binder(); public MyService() { } @Override public IBinder onBind(Intent intent) { Log.i("test", "绑定服务"); return Mybinder; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("test", "服务启动"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); Log.i("test", "服务关闭"); } @Override public boolean onUnbind(Intent intent) { Log.i("test", "解除绑定"); return super.onUnbind(intent); } public void ServiceMethod() { Log.i("test", "我是服务里面的方法"); } public class binder extends Binder{ public void CallServiceMethod(){ ServiceMethod(); } }}
开启服务:服务一直在后台运行,会调MyService里的onStartCommand()方法,这种方式不能与MyService 通讯,但是服务一直在后台允许,除非服务被停止。
Intent intent = new Intent(Activity.this,MyService.class);startService(intent);
关闭服务:MyService里的onDestroy()方法会被调用
stopService(intent);
绑定服务:这个方式可以与MyService通讯,可以调用里面的方法,例如 调用 ServiceMethod()方法,bindService()方法会,调用服务里的onCreate()(第一次把绑定时)->onBind() 并不会调用 onStartCommand()方法。
Intent intent = new Intent(Activity.this,MyService.class);serviceconnection con = new serviceconnection();bindService(intent, con, BIND_AUTO_CREATE);public class serviceconnection implements ServiceConnection{ @Override public void onServiceConnected(ComponentName name, IBinder service) { MyService.binder mybinder = (MyService.binder) service; mybinder.CallServiceMethod(); } @Override public void onServiceDisconnected(ComponentName name) { } }
解除绑定:调用Activity类的unbindService()方法,可以解除绑定。
unbindService(con);
混合调用:用startserivce 开启服务,bindservice 绑定服务,unbindservice 解除绑定,stopservice 关闭服务。服务会一直在后台运行,这样也能调用服务里面的方法。
区别:startService 开启服务,服务一直在后台运行,跟开启者没有关系,bind的方式开启服务,绑定服务,调用者挂了,服务也会跟着挂掉,开启者可以调用服务里面的方法。
1 0
- 学习android service记录
- android service 学习(上)
- android service 学习(下)
- Android Service学习
- Android Service学习笔记
- android service 学习
- android service 学习(下)
- android service 学习(上)
- android service 学习(下)
- Android学习之Service
- android service学习列表
- Android学习之Service
- android service 学习(上)
- android service 学习(下)
- Android中的Service学习
- Android Service学习笔记
- Android学习--Service初步
- android service 学习(上)
- 第一天:代码入门、HTML语法基础及文档类标签
- ios静态库与动态库的区别
- jq与JS点击显示隐藏二级菜单的几种方法
- 白话Spring(基础篇)---helloworld
- 1090 Higest Price in Supply Chain
- 学习android service记录
- Linux 初始化之 Systemd机制简介
- Swift 笔记(四)
- UML图与机房收费系统实例
- 使用Memory Analyzer tool(MAT)分析内存泄漏(二)
- java.lang.ThreadLocal实现原理和源码分析
- 四叉树空间索引原理及其实现
- ios 开发中 动态库 与静态库的区别
- LA-3942 (字典树模板)