如何使asynctask在后台运行,即使活动被破坏了?

时间:2015-11-25 17:42:45

标签: android android-asynctask

我正在制作一些asynctask方法,但我不确定如何在应用程序关闭时让它继续在后台运行。有人说它可以与Service一起使用或将代码放在doinbackground中,但我不知道如何实现它。顺便说一句,这是我的代码:

    private class DataBinatangOperation extends AsyncTask<String, Void, String> {

    MainMenuAdapter adapter = new MainMenuAdapter(MainMenu.this,
            listBinatang);

    @Override
    protected String doInBackground(String... params) {

        JSONArray json;
        try {
            result = JSONParser.getPage(url);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return result;
    }


    @Override
    protected void onPostExecute(String result) {

        //updateList();
        tv.setVisibility(View.GONE);

            //mSwipeRefreshLayout.setRefreshing(false);


        try {
            System.out.print("result = " + result);
            json = new JSONObject(result);
            progress.dismiss();

            JSONArray objek = json.getJSONArray("data_vaksinasi_menu");

            for (int i = 0; i < objek.length(); i++) {

                JSONObject jo = objek.getJSONObject(i);

                ID_USER = jo.getString(id_user);
                ID_BINATANG = jo.getString(id_binatang);
                NAMA_BINATANG = jo.getString(nama_binatang);
                JENIS_BINATANG = jo.getString(jenis_binatang);
                FOTO_BINATANG = jo.getString(foto_binatang);
                TANGGAL_VAKSIN = jo.getString(tanggal_vaksin);
                NAMA_VAKSIN = jo.getString(nama_vaksin);
                RAS_BINATANG = jo.getString(ras_binatang);

                DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

                Calendar waktuSekarang = Calendar.getInstance();

                Date date1 = waktuSekarang.getTime();
                Date date2 = new Date();

                date2 = formatter.parse(TANGGAL_VAKSIN);

                /*waktuVaksin.setTime(date2);

                DateMidnight start = new DateMidnight(tanggalSkrg);
                DateMidnight vaksin = new DateMidnight(TANGGAL_VAKSIN);*/

                if (pref.getPreferences("ID").equals(ID_USER)) {
                    if (date2.after(date1)) {
                        int days = Days.daysBetween(new DateTime(date1), new DateTime(date2)).getDays();
                        if (days > 7 && days <= 30) {
                            int weeks = days / 7;
                            sisaWaktu = String.valueOf(weeks) + " minggu";
                        } else if (days > 30 && days <= 365) {
                            int months = days / 30;
                            sisaWaktu = String.valueOf(months) + " bulan";
                        } else if (days > 365) {
                            int years = days / 365;
                            sisaWaktu = String.valueOf(years) + " tahun";
                        } else {
                            sisaWaktu = String.valueOf(days) + " hari";
                            if (days <= 5) {
                                NH.createSimpleNotification(getActivity(), NAMA_BINATANG, sisaWaktu, ID_BINATANG);
                            }
                        }
                    } else if (date2.before(date1)) {
                        int days = Days.daysBetween(new DateTime(date2), new DateTime(date1)).getDays();
                        sisaWaktu = "lewat " + String.valueOf(days) + " hari";
                        NH.createButtonNotification(getActivity(), NAMA_BINATANG, sisaWaktu, ID_BINATANG);

                    } else if (date2.equals(date1)) {
                        sisaWaktu = "sekarang";
                        NH.createButtonNotification(getActivity(), NAMA_BINATANG, sisaWaktu, ID_BINATANG);
                    }
                }
                HashMap<String, String> map = new HashMap<String, String>();

                map.put(id_binatang, ID_BINATANG);
                map.put(nama_binatang, NAMA_BINATANG);
                map.put(jenis_binatang, JENIS_BINATANG);
                map.put(foto_binatang, urlgambar+FOTO_BINATANG);
                map.put(ras_binatang, RAS_BINATANG);
                map.put(tanggal_vaksin, sisaWaktu);
                map.put(nama_vaksin, NAMA_VAKSIN);



                if (pref.getPreferences("ID").equals(ID_USER)) {
                        listBinatang.add(map);
                }


            }

            System.out.println("hasil list : " + String.valueOf(listBinatang));

            System.out.println("adapter : " + String.valueOf(adapter));
            list.setAdapter(adapter);



            /*list.setVisibility(View.VISIBLE);*/
            list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long idx) {

                    HashMap<String, String> ambilid = new HashMap<String, String>();
                    ambilid = listBinatang.get(position);

                    Toast.makeText(getActivity(), "pindah halaman", Toast.LENGTH_SHORT).show();

                    Intent a = new Intent(getActivity(), MainPetInformation.class);
                    pref.savePreferences("IDB", ambilid.get(MainMenu.id_binatang));
                    pref.savePreferences("NAMAB", ambilid.get(MainMenu.nama_binatang));
                    pref.savePreferences("FOTOB", ambilid.get(MainMenu.foto_binatang));
                    pref.savePreferences("JENISB", ambilid.get(MainMenu.jenis_binatang));
                    pref.savePreferences("RASB", ambilid.get(MainMenu.ras_binatang));
                    startActivity(a);
                }

            });

        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // might want to change "executed" for the returned string passed
        // into onPostExecute() but that is upto you
    }

    @Override
    protected void onPreExecute() {
        listBinatang.clear();
        adapter.notifyDataSetChanged();
        progress = ProgressDialog.show(getActivity(), "Please Wait",
                "Loading Data", true);

    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}

1 个答案:

答案 0 :(得分:0)

protected abstract Object doInBackground(Object... params)

来自AsyncTask的方法是在主线程(也称为UI线程)的后台执行操作,用于执行需要在主线程(网络)上执行的操作,或者您想要的操作在不阻止用户体验负面的情况下(例如在任务完成之前阻止用户进一步使用应用程序的任务)。

这是一个简洁而精彩的服务教程,这正是您所寻找的:http://www.vogella.com/tutorials/AndroidServices/article.html。服务 可以 在后台执行操作,就像AsyncTask的doInBackground方法一样,但可以在应用程序处于后台时按照您的说法执行操作,并且间隔,如果你需要它。

我可以更深入地了解这一点,但是该教程包含了您需要的所有信息,我怀疑它正是您所寻找的。