I am making an android app with 3 activities for the moment, that get data from distant server , I used AsyncTask, it works perfectly .
Activity A & Activity B Activity C :
Activity A executes an AsyncTask (Task_A) and in onPostExecute, I launch the second Activity_B , that will execute an AsyncTask (Task_B) in onResume., and the second onPostExecute,the third activity will excute .
In Activty A :
// GetResults1 task1 =new GetResults1();
#Override
public void onClick(View v) {
task1.execute();
}
private class GetResults1 extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
// here my code (it worked finally)
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Intent intent = new Intent(ActivityA.this, ActivityB.class);
startActivity(intent);
}
}
In Activty B :
#Override
protected void onResume() {
// TODO Auto-generated method stub
Log.i("LOADING", "onResume");
super.onResume();
GetResults2 task2 =new GetResults2();
task2.execute();
}
private class GetResults2 extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
// here my code (it worked finally)
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Intent intent = new Intent(ActivityB.this, ActivityC.class);
startActivity(intent);
}
}
THE PROBLEM Now :
If I run my app and see the logcat : the second asynck Task executes before onStop of the first activity.
OnCreate Activity_A
OnStart Activity_A
OnResume Activity_A
Task_1 begin // action button
onPreExecute Task_1
doInBackground Task_1
onPostExecute Task_1
OnPause Activty_A |||||||||||
OnCreate Activity_B ||||||
OnStart Activity_B
OnResume Activity_B
Task_2 begin
onPreExecute Task_2
doInBackground Task_2
onPostExecute Task_2
OnStop Activity_A
I want that the second AsynckTask executes when ActivityA executes onStop method.
Related
I've an Asynchronous task method, that calls background process. when i call this summaryCalc method, preexecute method runs when this method calls but doInBackground method takes more than 20 seconds to start. it takes a long time. is there any other way to improve the speed of calling doInBackground method or any other fastest way to execute thread? Thank you.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_summary_date_select);
btnSearch = (Button) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
summaryCalc();
}
});
}
/**
* method to create asynchronous task to realign summary data
*/
public void summaryCalc() {
new AsyncTask<Void, Void, String>() {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(SummaryDateSelectActivity.this);
dialog.setTitle(getResources().getString(R.string.app_name));
dialog.setMessage(getResources().getString(R.string.please_wait));
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
ExtraSettingsDS settingsDS = new ExtraSettingsDS(getApplicationContext());
ExtraSettingsDO settingsDO = settingsDS.getExtraSettingsValues();
WeeklySummaryRecovery summaryRecovery = new WeeklySummaryRecovery(getApplicationContext());
/*Insert missing account order data*/
summaryRecovery.insertMissingAccOrderData();
if (settingsDO.getAccManage() == 0) {
summaryRecovery.summaryInsertForSeparateAccManage();
} else {
summaryRecovery.summaryInsertForJoinAccManage();
}
settingsDS.updateWeeklyFinishedDate();
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
dialog.dismiss();
intent = new Intent(getApplicationContext(), SummaryDetailsShowActivity.class);
intent.putExtra(KandhaConstants.IE_NEXT_ACTIVITY, accCheck);
intent.putExtra(KandhaConstants.IE_DAY_OF_LINE, currentDay);
intent.putExtra(KandhaConstants.IE_START_DATE, date);
startActivity(intent);
finish();
}
}.execute(null, null, null);
}
It is possible you have a lot of async tasks running. Calling .execute() will execute them one by one. Try calling .executeOnExecutor() instead.
http://developer.android.com/reference/android/os/AsyncTask.html
I am trying to implement an app in which I have to initially download a file, and only then can I proceed. So I don't want to make the screen idle for N number of seconds for the duration of downloads, I want to cover it with a splash screen. So basically downloading all the files, and it will be covered by the splash activity.
This is the code I generally use for splash activity, then jumping to the main activity after the delay.
The real problem is that I have the AsyncTask in the main_activity, I want to show the splash screen, while I can download the file in the AsyncTask . Then I can move to the main activity
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(Splash_Screen.this, MainActivity.class);
startActivity(i);
// close this activity
finish();
}
}, 3000);
}
I recommande you to choose the AsyncTask, where you can do a task in the backGround in your example downloading the file, and in the post execution wich mean after your file is downloaded you can do what ever you want.
private class Asyn_DownLoadFile extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
//download your file here
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
/*this function is called automatically by the doInBackground when
it finish it's work*/
}
}
Just remenber AsyncTask must be subClassed, that's mean call implement the AsyncTask in the Splash screen Activity and in the onPostExecution do what you want
to start the AsyncTask use
new Asyn_DownLoadFile().execute(null,null,null);
EDIT:
here what you have to do:
suppose this your Splash class
public class SplashActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
context = this;
//.......................
new Asyn_DownLoadFile().execute(null,null,null);
}
//this is your function that downLoad the file
public void downLoadFile(){
//............................
}
private class Asyn_DownLoadFile extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
downLoadFile();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Intent i = new Intent (context, MainActivity.class)
startActivity(i);
}
}
}
Anyone know if it possible to kill/stop AsyncTask without loop.
There was many examples with loop but the task which I should do in doInBackground() function only one function which in some cases take long time and I shall stop it for example in onPause. If it possible or I should use another task for example Futuretask.
Thanks in advance.
The code like this:
class ProcessTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
Log.i(TAG, " ---- ProcessTask -- doInBackground ----");
// Task
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Log.i(TAG, " ---- ProcessTask -- onPostExecute ----");
}
#Override
protected void onCancelled(Boolean result) {
super.onCancelled(result);
Log.i(TAG, " ---- ProcessTask -- onCancelled ----");
}
}
...
ProcessTask myTask;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
myTask = new OCRProcessTask();
myTask.cancel(false);
myTask.execute();
}
#Override
public void onPause() {
myTask.cancel(true);
}
You can cancel the AsyntTask by setting cancel(true) to the task.
new MyAsyncTask().cancel(false);
I have a AsysTask
class myAsyncTask extends AsyncTask<Void, Void, Integer> {
ProgressDialog progDialog;
myAsyncTask() {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progDialog = ProgressDialog.show(
SwitchArticle.this,
"Loading",
"Pleasewait",
true,
true,
new DialogInterface.OnCancelListener(){
#Override
public void onCancel(DialogInterface dialog) {
myAsyncTask.this.cancel(true);
}
}
);
}
#Override
protected Integer doInBackground(Void... arg0) {
// Call a function load Data Json...
return 1;
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (result != 1) {
progDialog.dismiss();
Toast.makeText(
SwitchArticle.this,
"Error Load Data",
Toast.LENGTH_SHORT).show();
}
else
{
//.. Bind Data To Adapter
}
progDialog.dismiss();
}
}
Call in Oncreate function :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myAsyncTask ma = new myAsyncTask();
ma.execute();
}
The first time, this code is load data and bind to listview very good.
then, i press back other activity,and comback this activity call asyntask, this code run very good.
After i back to other activity , and finish this activity call this asysntask. I press lock screen device and wait about 5 minute. i unlock device and come back activity call this asysntask. myAsynTask run doInBackGround and NOT run to onPostExcute to bind data to ListView.
Sorry because my English is very poor. I'm Vietnamese.
I think onCreate is called when you unlock the screen and go back to your activity. That means your AsyncTask will start running again... Hope that helps
I have this async task that call an web service and parse an xml
#Override
protected void onPreExecute(){
super.onPreExecute();
time = System.currentTimeMillis();
}
protected Boolean doInBackground(Integer... params) {
//code
}
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
difftime = System.currentTimeMillis() - time;
}
while async task is executing I want to display an loading screen,but the loading screen finishes before async task finish if I am doing like this
super.onCreate(savedInstanceState);
setContentView(R.layout.loading_screen);
final CallWebService callTarif = new CallWebService(6,sett.getDeviceId());
callTarif.execute();
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
LoadingScreen.this.finish();
Intent intent = new Intent(LoadingScreen.this, NextActivity.class);
startActivity(intent);
}
}
},callTarif.difftime);
Actually postDelayed is called before completing the AsyncTask.
Just put these code lines
LoadingScreen.this.finish();
Intent intent = new Intent(LoadingScreen.this, NextActivity.class);
startActivity(intent);
in opPostExecute() of AsyncTask.
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
difftime = System.currentTimeMillis() - time;
LoadingScreen.this.finish();
Intent intent = new Intent(LoadingScreen.this, NextActivity.class);
startActivity(intent);
}
And remove Handler new Handler().postDelayed(new Runnable(){
start your loading screen onPreExecute method and kill it onPostExecute method of the async task
No need to use Handler for showing loading when accessing webservice using async task . use onPreExecute() method of AsyncTask to Show loading Screen and finish it inside onPostExecute because this method called when doInBackground execution complete . change code code as :
#Override
protected void onPreExecute() {
// show loading bar here
}
#Override
protected String doInBackground(String... params) {
// do network operation here
return null;
}
#Override
protected void onPostExecute(String result) {
// dismiss loading bar here
}