Amit
Amit

Reputation: 3990

run task when activity starts

How can i run an async task when an activity starts? there are about 7 activities, and i need to run the async task, every time one starts, and cancel it when the activity dies.

public MyApp extends Application{
    public void onCreate(){super.onCreate();}
}

One obvious way would be to put it in onCreate of every activity, but that is not very DRY. Is there any other way? If I put it in the Application onCreate, then I am unable to execute, Toast.makeText, since I guess no activity is available...

Upvotes: 0

Views: 187

Answers (2)

r-hold
r-hold

Reputation: 1120

First of all your Code uses the onCreate-Method of the Application Class. In general you should avoid doing stuff here, but use your Activity class. You should be aware of the difference between Application and Activity and should have a good understandig of the Activity-Lifecycle because this are Android fundamentals.

For common tasks to all Activities you should create your own probably abstract BaseActivity , implement common/shared stuff there and inherit from this class. But keep in mind, that several Activities might be instantiated at the same time, so the right handlers to use really depend on what kind of behavior you want to achieve. Again: Understand how the android life-cycle works and how activities are managed or you might run into some trouble.

Upvotes: 1

Ramseys
Ramseys

Reputation: 431

Have you considered creating a service to host your task, and binding it in each of your activities' OnCreate ?

Upvotes: 0

Related Questions