简体   繁体   English

如何即使在应用最小化状态下也始终运行asynctask?

[英]How to run asynctask always even in app minimised sate?

Hi i have completed a process in android which will call a web service containing calendar events. 嗨,我已经在android中完成了一个流程,该流程将调用包含日历事件的网络服务。 i parsed and added the events to android calendar successfully. 我解析并将事件成功添加到android日历中。 I used asynctask to do this. 我使用asynctask来做到这一点。 But now this process has to run for every 30 seconds even if the app is in minimised state. 但是现在,即使应用程序处于最小化状态,此过程也必须每30秒运行一次。 i surfed and found that we can use thread,aynstask,service,alarm receiver to implement it. 我冲浪,发现我们可以使用线程,aynstask,服务,警报接收器来实现它。 but iam not having knowledge in those things.Please help me if anybody knows. 但我对这些事情一无所知。如果有人知道,请帮助我。

My asynctask: 我的asynctask:

public class SyncCalendar extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            progressdialog = new ProgressDialog(MainActivity.this);
            progressdialog.setCancelable(true);
            progressdialog.setMessage("Fetching Appointments and Tasks...");
            progressdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressdialog.setProgress(0);
            progressdialog.show();
        }

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            String taskresult = getCalendarData();
            Log.d("test", "" + taskresult);
            return taskresult;
        }

        protected void onPostExecute(String taskresult) {

            if (taskresult != "" && taskresult != null) {
                try {

                    if (response.contains("Appointment")) {
                        Log.e("called", "called");
                        try {
                            leadna_leadAppointaray = leadna_leadSyncCalendar
                                    .getJSONArray("Appointment");                           
                            if(leadna_leadAppointaray.length()!=0){
                            for (int i = 0; i < leadna_leadAppointaray
                                    .length(); i++) {
                                Log.e("called", "called"+i);
                                JSONObject c = leadna_leadAppointaray
                                        .getJSONObject(i);
                                String startDate = c.getString("StartDate");
                                String[] startDatearay = startDate.split("\\-");
                                String endDate = c.getString("EndDate");
                                String[] endDatearay = endDate.split("\\-");
                                String startTime = c.getString("StartTime");
                                String[] startTimearay = startTime.split("\\:");
                                String endTimeData = c.getString("EndTime");
                                String[] endTimearay = endTimeData.split("\\:");
                                long calID = 1;
                                long startMillis = 0;
                                long endMillis = 0;
                                Calendar beginTime = Calendar.getInstance();
                                beginTime.set(
                                        Integer.parseInt(startDatearay[0]),
                                        Integer.parseInt(startDatearay[1]),
                                        Integer.parseInt(startDatearay[2]),
                                        Integer.parseInt(startTimearay[0]),
                                        Integer.parseInt(startTimearay[1]));
                                startMillis = beginTime.getTimeInMillis();
                                Calendar endTime = Calendar.getInstance();
                                endTime.set(Integer.parseInt(endDatearay[0]),
                                        Integer.parseInt(endDatearay[1]),
                                        Integer.parseInt(endDatearay[2]),
                                        Integer.parseInt(endTimearay[0]),
                                        Integer.parseInt(endTimearay[1]));
                                endMillis = endTime.getTimeInMillis();
                                ContentResolver cr = getContentResolver();
                                ContentValues values = new ContentValues();
                                SimpleDateFormat formatter = new SimpleDateFormat(
                                        "dd/MM/yyyy");
                                String dateString = formatter.format(new Date(
                                        startMillis));
                                String edateString = formatter.format(new Date(
                                        startMillis));
                                Log.e("Date", dateString);
                                Log.e("EDate", edateString);
                                values.put(Events.DTSTART, startMillis);
                                values.put(Events.DTEND, endMillis);
                                values.put(Events.TITLE, c.getString("Subject"));
                                values.put(Events.DESCRIPTION,
                                        c.getString("Descrip"));
                                values.put(Events.EVENT_LOCATION,
                                        c.getString("Location"));
                                values.put(Events.CALENDAR_ID, calID);
                                values.put(Events.EVENT_TIMEZONE,
                                        "America/Los_Angeles");
                                Uri uri = cr.insert(Events.CONTENT_URI, values);
                                Log.e("called", "called");
                            }
                            }

                            leadna_leadTaskaray = leadna_leadSyncCalendar
                                    .getJSONArray("Task");                          
                            if(leadna_leadTaskaray.length()!=0){
                            for (int i = 0; i < leadna_leadTaskaray
                                    .length(); i++) {
                                Log.e("called", "called"+i);
                                JSONObject c = leadna_leadTaskaray
                                        .getJSONObject(i);      
                                String taskDateTime = c.getString("task_date");

                                SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd hh:mm"); // I assume d-M, you may refer to M-d for month-day instead.
                                Date date = formatter1.parse(taskDateTime); // You will need try/catch around this
                                long millis = date.getTime();
                                Log.e("taskDateTime",String.valueOf(millis));
                                long calID = 1;
                                long startMillis = 0;
                                long endMillis = 0;
                                Calendar beginTime = Calendar.getInstance();
                                //beginTime.set();
                                startMillis = millis;
                                Calendar endTime = Calendar.getInstance();
                                /*endTime.set(Integer.parseInt(Date[0]),
                                        Integer.parseInt(Date[1]),
                                        Integer.parseInt(Date[2]),
                                        Integer.parseInt(Time[0]),
                                        Integer.parseInt(Time[1]));*/
                                endMillis = millis;
                                ContentResolver cr = getContentResolver();
                                ContentValues values = new ContentValues();
                                SimpleDateFormat formatter = new SimpleDateFormat(
                                        "dd/MM/yyyy");
                                String dateString = formatter.format(new Date(
                                        startMillis));
                                String edateString = formatter.format(new Date(
                                        startMillis));
                                Log.e("Date", dateString);
                                Log.e("EDate", edateString);
                                values.put(Events.DTSTART, startMillis);
                                values.put(Events.DTEND, endMillis);
                                values.put(Events.TITLE, c.getString("task_title"));
                                values.put(Events.DESCRIPTION,c.getString("task_note"));                                
                                values.put(Events.CALENDAR_ID, calID);
                                values.put(Events.EVENT_TIMEZONE,
                                        "America/Los_Angeles");
                                Uri uri = cr.insert(Events.CONTENT_URI, values);
                                Log.e("called", "called");
                            }
                            }

                            progressdialog.cancel();


                        } catch (Exception e) {

                        }
                    }
                } catch (Exception e) {

                }
            }
        }


        public String getCalendarData() {
            Date date1 = new Date();
            SimpleDateFormat postFormater = new SimpleDateFormat("yyyy-MM-dd");
            String toDate = postFormater.format(date1);
            URLSyncCalendar = URLSyncCalendar + "&today=" + toDate
                    + "&userId=" + LoginActivity.user_id + "&clientId="
                    + LoginActivity.user_client_id;
            System.out.println("URL-->>" + URLSyncCalendar);
            try {
                BufferedReader inStream = null;
                OutputStream out = null;
                HttpURLConnection httpconn = null;
                URI uri = new URI(URLSyncCalendar);
                URL url = uri.toURL();
                httpconn = (HttpURLConnection) url.openConnection();
                httpconn.setDoOutput(true);
                out = httpconn.getOutputStream();
                httpconn.connect();
                out.flush();
                inStream = new BufferedReader(new InputStreamReader(
                        httpconn.getInputStream()));
                if ((response = inStream.readLine()) != null) {

                    try {
                        leadna_leadSyncCalendar = new JSONObject(response);
                    } catch (JSONException e1) { // TODO Auto-generated catch //
                                                    // block
                        e1.printStackTrace();
                    }

                }
                out.close();
                httpconn.disconnect();
            } catch (Exception e) {

            }
            return response;

        }
    }

