从运行或AsyncTask的主题服务? [英] Running a Service from ASyncTask or Thread?

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

问题描述

我有一个Android应用程序,它使用一个服务时,应用程序是开放的,不断在视图更新一个TextView。它使用它发送意图的广播接收机它更新。通过该应用程序的性质,服务需要不断地应用已经结束,也/视图不见了运行。显然,这不是明智的做法在这种情况下,运行在主线程上的服务,因为这将霸占了太多,最终迫使关闭和崩溃的应用程序。那么,什么是保持该服务运行的最好方法?一个AsyncTask的?一个单独的线程?我将如何去这样做呢?

I have an Android app which uses a service to continuously update a textview in the view when the app is open. It updates it using a broadcast receiver which it sends intents to. By the nature of the app, the service needs to continue to run even after the app has exited/the view is gone. Obviously it's not wise to run the service on the main thread in this case, as that will hog up too much and eventually force close and crash the app. So what is the best way to keep this service running? An ASyncTask? A separate thread? How would I go about doing this? I tried it with an ASyncTask like this:

private class MyTask extends AsyncTask {

    @Override
    protected Object doInBackground(Object... objects) {
        return getActivity().getApplicationContext().startService(intent);
    }

    @Override
    protected void onCancelled() {
        getActivity().getApplicationContext().stopService(intent);
        super.onCancelled();
    }
}

哦,是的,我使用getActivity()。getApplicationContext(),因为这是一个片段内。

Oh yeah, I'm using getActivity().getApplicationContext() because this is inside of a fragment.

所以这个工作正常;我叫MyTask.execute()时,我要开始它和MyTask.cancel(真)时,我想阻止它,但我pretty肯定我没有使用它,它应该如何使用。我甚至不知道我应该为execute方法(?)的参数使用。它似乎并不是刚开始在它的服务,没有别的最好的办法,当然这将更好地工作,只使用一个线程?什么是去了解这一点,为了为它工作它的目的是方式的正确方法?顺便说一句,尽管这比在主线程上运行它长得多的工作,但它还是几个小时之后崩溃。

So this works fine; I call MyTask.execute() when I want to start it and MyTask.cancel(true) when I want to stop it, but I'm pretty sure I'm not using it how it should be used. I don't even know what I'm supposed to use as the argument for the execute method (??). And it doesn't seem to be the best idea to just start a service in it and nothing else, surely that would work better using just a thread? What's the proper way to go about this, in order for it to work the way it was intended to? By the way, although this does work for much longer than running it on the main thread, it does still crash after several hours.

推荐答案

更​​新:我想我想通了。我是什么,我想我需要做的路要走,显然对这种服务我有我只需要在前台(因此使用startForeground()方法)运行它。这似乎是现在的工作。对不起!

Update: I think I figured it out. I was way off in what I thought I needed to do, apparently for the kind of service I had I only needed to run it in the foreground (so using the startForeground() method). It seems to be working now. Sorry!

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

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