简体   繁体   中英

how to make the asynctask run in background even the activity destroyed?

i'm making some asynctask method, but i'm not really sure how to make it keep running on the background when the app was closed. Some said it could be used with Service or put the code in doinbackground but i'm not sure how to implement it. Btw, Here's my code:

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

protected abstract Object doInBackground(Object... params)

Is the method from the AsyncTask that performs operations in the background of the main thread (also known as UI thread), which is used to do actions that either are required to be performed off the main thread (networking) or you want to do without preventing a negative user experience (such as a task that would prevent the user from using the app any further until the task has completed).

Here is a succinct and nice tutorial for Services, which is indeed what you are looking for: http://www.vogella.com/tutorials/AndroidServices/article.html . A service can perform operations in the background like an AsyncTask's doInBackground method does, but can do it when the app is in the background as you said, and in intervals if you need it to.

I could go into more depth on this, but that tutorial has all the information you need and I suspect it is what you are looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM