Issue
I am having some trouble restarting an AsyncTask
after I try to reopen the activity.
When I first open the activity I call this to start the AsyncTask
which works the very first time.
myTask connectedTask;
connectedTask = new myTask();
connectedTask.execute();
public class myTask extends AsyncTask<Integer,Integer, Integer> {
@Override
protected Integer doInBackground(Integer... arg0) {
//Increase timer and wait here in a loop
System.out.println("ASYNC TASK STARTING!");
return IsSocketConnected();
}
protected void onPostExecute(Integer result) {
//Something you want to do when done?
System.out.println("ASYNC TASK DONE!");
// if it was connected successfully
if(result == 1) {
// remove the progress bar
proBar.setVisibility(View.GONE);
// Discover available devices settings and create buttons
CreateButtons(btnList);
}
}
}
IsSocketConnected(); // checks for a bluetooth connections to be done.
When I go back to previous activity and try to start that activity again I can't get the AsyncTask
to start again.
I read that as long as I create a new instance of the AsyncTask
I should be to restart those tasks.
Is there something else that I should be doing?
Thank you,
Solution
Thank you for all your comments they helped a lot. I decided to do away with the AsyncTask. I ended using a normal runnable Thread and using Handlers to post messages back to the UI thread. here is the code:
// Start thread here only for IsSocketConnected
new Thread(new Runnable() {
public void run() {
//Add your code here..
IsSocketConnected();
}
}).start();
// handler that deals with updating UI
public Handler myUIHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
if (msg.what == Bluetooth.STATE_CONNECTED)
{
//Update UI here...
Log.d(TAG, "Connected");
// Discover available devices settings and create buttons
CreateButtons(btnList);
} else if(msg.what == Bluetooth.STATE_NONE) {
Log.d(TAG, "NOT Connected");
}
}
// in the IsSocketConnected() I call this
Message theMessage = myUIHandler.obtainMessage(Bluetooth.STATE_CONNECTED);
myUIHandler.sendMessage(theMessage);//Sends the message to the UI handler.
This is working so far. Thank you again. Hope this helps someone
Answered By - jramirez
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.