Service

来源:互联网 发布:fgo花嫁尼禄宝具本数据 编辑:程序博客网 时间:2024/06/03 05:59


 Service(服务)是能够在后谈执行长时间运行操作并且不提供用户见面的应用程序组件。


 Service分类

 Started(启动): startService(serviceIntent);/stopService(serviceIntent);服务需要停止自身
 
 Bind(绑定):bindService(serviceIntent,this, Context.BIND_AUTO_CREATE);/unbindService(this);
                BIndService会随着绑定的Activity的destroy而destroy。

Service类

public class MyService extends Service {    public MyService() {    }    @Override    public IBinder onBind(Intent intent) {        // TODO: Return the communication channel to the service.        System.out.println("onBind");        return  myServiceBinder;    }    private  final MyServiceBinder myServiceBinder=new MyServiceBinder();    public class  MyServiceBinder extends Binder{        //取得服务实例        public MyService getService(){            return  MyService.this;        }    }    @Override    public void  onCreate(){        startTimer();        System.out.println("onCreate");        super.onCreate();    }    @Override    public void onDestroy() {        stopTimer();        System.out.println("onDestroy");        super.onDestroy();    }    private Timer timer=null;    private TimerTask timerTask=null;    private int i=0;    public int getCurrentNum(){        return i;    }    public void startTimer(){        if(timer==null){            timer=new Timer();            timerTask =new TimerTask() {                @Override                public void run() {                    i++;                    System.out.print(i);                }            };            timer.schedule(timerTask,1000,1);        }    }    public void stopTimer(){        if(timer!=null){            timerTask.cancel();            timer.cancel();            timerTask=null;            timer=null;        }    }


0 0
原创粉丝点击