Service详解
来源:互联网 发布:生产仿真软件 编辑:程序博客网 时间:2024/06/10 21:19
Service生命周期:
如图:
代码测试:
继承Swevice:
public class Myservice extends Service { @Override public void onCreate() { super.onCreate(); Log.i("woyaokk", "====================onCreate=============="); } @Nullable @Override public IBinder onBind(Intent intent) { Log.i("woyaokk","====================onBind=============="); return new MyBinder(); } @Override public void onRebind(Intent intent) { super.onRebind(intent); Log.i("woyaokk", "====================onBind=============="); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("woyaokk","====================onStartCommand=============="); return super.onStartCommand(intent, flags, startId); } @Override public boolean onUnbind(Intent intent) { Log.i("woyaokk","====================onUnbind=============="); return super.onUnbind(intent); } @Override public void onDestroy() { Log.i("woyaokk","====================onDestroy=============="); super.onDestroy(); } class MyBinder extends Binder { /** * 获取Service的方法 */ public Myservice getService(){ return Myservice.this; } }}
注册:
<service android:name=".Myservice"></service>
启动:
Intent intent=new Intent(MainActivity.this,Myservice.class); MainActivity.this.startService(intent);
停止:
Intent intent=new Intent(MainActivity.this,Myservice.class); MainActivity.this.stopService(intent);
当使用两次启动方法,一次停止方法,返回:
由此可知:通过startService方法启动Service则会调用OnCreate方法和OnStartCommand方法,并且多次调用startService方法只会调用由此OnCreate,但会掉用多次onStartCommand,销毁时调用onDestory
绑定:
ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { // 建立连接 Myservice.MyBinder binder = (Myservice.MyBinder) service; myService = binder.getService(); } @Override public void onServiceDisconnected(ComponentName name) { // 连接断开 } };
Intent intent=new Intent(MainActivity.this,Myservice.class); bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);解绑:
unbindService(serviceConnection);
声明周期:
由此可知:通过启动通过绑定启动Service调用onCreate和onBind方法,解绑时调用onUnbind和onDestory方法;
注意:
Service和Thread本质上没有半毛钱关系,Service同样运行在主线程中,所以一样不能执行耗时操作,如果需要执行耗时操作,可以开启异步线程或者继承IntentService
0 0
- service 详解
- Service详解
- service详解
- Service 详解
- Service详解
- Service详解
- service详解
- service详解
- service详解
- Service 详解
- service详解
- Service 详解
- Service详解
- Service详解
- Service详解
- Service详解
- Service详解
- Service详解
- 《Windows核心编程》之“堆”
- android BitmapFacty.Options的用法
- 解析器把 XML 转换为 JavaScript 可存取的对象
- MySQL行级锁、表级锁、页级锁详细介绍
- C#基础教程之IComparable用法,实现List<T>.sort()排序
- Service详解
- 【python】__name__ = '__main__' 的作用
- Python 学习进阶
- Hibernate报错prefix
- Route add 命令举例
- leetcode_c++:树:Invert Binary Tree(226 )
- Android的JNI开发涉及的char和string之间的互相转换
- ElasticSearch Java 增删改查
- Android 实现部分文字高亮的三种方法