android - 即使在应用程序最小化状态下,如何始终运行 asynctask?

标签 android service android-asynctask

您好,我已经在 Android 中完成了一个进程,该进程将调用包含日历事件的网络服务。我已成功解析事件并将其添加到 android 日历中。我使用 asynctask 来做到这一点。但是现在即使应用程序处于最小化状态,这个过程也必须每 30 秒运行一次。我上网发现我们可以使用thread,aynstask,service,alarm receiver来实现。但我对这些事情一无所知。如果有人知道,请帮助我。

我的异步任务:

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;

        }
    }

最佳答案

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

关于android - 即使在应用程序最小化状态下,如何始终运行 asynctask?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24145705/

相关文章:

android - 如何实现一个水平滚动的倒数计时器?

javascript - 如何通过注入(inject) javascript 更改 android webview 中的样式?

http - 当服务不可用时,如何在 JMeter 中测试 http 请求

android - RecyclerView 适配器内部的 AsyncTask,如何同步?

android - 从 Android 应用程序调用 Web 服务

android - ScrollView 内的 RelativeLayout 不滚动。我做错了什么?

android - 如何不打开已通过最近的应用程序完成的 Activity

objective-c - 通过 Cocoa Touch 访问亚马逊电子商务服务

java - 线程等待一组异步任务完成

java - HttpURLConnection.getInputStream() 挂起并且永远不会完成