You definitely should use a Service for this. 您绝对应该为此使用服务 One more thing though. 还有一件事。 Never ever send requests to a server every 30 seconds. 永远不要每30秒将请求发送到服务器。 Imagine there are one million client apps sending requests every 30 seconds. 想象一下,每30秒发送一百万个客户端应用程序发送请求。 Or there are 50 apps installed on a device. 或者设备上安装了50个应用程序。 Be reasonable. 合理一点

I think the best option in your case is to implement a service that does what you need. 我认为您的情况下最好的选择是实施能够满足您需求的服务。

You can read about it here and here . 您可以在这里这里阅读有关它的信息 The links also have example codes inside... 链接中还包含示例代码...

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

相关问题 即使应用程序被销毁,AsyncTask也会一直运行? - AsyncTask will always run even if app is destroyed? 如何处理最小化的应用程序反压? - How to handle minimised app back press? 带计时器的Asynctask。 即使应用程序不在后台运行,它也会运行吗? - Asynctask with timer. Will it run even if the app is not running in the background? 如何使asynctask在后台运行,甚至活动被破坏? - how to make the asynctask run in background even the activity destroyed? 在onResume()中,如何识别是否由于屏幕锁定或应用程序最小化而调用了onPause() - At onResume() how to identify if onPause() was called because of screen lock or app minimised 更新应用程序后,MainApplication 是否会一直运行,即使用户没有打开它? - Will MainApplication always run after updating the app, even if the user does not open it? Android 每次启动应用程序时运行一段代码,但在应用程序最小化和重新打开时不运行 - Android run a piece of code each time the app is started but not when the app is minimised and reopened 如何在 Android 中运行 AsyncTask? - How to run AsyncTask in Android? 如何在AsyncTask中运行ProgressDialog - How to run ProgressDialog in AsyncTask 如何运行多个 AsyncTask? - How to run multiple AsyncTask?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM