开发者

When to use a service in Android

开发者 https://www.devze.com 2023-01-02 17:03 出处:网络
I have a class that fetches data in response to button presses in the main activity. Unfortunately, I keep running into problems because this class is not an Activity or a Service. For example, withou

I have a class that fetches data in response to button presses in the main activity. Unfortunately, I keep running into problems because this class is not an Activity or a Service. For example, without a Context I cannot translate a resource id into a string:

getString(R.string.example_string); // Doesn't work

Should I make this class into a Service and have the main Activity stop the class when it is closed? Should I pass the Context from the Activity into this class like this?

MyClass c = new MyClass(this);

Or is there some better way to handle this problem?

This issue also comes up when I try to send a Toast from this class.

Update: Erich and Janusz pointed me in the direction of the AsyncTask class which works perfectly, except that it creates a new thre开发者_如何学Cad and never kills that thread. This means that ever time the user presses a button, another thread is added and the old ones just sit there.


If you have a background action whose lifecycle is decoupled from your activity, I would use a Service. In that case, the Service will have its own Context, so you won't need to pass it in. If, however, you need to perform a background action in response to a UI event (and optionally post the results back into the UI thread), I would recommend you use an AsyncTask.


I agree with Erich, if you only have a something small like posting a change to a web backend or loading something from the phone memory to show it on screen use a Async Task. If the task will exit very "quick" (some seconds) you can make an anonymous class inside your activity. This will enable you to use a implicit reference to the outer activity inside the task and you can get your context from there.

If the task is running for a longer time you can pass down the context. If you are passing down the context try to not pass this from the activity use this.getApplicationContext() this will minimize the number of references to your activity and enable the garbage collector to clean up properly.

0

精彩评论

暂无评论...
验证码 换一张
取 消