在文档(https://developer.android.com/guide/components/services.html#ExtendingService)的这个例子中,我们使用了一个线程的“looper”,我们在Service类中使用它,然后Service就像它在一个单独的一样工作线程?
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();
}
}
由于
答案 0 :(得分:6)
线程(HandlerThread
)在onCreate
中启动,当您调用thread.start();
时,您会获得对该线程的Looper
的引用(仅一个{每Looper
}创建{1}}以创建HandlerThread
,Handler
用于向线程发布消息。 Handler
是等待Looper
循环中的消息的对象。
每次向while(true)
发送命令时,Service
都会通过Service
向HandlerThread
发送消息。
仔细查看源代码将有助于您更好地了解它的工作原理。在Square Engineering Blog - A journey on the Android Main Thread - Part 1有一篇关于Handler
和Handler
s的优秀帖子。
您还可以使用IntentService来避免实例化自己的线程。