用户定义的方法和Service类中的onStartCommand()

时间:2015-11-21 11:32:31

标签: android service

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

为了实现我所遵循的有界服务。

在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()内运行的线程具有相同的权限。

0 个答案:

没有答案