Service的理解和用法

来源:互联网 发布:淘宝信誉分怎么看 编辑:程序博客网 时间:2024/05/31 19:08

Servic是可以在后台运行的服务,一个程序只会有一个服务的实例。

startService(),stopService()的用法和startActivity()一样。

后台执行指定的服务代码:

package com.example.administrator.app1;import android.app.Service;import android.content.Intent;import android.os.IBinder;public class MyService extends Service {public MyService() {}private  Boolean serviceRunning = false;//判断service是否开始执行@Overridepublic IBinder onBind(Intent intent) {    // TODO: Return the communication channel to the service.    throw new UnsupportedOperationException("Not yet implemented");}@Override//在startService执行之后,都会执行到onStartCommandpublic int onStartCommand(Intent intent, int flags, int startId) {    return super.onStartCommand(intent, flags, startId);}@Override//oncreate只会执行一次,服务只有一个实例public void onCreate() {    super.onCreate();    serviceRunning = true;    new Thread(){        @Override        public void run() {            super.run();            while(serviceRunning) {//循环执行程序                System.out.println("程序正在运行。。。");                try {                    sleep(1000);//休眠1秒                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }    }.start();}@Overridepublic void onDestroy() {    super.onDestroy();    serviceRunning = false;}

}

activity和service进行绑定的时候也会执行oncreate和onstartcommand

0 0