views:

22

answers:

0

I was trying to get my method running in background using Asynctask, but using sample from the book for a basis the only thing I get is crashed application. At moment I am using this code:

private Handler mHandler = new Handler();
private Runnable mUpdateTimeTask = new Runnable() {
    public void run() {
        Location location = tracker.getLastKnownLocation(best);
        RetrieveAvgPower(location);
        mHandler.postDelayed(this, 1000);
    }
};

An this code to start/stop it:

public void onClick(View v) {
         switch (v.getId()) {
                case R.id.start:
                    mStartTime = System.currentTimeMillis();
                    mHandler.removeCallbacks(mUpdateTimeTask);
                    mHandler.postDelayed(mUpdateTimeTask, 2000);
                    break;
                case R.id.stop:
                    mHandler.removeCallbacks(mUpdateTimeTask);
                    break;
               }
    } 

However, like it should be UI is not responding when the method is executed, so I clearly understand that asynctask is needed, but I do not clearly understand what I need to do. Probably this is all wrong, but...

private class StarT extends AsyncTask<Void,Void,String> {
@Override
protected String doInBackground(Void... params) {
    Location location = tracker.getLastKnownLocation(best);
    //RetrieveAvgPower(location);
    String result=AvgPower2String(location);
    return result;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast output = Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT);
output.show();
}
}

As I understood this should be executed with

new StarT().execute();

Another thing I wanted to ask is if I have Thread.sleep() inside the RetrieveAvgPower(location) will it affect UI?

Updated 28.10.2010

I managed to make my asynctask working. Now i would like to know how to insert something like mHandler.postDelayed(mUpdateTimeTask, 2000); ,because i need this method to execute automatically after approx. 10 seconds?