gpt4 book ai didi

android - 在服务中使用 Looper 与使用单独的线程一样吗?

转载 作者:太空宇宙 更新时间:2023-11-03 12:35:48 24 4
gpt4 key购买 nike

在文档 (https://developer.android.com/guide/components/services.html#ExtendingService) 中的这个例子中,我们使用线程的“循环器”,并在服务类中使用它,然后服务将像在单独的线程中一样工作?

public class HelloService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;

// Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
long endTime = System.currentTimeMillis() + 5*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) {
}
}
}
// Stop the service using the startId, so that we don't stop
// the service in the middle of handling another job
stopSelf(msg.arg1);
}
}

@Override
public void onCreate() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();

// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

// For each start request, send a message to start a job and deliver the
// start ID so we know which request we're stopping when we finish the job
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);

// If we get killed, after returning from here, restart
return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}

@Override
public void onDestroy() {
Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}
}

谢谢

最佳答案

线程(HandlerThread)开始于onCreate , 当你调用 thread.start(); ,然后您将获得对 Looper 的引用该线程(每个 Looper 只创建一个 HandlerThread)创建一个 HandlerHandler用于向线程发布消息。 Looper是等待 while(true) 中消息的对象循环。

每次命令发送到Service , ServiceHandlerThread 发送消息通过 Handler .

仔细查看源代码将有助于您更好地理解它的工作原理。有一篇关于 Handler 的优秀帖子s 和 Looper位于 Square Engineering Blog - A journey on the Android Main Thread - Part 1 .

您还可以使用 IntentService以避免实例化您自己的线程。

关于android - 在服务中使用 Looper 与使用单独的线程一样吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19825879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com