正如我在在线教程中读到的那样,服务是持久的对象,而这些对象用于长期任务 . 例如 . Map ,在后台播放音乐等 . 我还阅读了一些关于服务的内容 .

为了实现有界服务我做了以下 .

在Service类的onStartCommand()中,我说了一个帖子 . 在run()方法内部,我添加了一个包含10次迭代的循环 . 每次迭代都会休眠5000毫秒,并将currentState(int变量)增加1 .

showThreadStateToClient()有一个方法 . 它将currentState返回给MainActivity . 以下是Service类的两个代码片段 . 请告诉我他们之间有什么区别?

代码段1 :(使用onStartCommand)

public class MyService extends Service {

IBinder iBinder = new LocalBinder();
static int currentState=0;
int totalIterations=10;


@Override
public IBinder onBind(Intent intent) {
    return iBinder;
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            while (currentState <= totalIterations) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ++currentState;
            }
        }
    };

    Thread t = new Thread(runnable);
    t.start();

    return Service.START_STICKY;
}


public class LocalBinder extends Binder
{
    public MyService getService()
    {
        return MyService.this;
    }
}


public int showThreadStateToClient()
{
    return currentState;
}
}

代码片段2 :(没有onStartCommand())

public class MyService extends Service {

IBinder iBinder = new LocalBinder();
static int currentState=0;
int totalIterations=10;


@Override
public IBinder onBind(Intent intent) {
    return iBinder;
}



public class LocalBinder extends Binder
{
    public MyService getService()
    {
        return MyService.this;
    }
}

/*this method is called form MainActivity after binding the service.*/
public void startThread()
{
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            while (currentState <= totalIterations) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ++currentState;
            }
        }
    };

    Thread t = new Thread(runnable);
    t.start();

}


public int showThreadStateToClient()
{
    return currentState;
}
}

代码片段2中运行的线程是否与代码片段1中onStartCommand()内运行的线程具有相同的权限 .