Service

来源:互联网 发布:js中target属性 编辑:程序博客网 时间:2024/05/16 07:37

//启动服务

Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);

//停止服务

stopService(intent);


     *   通过startService(intent) 启动时掉用
     * 参数1:表示启动的组件传递过来的intent对象
     * flags:标记
     * startId:表示请求的标识
     * 返回值:
        START_STICKY:粘性service 表示服务 kill系统会尝试创建新的服务创建成功后  继续调用此方法    intent  为null
        START_NOT_STICKY:非粘性service 如果被kill掉  只能通过startService()  方法启动
        START_CONTINUATION_MASK:和START_STICKY  类似 不能保证 重新创建服务  执行onStartCommand
        START_REDELIVER_INTENT:重传Intent。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉; 系统会自动重启该服务,并将Intent的值传入
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_NOT_STICKY;
    }


public class MyServiceConn implements ServiceConnection{
        /**
         * 表示服务链接成功后回调的方法
         * 参数1:组件的名称
         * 参数2:链接后onBind()返回的值
         */
        public void onServiceConnected(ComponentName name, IBinder service) {
            MyBinder binder = (MyBinder) service;
            MyService myService = binder.getService();
        }



     * 通过 binderService()绑定服务  启动后回调的方法
     */
    @Override
    public IBinder onBind(Intent arg0) {
        Log.i(Tag, "==onBind==");
        return new MyBinder();
    }
     *如果向访问getRandom()方法  不能直接方法  service对象不能直接去new  需要去传递过去
     *通过  IBinder 向外暴漏 服务对象
    public class MyBinder extends Binder{
        //向外暴漏service对象
        public MyService getService(){
            return MyService.this;  
        }
    }


0 0