如何在app最小化状态下始终运行asynctask?

时间:2014-06-10 16:02:02

标签: android service android-asynctask

您好我已经在android中完成了一个进程,该进程将调用包含日历事件的Web服务。我解析并成功将事件添加到android日历。我使用asynctask来做到这一点。但是现在这个过程必须每30秒运行一次,即使应用程序处于最小化状态。我冲浪,发现我们可以使用线程,aynstask,服务,报警接收器来实现它。但我对这些事情没有了解。如果有人知道,请帮助我。

我的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;

        }
    }

2 个答案:

答案 0 :(得分:5)

你绝对应该使用Service。 还有一件事。永远不会每30秒向服务器发送一次请求。想象一下,每30秒就有一百万个客户端应用发送请求。或者设备上安装了50个应用程序。合理。

答案 1 :(得分:0)

我认为您的最佳选择是实施满足您需求的服务。

您可以阅读herehere。 这些链接里面还有示例代码......