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
Related
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.
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);
}
}
}
Since the game requires TTS, and need quite a long time to load, I would like to implement Progress Dialog (PD), as either in the following ways:
Implement AsyncTask in Game Index Page:
This will show the PD, but the PD is freezed, i.e. the looping circle inside the PD is not looping.
buttonC.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
new initialize_game().execute();
}
});
private class initialize_game extends AsyncTask<String,Integer,String>
{
#Override
protected void onPreExecute()
{
dialog= new ProgressDialog(Index_game.this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading!\nPlease wait...");
dialog.show();
}
#Override
protected String doInBackground(String... params)
{
buttonC.setBackgroundColor(getResources().getColor(R.color.tran_black));
Intent intent = new Intent(Index_game.this, Game_star_intro.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivityForResult(intent, 0);
overridePendingTransition(0, 0); // 0 for no animation
Index_game.this.finish();
return "Done!";
}
protected void onPostExecute(String result)
{
super.onPostExecute(result);
Log.i("result","" +result);
if(result!=null)
{
dialog.dismiss();
}
}
}
AsyncTask for TTS:
Once clicked from the Game Index Page, no PD is shown until the Game is loaded fully, and at that time then the PD pops up and off for a millisecond, i.e. even worse than that above.
private class MainFrameTask extends AsyncTask<String,Integer,String> implements OnInitListener, OnUtteranceCompletedListener
{
private Index_game_card_intro mainFrame = null;
public MainFrameTask(Index_game_card_intro mainFrame)
{
this.mainFrame = mainFrame;
}
#Override
protected void onCancelled()
{
stopProgressDialog();
super.onCancelled();
}
#Override
protected void onPreExecute()
{
startProgressDialog();
}
#Override
protected String doInBackground(String... params)
{
// setup TTS part 1.1
mTts = new TextToSpeech(Index_game_card_intro.this, this); // TextToSpeech.OnInitListener
return "Done!";
}
protected void onPostExecute(String result)
{
stopProgressDialog();
}
// setup TTS part 2
#Override
public void onUtteranceCompleted(String utteranceId)
{
Log.v(TAG, "Get completed message for the utteranceId " + utteranceId);
lastUtterance = Integer.parseInt(utteranceId);
}
// setup TTS part 3
#Override
public void onInit(int status)
{
if(status == TextToSpeech.SUCCESS)
{
int result = mTts.setLanguage(Locale.US); // <====== set speech location
mTts.setSpeechRate((float) 0.8);
mTts.setPitch(1.0f);
if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED)
{
// button_header.setEnabled(false);
}
else
{
// button_header.setEnabled(true);
mTts.setOnUtteranceCompletedListener(this);
}
}
}
}
// setup TTS part 4
private void speakText()
{
lastUtterance++;
if(lastUtterance >= loveArray.length)
{
lastUtterance = 0;
}
Log.v(TAG, "the begin utterance is " + lastUtterance);
for(int i = lastUtterance; i < loveArray.length; i++)
{
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, String.valueOf(i));
mTts.speak(loveArray[i], TextToSpeech.QUEUE_ADD, params);
mTts.playSilence(ttsilience, TextToSpeech.QUEUE_ADD, null);
}
}
Question:
I found that the Progress Dialog does not show out when Button C in the game index is pressed. However, when the Game_star_intro is finally loaded, the progress dialog pops up for a very very short time and then gone.
I would like to show the ProgressDialog when it is loading up the game, not after the game is loaded then the dialog pops for a millisecond.
In this way, I have also tried to put the load TTS in AsyncTask inside Game_star_intro, yet the result is the same: the dialog just pops up for a millisecond.
Actually how should the AsyncTask be coded?? I have followed some website like this http://karanbalkar.com/2012/10/tutorial-5-custom-progressdialog-with-asynctask/
Thanks for your time!
You shouldn't start your activity in background thread. Start it, for example, in your onClick() method. You should put only your expensive code in doInBackground(), separating it from the framework lifecycle stuff. I guess you should implement AsyncTask inside Game_star_intro class for this.
ProgressDialog is not showing probably because UI thread is freezed until the work is done.
Also, naming conventions in Java suggest name classes without underscores, i.e. GameStarIntro :)
If I understood correctly from your question, loading of the Game_star_intro activity takes a lot of time because you use TTS in creation of this activity. The code you use is wrong. ProgressDialog from Index_game won't be shown when another activity is running (or is being created). You should use AsyncTask in Game_star_intro activity and use TTS there. In Index_game just start Game_star_intro:
buttonC.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(Index_game.this, Game_star_intro.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivityForResult(intent, 0);
}
});
And in Game_star_intro something like this
public void onCreate() {
...
new TTLTask().execute();
}
private class TTLTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute()
{
dialog= new ProgressDialog(Index_game.this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading!\nPlease wait...");
dialog.show();
}
#Override
protected String doInBackground(String... params)
{
//... TTS code
return null;
}
protected void onPostExecute(String result)
{
super.onPostExecute(result);
Log.i("result","" +result);
if(dialog.isShown())
{
dialog.dismiss();
}
}
}
i want to add a progress Dialog button when i click on this button before the new activity apperar, i think i don't need a thread, i did search but i find only that i need to do a thread and many other think it s not clear
i just want when i clik on a progress Dialog say to the user to wait so a few sec the other activity will appear that's all:
btn_newsfeed.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Launching News Feed Screen
Intent i = new Intent(getApplicationContext(), CustomizedListView.class);
startActivity(i);
}
});
There are three different different ways in which you can use a ProgressDailog -using threads, handlers and async tasks.
here a example of async task for using a progress Dialog
private class Operation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params)
{
// code to be executed in background thread
for(int i=0;i<5;i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
// runs on UI thread and updated UI after executing doInBackground
progressDialog.dismiss();
}
#Override
protected void onPreExecute() {
ProgressDialog progressDialog = ProgressDialog.show(MainActivity.this, "Title ", "Loading...");
progressDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
// runs on UI thread and starts first
}
}
I'm creating a thread in android for a time consuming operation. I want the main screen to show a progress dialog with a message informing that the operation is in progress, but I want that dialog to dismiss once the thread is done. I've tried with join but it locks the thread and doesn't show the dialog. I tried using:
dialog.show();
mythread.start();
dialog.dismiss();
but then the dialog doesn't show. How can I make that sequence but wait for the thread to end without locking the main thread?
This is as far as I got:
public class syncDataElcanPos extends AsyncTask<String, Integer, Void> {
ProgressDialog pDialog;
Context cont;
public syncDataElcanPos(Context ctx) {
cont=ctx;
}
protected void onPreExecute() {
pDialog = ProgressDialog.show(cont,cont.getString(R.string.sync), cont.getString(R.string.sync_complete), true);
}
protected Void doInBackground(String... parts) {
// blablabla...
return null;
}
protected void onProgressUpdate(Integer... item) {
pDialog.setProgress(item[0]); // just for possible bar in a future.
}
protected void onPostExecute(Void unused) {
pDialog.dismiss();
}
But when I try to execute it, it gives me an exception: "Unable to add window".
When your thread is done, use the runOnUIThread method to dismiss the dialog.
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
To do that there is two ways to do it , ( and i prefer the first second one : AsyncTask ) :
First : you display your alertDialog , and then on the method run() you should do like this
#override
public void run(){
//the code of your method run
//....
.
.
.
//at the end of your method run() , dismiss the dialog
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
}
Second : Using an AsyncTask like this :
class AddTask extends AsyncTask<Void, Item, Void> {
protected void onPreExecute() {
//create and display your alert here
pDialog = ProgressDialog.show(MyActivity.this,"Please wait...", "Downloading data ...", true);
}
protected Void doInBackground(Void... unused) {
// here is the thread's work ( what is on your method run()
items = parser.getItems();
for (Item it : items) {
publishProgress(it);
}
return(null);
}
protected void onProgressUpdate(Item... item) {
adapter.add(item[0]);
}
protected void onPostExecute(Void unused) {
//dismiss the alert here where the thread has finished his work
pDialog.dismiss();
}
}
well in AsyncTask in the on postexecute you can call dismiss
here is an example from other thread
class AddTask extends AsyncTask<Void, Item, Void> {
protected void onPreExecute() {
pDialog = ProgressDialog.show(MyActivity.this,"Please wait...", "Retrieving data ...", true);
}
protected Void doInBackground(Void... unused) {
items = parser.getItems();
for (Item it : items) {
publishProgress(it);
}
return(null);
}
protected void onProgressUpdate(Item... item) {
adapter.add(item[0]);
}
protected void onPostExecute(Void unused) {
pDialog.dismiss();
}
}