安卓服务Handler 线程代码
时间: 2024-01-11 10:02:07 浏览: 181
Android消息机制
以下是一个简单的安卓服务Handler线程代码:
```java
public class MyService 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) {
// Do some work here
// ...
// Stop the service using the stopSelf() method.
// This will also stop the thread.
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.
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并使用它的Looper为ServiceHandler创建了一个Handler。ServiceHandler实现了handleMessage()方法,在该方法中执行服务的工作,然后调用stopSelf()方法停止服务。在onStartCommand()方法中,使用Handler发送一个消息来启动服务的工作。如果服务被杀死,则返回START_STICKY以便在可用时重新启动服务。最后,在onDestroy()方法中,显示一个Toast以表明服务已完成。
阅读全文