与AsyncTask的服务 [英] Service with AsyncTask

查看:92
本文介绍了与AsyncTask的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说它不是件好事,在服务的异步任务。

真的有必要为的AsyncTask 或只是 onStartCommand()

我不知道,因为我有一个服务的AsyncTask 由报警启动。它启动服务不止一次;它应该只是一个启动一次。

难道这是什么原因呢?

编辑:

这是我如何设置报警。

 字符串报警= Context.ALARM_SERVICE;    AlarmManager AM =(AlarmManager)getSystemService(报警);    意图Aintent =新意图(REFRESH_THIS);
    的PendingIntent圆周率= PendingIntent.getBroadcast(在此,0,Aintent,0);
    台历挂历= Calendar.getInstance();
    calendar.add(Calendar.HOUR_OF_DAY,9);
    calendar.add(Calendar.MINUTE,0);
    calendar.add(Calendar.SECOND,0);
    calendar.add(Calendar.MILLISECOND,0);    am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,PI);


解决方案

如果你在一个服务有一个长期运行的操作,可以考虑使用的 IntentService ,它将启动和管理一个后台线程你。而且它具有自动完成时,它自行关闭额外的好处。你可以达到与类似的东西的AsyncTask ,但一个 IntentService 将做正确的事情。

至于您的其他问题,该服务是启动多次无关与的AsyncTask 。如果您运行的报警多次,将推出你的服务的多个实例。还有就是,据我所知,确实没有办法自动进行单独服务。你可以检查它是否启动之前运行,或者设置preferences标志(容易出错),但preferred方法是有短暂的服务发布的每一个你需要做的事情的时间,完成后把自己关。 IntentService 非常适合这种模式。

I have heard that it isnt good to have an async task in a service.

Is it really necessary for an AsyncTask or just onStartCommand()?

I am wondering because I have a Service with an AsyncTask that is launched by an alarm. And it launches the Service more than once; it's only supposed to launch once.

Could this be the reason?

EDIT:

Here is how i set up the alarm.

    String alarm = Context.ALARM_SERVICE;

    AlarmManager am = (AlarmManager)getSystemService(alarm);

    Intent Aintent = new Intent("REFRESH_THIS");
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, Aintent, 0);
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.HOUR_OF_DAY, 9);
    calendar.add(Calendar.MINUTE, 0);
    calendar.add(Calendar.SECOND, 0);
    calendar.add(Calendar.MILLISECOND, 0);

    am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() , AlarmManager.INTERVAL_DAY, pi);

解决方案

If you have a long-running operation in a service, consider using IntentService, it will launch and manage a background thread for you. And it has the added benefit that it shuts itself down when finished automatically. You could achieve something similar with an AsyncTask, but an IntentService will do the right thing.

As for your other question, the service being launched multiple times has nothing to do with the AsyncTask. If your alarm runs multiple times, it will launch multiple instances of your service. There is, AFAIK, really no way to make a singleton service automatically. You could check if it's running before launching, or set a preferences flag (error prone), but the preferred way is to have short-lived services launched every time you need to do something, and shut themselves when done. IntentService fits this pattern nicely.

这篇关于与AsyncTask的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