简体   繁体   English

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

[英]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. 我正在做一些asynctask方法,但是我不确定如何关闭应用程序时使其在后台继续运行。 Some said it could be used with Service or put the code in doinbackground but i'm not sure how to implement it. 有人说它可以与Service一起使用或将代码放在doinbackground中,但是我不确定如何实现它。 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) 受保护的抽象对象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). 是AsyncTask中的方法,该方法在主线程(也称为UI线程)的后台执行操作,该方法用于执行需要在主线程(网络)上执行的操作,或者您想要不执行的操作防止负面的用户体验(例如一项任务,该任务将阻止用户在任务完成之前进一步使用该应用)。

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 . 这是有关Service的简洁明了的教程,确实是您所需要的: 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. 服务可以像AsyncTask的doInBackground方法一样在后台执行操作,但是可以按照您所说的在后台运行应用程序执行操作,并且在需要时可以间隔执行操作。

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. 我可以对此进行更深入的研究,但是该教程包含了您需要的所有信息,我怀疑这正是您所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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