Disabling Re-execution of Async Task on finishing of foreground activity

一曲冷凌霜 提交于 2019-12-13 06:06:39

问题


Case: I am using Async Task for showing some list. When I click on any item of listview another activity comes foreground of last activity. This foreground activity contains a finish button through which the foreground activity finishes.

Problem: When i press finish button the foreground activity finishes but that last activity having the Async Task executes again.

Need: I want when i press finish button then only foreground activity finishes and background activity having Async Task must not execute again. That background activity must be same as it was before opening foreground activity.

EDIT: First Class having Asynch Task

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.restaurant_detail);
    Intent i = getIntent();
    res_id = i.getStringExtra("id");
    gps = new GPSTracker(getApplicationContext());
    session = new SessionManagement(getApplicationContext());
    fillDatabase = new DatabaseHandler(getApplicationContext());
    fillDatabase.open();
    count = fillDatabase.fetchCount();
    SetUpViews();
    SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
    Date d = new Date();
    dayOfTheWeek = sdf.format(d);
    Log.i("WEEKDAY", dayOfTheWeek);
    imageLoader = new ImageLoader(getParent());
    progressDialog = ProgressDialog.show(getParent(), "", "Loading...");
    Log.v(String.valueOf(count), "count");
    // new MenuTask().execute();
    new DetailsTask().execute();


}
public class DetailsTask extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... arg0) {
        // Creating JSON Parser instance//////////
        JSONParser jParser = new JSONParser();
        // Getting JSON String from URL..............
        JSONObject jObject = jParser
                .getJSONFromUrl("http://smartaway.dk/json/rest_get_details.php?id="
                        + res_id);
        try {
            // /Getting array of Events.......
            details = jObject.getJSONArray(TAG_NODE);
            // / LOOping through AllEvents........
            for (int i = 0; i < details.length(); i++) {
                JSONObject e = details.getJSONObject(i);
                res_id = e.getString(TAG_ID);
                res_name = e.getString(TAG_RESNAME);
                logo = e.getString(TAG_RES_LOGO);
                name = e.getString(TAG_RESNAME);
                city_state = e.getString(TAG_CITY);
                street = e.getString(TAG_STREET);
                localityString = e.getString(TAG_LOCALITY);
                restype = e.getString(TAG_RESTYPE);
                Log.v(restype, "restype");
                lat = e.getString(TAG_LAT);
                Log.v(lat, "latitude");

                lng = e.getString(TAG_LNG);
                Log.v(lng, "longitude");
                cuisineString = e.getString(TAG_COUSINE);
                timingsString = e.getString(TAG_TIMING);
                // costString = e.getString(TAG_COSRTWO);

                res_des_String = e.getString(TAG_RES_DES);

                cardString = e.getString(TAG_CARDS);
                facilitiesString = e.getString(TAG_FACILITIES);

                parkingString = e.getString(TAG_PARKING);
                minorderString = e.getString(TAG_MINORDER);
                deliverychargesString = e.getString(TAG_DELIVERY_CHARGES);
                ratings = e.getString(TAG_RATING);
                smily = e.getString(TAG_SMILY);
                s_o_t = e.getString(TAG_S_O);
                s_c_t = e.getString(TAG_S_C);
                m_o_t = e.getString(TAG_M_O);
                m_c_t = e.getString(TAG_M_C);
                t_o_t = e.getString(TAG_T_O);
                t_c_t = e.getString(TAG_T_C);
                w_o_t = e.getString(TAG_W_O);
                w_c_t = e.getString(TAG_W_C);
                th_o_t = e.getString(TAG_TH_O);
                th_c_t = e.getString(TAG_TH_C);
                f_o_t = e.getString(TAG_F_O);
                f_c_t = e.getString(TAG_F_C);
                sat_o_t = e.getString(TAG_SAT_O);
                sat_c_t = e.getString(TAG_SAT_C);
                smily = e.getString(TAG_SMILY);

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {

        super.onPostExecute(result);
        // progressBar.setVisibility(View.GONE);
        progressDialog.dismiss();
        detail.setVisibility(View.VISIBLE);
        imageLoader.DisplayImage(logo, reslogo);
        resname.setText(StringEscapeUtils.unescapeHtml(name));
        toptxt.setText(StringEscapeUtils.unescapeHtml(name));
        address.setText(StringEscapeUtils.unescapeHtml(street) + " \n"
                + StringEscapeUtils.unescapeHtml(localityString) + " "
                + StringEscapeUtils.unescapeHtml(city_state));
        cuisineString = (cuisineString.equals("") ? "Not present"
                : StringEscapeUtils.unescapeHtml(cuisineString));
        cuisine.setText(cuisineString);
        if (dayOfTheWeek.equalsIgnoreCase("monday")) {
            timings.setText(m_o_t + " - " + m_c_t);

        } else if (dayOfTheWeek.equalsIgnoreCase("tuesday")) {
            timings.setText(t_o_t + " - " + t_c_t);
        } else if (dayOfTheWeek.equalsIgnoreCase("wednesday")) {
            timings.setText(w_o_t + " - " + w_c_t);
        } else if (dayOfTheWeek.equalsIgnoreCase("thursday")) {
            timings.setText(th_o_t + " - " + th_c_t);
        } else if (dayOfTheWeek.equalsIgnoreCase("friday")) {
            timings.setText(f_o_t + " - " + f_c_t);
        } else if (dayOfTheWeek.equalsIgnoreCase("saturday")) {
            timings.setText(sat_o_t + " - " + sat_c_t);
        } else if (dayOfTheWeek.equalsIgnoreCase("sunday")) {
            timings.setText(s_o_t + " - " + s_c_t);
        }
        // costfortwo.setText(costString);
        res_des_String = (res_des_String.equals("") ? "Not present"
                : StringEscapeUtils.unescapeHtml(res_des_String));
        cardString = (cardString.equals("") ? "Not present"
                : StringEscapeUtils.unescapeHtml(cardString));
        parkingString = (parkingString.equals("") ? "Not present"
                : StringEscapeUtils.unescapeHtml(parkingString));
        facilitiesString = (facilitiesString.equals("") ? "Not present"
                : StringEscapeUtils.unescapeHtml(facilitiesString));
        minorderString = (minorderString.equals("") ? "Not present"
                : StringEscapeUtils.unescapeHtml(minorderString));
        deliverychargesString = (deliverychargesString.equals("") ? "Not present"
                : StringEscapeUtils.unescapeHtml(deliverychargesString));

        res_description.setText(res_des_String.replaceAll(
                "(\r\n\t|\n\t|\n|\t)", ""));
        cards.setText(cardString);
        facilities.setText(facilitiesString);

        parking.setText(parkingString);
        minoredr.setText(minorderString);
        delivery_charges.setText(deliverychargesString);
        if (ratings.equals("")) {
            rating.setVisibility(View.GONE);
        } else {
            DecimalFormat numberFormat = new DecimalFormat("##.##");
            rating.setText(numberFormat.format(Double.valueOf(ratings)));
        }
        if (smily.equals("1")) {
            smiley.setImageResource(R.drawable.happy_smile);
        } else if (smily.equals("0")) {
            smiley.setImageResource(R.drawable.sad_smile);
        } else {
            smileyLayout.setVisibility(View.GONE);
        }

    }
}

Second Class Having finish Button

setContentView(R.layout.submenulist);

    Intent i = getIntent();
    main_menu = i.getStringExtra("id");
    res_id = i.getStringExtra("res_id");
    res_name = i.getStringExtra("res_name");
    Log.v("Main Menu Name", main_menu);
    fillDatabase = new DatabaseHandler(getApplicationContext());
    fillDatabase.open();
    count = fillDatabase.fetchCount();


    backButton = (Button) findViewById(R.id.finish);
    backButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            finish();
        }
    });



}

Second activity have button on pressing that foreground activity finishes but after finishing that background activity call Acync Task to execute again. How to reslove that.

Thanks a lot


回答1:


then start your asynctask in oncreate method of first activity when second activity start the first activity will become foreground and when visible second activity finjsh then first activity will not be recreate it will only resume the pause activity so as u called asynctask in oncreate it will not start thread again.




回答2:


Well this is something you should achieve using the singleton class

  1. Create a class say DataManager

    public class DataManager {
    public static DataManager dManager;
    
    boolean isDataRecieved;
    
    public static DataManager getInstance()
    {
        if(dManager!=null)
            return dManager;
    
        else
            dManager=new DataManager();
    
        return dManager;
    }
    
    }
    

here the getInstance method ensures there is only one object of this class and the boolean isDataRecieved should be set to true as soon as the data is parsed and stored.

like on postExecute of your ASyncTask add these lines

Datamanager d=Datamanager.getInstance();
d.isDataRecieved=true;

now on onCreate add these lines

Datamanager d=Datamanager.getInstance();
if(!d.isDataRecieved)
{
//This means data is not recieved 

execute your asynctask else not 
}


来源:https://stackoverflow.com/questions/16894686/disabling-re-execution-of-async-task-on-finishing-of-foreground-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!