Service详解

来源:互联网 发布:生产仿真软件 编辑:程序博客网 时间:2024/06/10 21:19

Service生命周期:

如图:

111111

代码测试:

继承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);

当使用两次启动方法,一次停止方法,返回:

2222222222
由此可知:通过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);

声明周期:

33333333

由此可知:通过启动通过绑定启动Service调用onCreate和onBind方法,解绑时调用onUnbind和onDestory方法;


注意:

Service和Thread本质上没有半毛钱关系,Service同样运行在主线程中,所以一样不能执行耗时操作,如果需要执行耗时操作,可以开启异步线程或者继承IntentService




0 0
原创粉丝点击