I want to make a test app, that when called, execute a few lines of code, and then exit automatically. I want all these done within onCreate().
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("onCreate()");
try {
initSocket(); //connect to server
} catch (IOException e) {
e.printStackTrace();
}
new Thread(new AudioRecordThread()).start();
}
The problem is, how can I exit the app in onCreate()? I tried "this.finish()" but didn't work.
Any one can help?
EDIT
I agree that the problem may be caused by thread. Will post my answer when solved.
I think the Problem is your AudioRecordThread which shares the same Process with your App. You could definetly call this.finish() inside onCreate (done this often, never had problems), but that doesn't mean neccesarily that your AudioRecordThread gets killed the same time as your Activity. So without further Information about your Thread, and if it should stay alive on finish of your Activity I cannot give you any advise. If You want that Thread to be alive, after your Activity finishes, a Service is the way to go.
try
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("onCreate()");
try {
initSocket(); //connect to server
} catch (IOException e) {
e.printStackTrace();
}
new Thread(new AudioRecordThread()).start();
finish();
}
Perhaps what you are trying to do is a service?
Have a look here: http://developer.android.com/reference/android/app/Service.html
try this one
finish is working in onCreate() & onResume().. there is another problem in your code
#Override
protected void onResume()
{
super.onResume();
finish();
}
You can use an AsynTask in your activity, juste put this class in the Same file of your activity
=> In onPostExecute() methode you will test if your handling is finished to close your activity.
class MyAsynTask extends AsyncTask<Void, Integer, Boolean> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
// Init your variables, in my case it's my Progress Bar
myprogress = new ProgressDialog(mcontext);
myprogress.setTitle("Update");
myprogress.setMessage("Update running ....");
myprogress.show();
}
#Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
boolean test = false;
int j = 0;
for (int i = 0; i < 50; i++) {
j = i + 10;
publishProgress(i);
// Your implemention code to connect to the server
if (i == 49)
test = true;
}
return test;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
myprogress.setProgress(values[0]);
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (myprogress.isShowing())
myprogress.dismiss();
if (result){
Toast.makeText(mcontext, "I Finished",Toast.LENGTH_SHORT).show();
yourActivity.this.finish();
}
}
}
Related
This question already has answers here:
Execute AsyncTask several times
(5 answers)
Closed 9 years ago.
I am new to Android and am now working on the counter thing using the AsyncTask.
So the thing is I'm having one button and with that button OnClickListener.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean check;
check=check_button_status();
if(check==true){
rec_forward_task.execute();
}
else
{
rec_forward_task.cancel();
}
}
});
So here the rec_forward_task is the class that extends the AsyncTask. The AsyncTask class is here.
//
private class CounterForwardTask extends AsyncTask<Void, Integer, Integer>
{
TextView record_counter_display;
int rec_counter,count;
int last_value;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
record_counter_display=(TextView) findViewById(R.id.rec_voice_counter);
rec_counter=0;
record_counter_display.setText(String.valueOf(rec_counter));
count=0;
}
public void cancel() {
// TODO Auto-generated method stub
onCancelled();
}
#Override
protected Integer doInBackground(Void... params) {
// TODO Auto-generated method stub
while(rec_status)
{
publishProgress(count);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
last_value=count;
count=count+1;
}
return 1;
}
#Override
protected void onCancelled() {
// TODO Auto-generated method stub
record_counter_display.setText(String.valueOf(0));
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
record_counter_display.setText(String.valueOf(count));
}
});
}
#Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
record_counter_display.setText(String.valueOf(last_value));
}
}
I'm making the object for that class in the oncreate method only so now the question is.
When user press first time the counter is starting and displaying in the textview and again pressing that same button the counter progress is stop due to oncancel method is called.but if user again pressing the same button app force closing and exception that u can't start the task which is already started.so what will be the way to perform this kind of operation.Thanks for any reply.
if(check==true){
rec_forward_task = new CounterForwardTask();
rec_forward_task.execute();
}
else
{
rec_forward_task.cancel();
}
Instead of instantiating AsyncTask in onCreate instaniate it when you need to start it. Hope this helps.
You will have to create a new AsyncTask object.
AsyncTasks are meant to run only once.
Check this answer.
The async task is designed to run only once. But you can run it by creating new instances of the asynctask class. See the answer of Passionate Androiden
Threading rules
There are a few threading rules that must be followed for this class to work properly:
The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.
The task instance must be created on the UI thread.
execute(Params...) must be invoked on the UI thread.
Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.
The task can be executed only once (an exception will be thrown if a second execution is attempted.)
pls findout more in Developer site
In my acivity, i need to run two background service.
main background service:
class loadingTask extends AsyncTask<Void, Void,Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pd = ProgressDialog.show(context, "", "Chargement en cours..", true, false);
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
}
...
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
getxml = Util.CallWebService("");
return null;
}
}
Second background service.
class mloadingTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
SAXHelper sh = null;
try {
sh = new SAXHelper(urls[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
sh.parseContent("");
return "";
}
protected void onPostExecute(String s) {
pd.dismiss();
}
}
In my onCreate() method I want to call the first background and when it finished loading the second background service starts. Part of my background service is as follows.
AsyncTask<Void, Void,Void> loadTask = new loadingTask().execute();
if(loadTask.getStatus()==AsyncTask.Status.FINISHED){
new mloadingTask().execute(getxml);
System.out.println("getxml: "+getxml);
}
However the second background service doesn't seem to start. i am not getting the a print also. I think I miss a step or android doesn't allow more than one background service in the same activity. A help please.
AsyncTask<Void, Void,Void> loadTask = new loadingTask().execute();
if(loadTask.getStatus()==AsyncTask.Status.FINISHED){
new mloadingTask().execute(getxml);
System.out.println("getxml: "+getxml);
}
there is a 99% chance that the if() block will never pass.
You first execute the first asyncTask named loadTask and RIGHT after check if it finished.
Small chance that it actually finishes by then.
The easy approach:
Use only one async task. You want to finish asyncTask 1 and then fire asyncTask 2, its exactly the same as having only one asyncTask doing both operations.
class loadingTask extends AsyncTask<Void, Void,Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pd = ProgressDialog.show(context, "", "Chargement en cours..", true, false);
super.onPreExecute();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
}
...
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
getxml = Util.CallWebService("");
SAXHelper sh = null;
try {
sh = new SAXHelper(urls[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
sh.parseContent("");
return null;
}
}
The difficult approach:
How I solve this kind of thing is(our situation is different, but it should do)
Create an interface, with one method. for example:
public interface OnDataChangedListner {
void dataChanged(Class listener);
}
Then somewhere (i use my repository classes)
write a method to add and remove entires to a list of OnDataChangedListener interfaces
private ArrayList<OnDataChangedListner> mOnDataChangedListners;
public void addOnDataChangedListner(OnDataChangedListner onDataChangedListner){
synchronized (mOnDataChangedListners){
mOnDataChangedListners.add(onDataChangedListner);
}
}
public void removeOnDataChangedListner(OnDataChangedListner onyDataChangedListner){
if (mOnDataChangedListners != null){
synchronized (mOnDataChangedListners){
for (Iterator<OnDataChangedListner> it = mOnDataChangedListners.iterator(); it.hasNext();) {
OnDataChangedListner listener = it.next();
if (listener .equals(onDataChangedListner))
it.remove();
}
}
}
}
This might be overkill. But this example should help you with updating the UI while your tasks are running. A free extra! :))
With the above code in place, create an onDataChanged() method in the same class where u defined the add and remove listener methods.
In that code call a handler
// Need handler for callbacks to the UI thread
final static Handler mHandler = new Handler();
// Create runnable for posting
final Runnable mNotifyDataChanged = new Runnable() {
public void run() {
if (mOnDataChangedListners != null){
synchronized (mOnDataChangedListners){
for (Iterator<OnDataChangedListner> it = mOnDataChangedListners.iterator(); it.hasNext();) {
OnDataChangedListner listener = it.next();
if (listener != null)
listener.dataChanged(this.getClass());
else
it.remove();
}
}
}
}
};
/**
* will notify registerred delegates on the main (UI) thread
*/
public void notifyDataChanged(){
mHandler.post(mNotifyDataChanged);
}
Ok, so I ended up giving out an entire sample.
Where you place this code is upto you. But when you call notifyDataChanged() it will fire the handler, which in turn will loop trough all current registered listeners for this class
then in turn it will call the listeners datachanged method.
To make this all work, all you have to do is have a class implement the interface
call addOnDataChangedListener(this);
and implement the method provided in the interface.
Note that this is deffinetly not the easiest way to do things.
I don't know what the easiest way to do what you want is. I never have been in that situation before.
but you can execute the second task in the implemented method. Should work..
AsyncTask is Asynchronous as its name suggest. You need to call your 2nd AsyncTask in onPostExecute of your 1st AsyncTask
OR
Loop and wait till AsyncTask is finished in your activity, but it may take more time and you can get Application Not Responding message.
As soon as you call execute() method, control comes to next statement which loadTask.getStatus(). As task is just started, loadTask.getStatus() will not return FINISH and your 2nd task is never getting executed.
In my application when i click on Button it sometimes shows the progressdialog and sometimes not show the progressdialog on click of button.
Asynchronous Task code is:
public class LoadData extends AsyncTask<Void, Void, Void>
{
ProgressDialog pd;
#Override
protected void onPreExecute()
{
pd = ProgressDialog.show(MainActivity.this, "", "Loading...");
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
LoadActivities(); // function to load data from url
}
});
return null;
}
#Override
protected void onPostExecute(Void unused)
{
pd.dismiss();
}
}
and on button click event call this as:
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new LoadMoreData().execute(null);
}
});
the wrong think you are doing is that in doInBackground you use runOnUiThreade . just remove that from your code . It solves your problem.
never use any thread in doInBackground.
Why you have taken run method again in doInBackground, doInBackground method performs computation on a background thread, so no need to take runOnUiThread
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
LoadActivities(); // function to load data from url
}
});
Just write
protected Boolean doInBackground(final String... args) {
try {
LoadActivities();
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
And also change new LoadMoreData().execute(); don't write null
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new LoadMoreData().execute();
}});
Nirali's answer seems correct, just to make further explaination and some edits.
Progress Dialog will be shown by the time doInBackground method returns value. and in your code it just create another thread, and completes execution, so to display progress dialog by the time LoadActivities exectues, execute this statement in the same thread doInBackground executes, so change to following:
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
MainActivity.this.runOnUiThread(new Runnable() {
LoadActivities(); // function to load data from url
return null;
}
I have my asyncTask run when the activity first starts, then if network connectivity is not available then i have a refresh button that tries to run the asyncTask to try again. But i get a debug error saying this..
07-29 18:14:21.290: ERROR/AndroidRuntime(9080): FATAL EXCEPTION: main
07-29 18:14:21.290: ERROR/AndroidRuntime(9080): java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once)
07-29 18:14:21.290: ERROR/AndroidRuntime(9080): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:541)
07-29 18:14:21.290: ERROR/AndroidRuntime(9080): at android.os.AsyncTask.execute(AsyncTask.java:499)
07-29 18:14:21.290: ERROR/AndroidRuntime(9080): at com.fttech.gameIT.MainMenu$1.onClick(MainMenu.java:90)
Is there anyway to run this twice?
Just create another instance and execute it.
Just like threads, AsyncTasks can't be reused. You have to create a new instance every time you want to run one.
You can never execute a thread again, not in Java, not in any other language, once the thread is done with the run() method, you cannot restart it, which is why you are getting the IllegalStateException.
You can however still call the methods on that thread but they will run on the thread that is calling them NOT on a different thread. Therefore you will have to create a new one.
You cannot run same instance of an AsyncTask more than once.
Let's assume you have an AsyncTask named MyAsyncTaks and you intend to do something like this,
MyAsyncTask myAsyncTask = new MyAsyncTaks();
myAsyncTask.execute(); // Works as expected
.
.
.
.
myAsyncTask.execute(); // This will throw you exception
The reason for this is, a thread once finishes its 'run' method, cannot be assigned another task. Here, on the first invocation of execute(), your AsyncTask started running and
after doing its job, the thread comes out of run. Naturally, next invocation of execute() will throw you exception.
The simplest way to run this more than once is to create a new instance of MyAsyncTaks and call execute on that.
MyAsyncTask myAsyncTask = new MyAsyncTaks();
myAsyncTask.execute(); // Works as expected
.
.
.
MyAsyncTask myAsyncTask2 = new MyAsyncTaks();
myAsyncTask2.execute(); // Works as expected
Though its not needed to be mentioned here, one must be aware that post Android SDK version Honeycomb, if your run more than one AsyncTask at once, they actually run
sequentially. If you want to run them parallally, use executeOnExecutor instead.
Just make a new call like new asyncTask().execute(); You must create a new object to restart that task.
I just create the asynctask then create a runnable that creates new instances of the asynctask. Then you can submit your runnable over and over again to the handler.
class MyAsyncTask extends AsyncTask<String, Void, String>{ ...}
Runnable myRunner = new Runnable(){
public void run() {
new MyAsyncTask ().execute(...);
}};
myHandler.post(myRunner);
This solved my problem:
public class MainActivity extends AnimationActivity {
MyAsyncTasks asyncTasks = new MyAsyncTasks();
#BindView(R.id.refresh_btn)
Button refreshBtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUnbinder(ButterKnife.bind(this)); // ButterKnife usage
syncTasks(); // run asyncTasks on activity start
refreshBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
syncTasks(); // run asyncTasks on button click
}
});
}
private void syncTasks() {
try {
if (asyncTasks.getStatus() != AsyncTask.Status.RUNNING){ // check if asyncTasks is running
asyncTasks.cancel(true); // asyncTasks not running => cancel it
asyncTasks = new MyAsyncTasks(); // reset task
asyncTasks.execute(); // execute new task (the same task)
}
} catch (Exception e) {
e.printStackTrace();
Log.e("MainActivity_TSK", "Error: "+e.toString());
}
}
}
You can do it like this :
private MyAsyncTask createAsyncTask(){
if (myAsyncTask == null){
return myAsyncTask = new MyAsyncTask();
}
myAsyncTask.cancel(true);
return myAsyncTask = new MyAsyncTask();
}
and then you can use it :
createAsyncTask().execute();
this make a new instance of your background task everytime.
Async tsk only run once as the Exceptions says the task has already been executed..
So you just have to make a new instance of async and then call .execute();
in order to run it again .. thank you
I created an Arraylist of type ProgressUpdater(Name of class which extends AsyncTask) and added the instances into it(in the onClick of a button). So you can execute and cancel these task when needed.
public class MainActivity extends Activity {
ProgressBar progress;
ProgressUpdater task;
ArrayList<ProgressUpdater> pu = new ArrayList<MainActivity.ProgressUpdater>();
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = (ProgressBar) findViewById(R.id.progress);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn:
task = new ProgressUpdater();
pu.add(task);
count++;
pu.get(count - 1).execute(0);
System.out.println("task" + task);
// task.execute(10);
break;
case R.id.btnCancel:
if (count >= 0) {
pu.get(count - 1).cancel(true);
pu.remove(count - 1);
count--;
}
// task.cancel(true);
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class ProgressUpdater extends AsyncTask<Integer, Integer, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progress = (ProgressBar) findViewById(R.id.progress);
progress.setMax(100);
}
#Override
protected Void doInBackground(Integer... params) {
// TODO Auto-generated method stub
int start = params[0];
for (int i = start; i <= 100; i++) {
try {
boolean cancelled = isCancelled();
if (!cancelled) {
publishProgress(i);
SystemClock.sleep(100);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.v("Progress", "Finished");
}
#Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
progress.setMax(0);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
progress.setProgress(values[0]);
}
}
}
in your MainActivity you can put so this:
LeoAsyncTask leoAsyncTaskGeneric;
public void onClick_AsyncTask(View view) {
LeoAsyncTask leoAsyncTaskInner = new LeoAsyncTask();
leoAsyncTaskInner.execute();
leoAsyncTaskGeneric=leoAsyncTaskInner;
}
/**if you create a space in memory of your AsyncTask class as a generic, then you can create an instance of that same class within the onClick method, and there the equals, so every time you press onClick you will be using a new instance of the Class AsyncTask, it will not give you problems
*/
You could cancel your asyncTask when you press the button and then execute it again.
Inside OnClic method:
asyncTask.cancel();
AsyncTask asyncTask = new AsyncTask();
asyncTask.execute();
#coder_For_Life22 I think am late for the answer ,anyway you can do like
#Override
protected void onPostExecute(Void a) {
myAsyncTask=new MyAsyncTask();
}
in order to start a new AsyncTask after execution :)
I have a button in one page and when I click on that button I
am able to go another activity through Intent(), but onbuttonclick()
in which activity I am going in that activity data in spinner
coming from server means on button click
I load that data on spinner from server.so it takes times for moving my button click activity
to other activity so I want to show progress bar when my button is clicked
and untill data is not coming from server...how to achieve this..and I want to show progress bar
on buttonclick page means on my first activity when I click the button.
My code of of on button click is given below.
cuurentloc.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Intent i = new Intent(MainMenu.this, currentlocmap.class);
startActivity(i);
}
});
Actually I know asynchronous task but using this I will be able to show progress bar on 2nd activity, I want to show it on my first activity until data is not loaded in second activity, so I want progree bar above the button on first activity, and when data is loaded on second activity it moves to second.
You need to use AsyncTask as the way I am guiding here.
Create Async Task in first activity. On button click event call that AsyncTask. In background do loading data from server. and onPostExecute start second activity
cuurentloc.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
new ProgressTask(MyClassName.class).execute(null);
}
});
Async Task
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
List<Message> titles;
private ListActivity activity;
//private List<Message> messages;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
Intent i = new Intent(MainMenu.this, currentlocmap.class);
startActivity(i);
}
protected Boolean doInBackground(final String... args) {
try{
//load data from server
} catch (Exception e){
Log.e("tag", "error", e);
return false;
}
}
}
}
Thanks
Deepak
have a look at this code
package com.exercise.AndroidBackgroundThread;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class AndroidBackgroundThread extends Activity {
Thread backgroundThread;
TextView myText;
boolean myTextOn = true;
boolean running = false;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
if (myTextOn){
myTextOn = false;
myText.setVisibility(View.GONE);
}
else{
myTextOn = true;
myText.setVisibility(View.VISIBLE);
}
}
};
void setRunning(boolean b){
running = b;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myText = (TextView)findViewById(R.id.mytext);
Toast.makeText(this, "onCreate()", Toast.LENGTH_LONG).show();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(this, "onStart()", Toast.LENGTH_LONG).show();
backgroundThread = new Thread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
while(running){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.sendMessage(handler.obtainMessage());
}
}
});
setRunning(true);
backgroundThread.start();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
boolean retry = true;
setRunning(false);
while(retry){
try {
backgroundThread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Toast.makeText(this, "onStop()", Toast.LENGTH_LONG).show();
}
}
and for more detail look at this guide http://tech-aamir.blogspot.in/2012/06/how-to-make-progress-bar-when.html
Best of luck
aamirkhan i.
To build on the first answer, since you are familiar with AsyncTask. You can have the AsyncTask perform the work to retrieve whatever data you'll need in your first activity. And during that process, you display your progress bar. Once the AsyncTask completes, you remove the progress bar, put your data in a bundle (by calling putExtras), and send it off with your intent to start the 2nd Activity.
You can use the ProgressBar or ProgressDialog in the currentlocmap class.
Use AsyncTask class for that and when the data is fetched, set the layout using setContentView() and dismiss the ProgressDialog.
Refer to these links:
Fetch data from server and refresh UI when data is fetched?
How to start and finish progressBar dynamically in android