服务与AsyncTask的 [英] Service and AsyncTask
问题描述
我如何运行,并在AsyncTask的服务,这样,当我做我的工作在服务的UI不会冻结?
今天我实现了一个非常基本的服务:
How can i run and AsyncTask in a Service so that the UI does not freeze when i do my work in a service? Today i implemented a very basic service:
public class ImageSendEmailService extends Service {
private NotificationManager notificationManager = null;
private Notification notification = null;
@Override
public void onCreate() {
super.onCreate();
this.notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
for (int i = 0; i <= 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String notificationText = String.valueOf((int) (100 * i / 10)) + " %";
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("Progress");
builder.setContentText(notificationText);
builder.setTicker("Notification!");
builder.setWhen(System.currentTimeMillis());
builder.setDefaults(Notification.DEFAULT_SOUND);
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.ic_launcher);
this.notification = builder.build();
this.notificationManager.notify(0, notification);
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
可是当我执行用户界面是冻结。
but the ui is freezing while i perform that.
推荐答案
您可以运行的AsyncTask
在服务
就像你在一个活动运行
或片段
。为什么会有什么区别呢?
You can run an AsyncTask
in a Service
just like you would run it in an Activity
or Fragment
. Why would there be any difference?
ExampleTask task = new ExampleTask();
task.execute();
但你也可以继承 IntentService
而不是服务
!一个 IntentService
自动处理每个意图
在一个单独的发
。这样,你可以不阻塞UI执行中的服务
的工作,你不必应付 AsyncTasks
或主题
!
But you can also subclass IntentService
instead of Service
! An IntentService
automatically handles each Intent
in a separate Thread
. That way you can perform work in the Service
without blocking the UI and you don't have to deal with AsyncTasks
or Threads
!
public class ImageSendEmailService extends IntentService {
@Override
protected void onHandleIntent(Intent intent) {
// Do your work here!
}
}
您可以找到 IntentService
的 这里 。
You can find the documentation of IntentService
here.
顺便说一句:无论你正在尝试与有视频下载()
是一个非常糟糕的主意。切勿使用视频下载()
这样。使用定时
或处理程序
,而不是!
As an aside: Whatever you are trying to there with Thread.sleep()
is a really bad idea. Never use Thread.sleep()
like that. Use a Timer
or Handler
instead!
这篇关于服务与AsyncTask的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!