简体   繁体   中英

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. i parsed and added the events to android calendar successfully. I used asynctask to do this. But now this process has to run for every 30 seconds even if the app is in minimised state. i surfed and found that we can use thread,aynstask,service,alarm receiver to implement it. but iam not having knowledge in those things.Please help me if anybody knows.

My 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. Imagine there are one million client apps sending requests every 30 seconds. Or there are 50 apps installed on a device. 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...

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