Reputation: 540
The goal is to run and load a second activity in the background when the user is still in the first activity. The second activity is pretty heavy and it takes time to load; so I need to show the second activity after it's loaded and ready.
public void onButtonClick(View view){
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("user_input", userInput.getText().toString());
startActivity(intent);
}
Can I modify the above code in order to load the second activity in the background?
Upvotes: 1
Views: 7617
Reputation: 121
Alternative option: Show a loading screen when user clicks button. This will give the user visual feedback while your second activity is being created...so your app doesn't seem like it's lagging.
public void onButtonClick(View view){
setContentView(R.layout.loading_screen);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("user_input", userInput.getText().toString());
startActivity(intent);
}
Upvotes: 0
Reputation: 293
You can't start activity from background because it is intended to run from Android Main thread.Instead of loading activity from background you can do your heavy work those are not related to UI in background thread you can use AsyncTask, Handler or even IntentService for the same and then get result on Main thread and update your UI. Try to avoid nested layout as much as possible and do not process any heavy task in main thread.
Upvotes: 1
Reputation: 69689
if you have heavy task in you second activity than move your heavy task into the background service or thread.
you can use AsyncTask for background work
AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
Android AsyncTask is an abstract class provided by Android which gives us the liberty to perform heavy tasks in the background and keep the UI thread light thus making the application more responsive.
example of AsyncTask
Upvotes: 2
Reputation: 228
For that you want to use Services
Step-1 Create class file which extend Service like below
public class TestService extends Service {
@Override
public void onCreate() {
// cancel if already existed
}
}
Step-2 Place your service class inside AndroidManifest.xml
<service android:name=".TestService" />
Step-3 Use Intent for call service like this
Intent intent = new Intent(this,TestService.class);
startActivity(intent);
Upvotes: 1