在完成前台活动时禁用重新执行异步任务

时间:2013-06-03 10:28:49

标签: android android-asynctask android-activity activity-lifecycle

案例: 我正在使用Async Task来显示一些列表。当我点击listview的任何项目时,另一个活动成为最后一个活动的前景。此前台活动包含一个完成按钮,前景活动通过该按钮完成。

问题: 当我按下完成按钮时,前台活动结束,但最后一次执行异步任务的活动再次执行。

需要: 我想按下完成按钮然后只有前台活动结束,并且具有异步任务的后台活动不能再次执行。该背景活动必须与打开前台活动前相同。

修改 头等舱有Asynch任务

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);
        }

    }
}

完成按钮后的第二课

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();
        }
    });



}

第二个活动按下该前景活动完成按钮但在完成该后台活动后调用Acync Task再次执行。如何重新获得。

非常感谢

2 个答案:

答案 0 :(得分:0)

然后在第一个活动开始第一个活动的第一个活动的oncreate方法开始你的asynctask第一个活动将成为前景,当第二个活动看到第二个活动时,第一个活动将不再重建它只会恢复暂停活动,因为你在oncreate中调用asynctask它不会再次启动线程

答案 1 :(得分:0)

这是你应该使用单例类

实现的
  1. 创建一个名为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;
    }
    
    }
    
  2. 此处getInstance方法确保此类只有一个对象和布尔值 一旦解析并存储了数据,isDataRecieved就应该设置为true。

    就像你的ASyncTask的postExecute一样添加这些行

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

    现在on onCreate添加这些行

    Datamanager d=Datamanager.getInstance();
    if(!d.isDataRecieved)
    {
    //This means data is not recieved 
    
    execute your asynctask else not 
    }