Service详解

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值