大佬教程收集整理的这篇文章主要介绍了android – 在服务中使用Looper与使用单独的线程相同?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
在文档(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();
}
}
谢谢
解决方法:
线程(HandlerThread)在onCreate中启动,当你调用thread.start();然后你得到对该线程的Looper的引用(每个HandlerThread只创建一个Looper)来创建一个Handler并使用Handler将消息发布到线程. Looper是在while(true)循环中等待消息的对象.
每次向服务发送命令时,服务都会通过处理程序向HandlerThread发送消息.
仔细查看源代码将有助于您更好地了解它的工作原理.在Square Engineering Blog – A journey on the Android Main Thread – Part 1有一篇关于Handlers and Loopers的优秀帖子.
您还可以使用IntentService来避免实例化自己的线程.
以上是大佬教程为你收集整理的android – 在服务中使用Looper与使用单独的线程相同?全部内容,希望文章能够帮你解决android – 在服务中使用Looper与使用单独的线程相同?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。