未触发异步任务

时间:2017-09-07 23:28:19

标签: android service android-asynctask

我有一个应用程序应该在应用程序停止后发送位置, 我重写onstop方法,它运行完美的服务 但当它到达位置发件人时,这里没有发生任何事情是我的服务代码:

    @Override
    public void onCreate() {
        super.onCreate();
        dbHelper = new DBHelper(this);
        warnniSharedPreference = new WarnniSharedPreference(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LocationSender locationSender = new LocationSender();
        locationSender.execute();
        return android.app.Service.START_NOT_STICKY;
    }
    private class LocationSender extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            if (null != response) {
           dbHelper.deleteAllRecords(DBHelper.LOCATION_TRACKER_TABLE_NAME);
                dbHelper.deleteAllRecords(DBHelper.IMAGES_TABLE_NAME);
            }
        }
        @Override
        protected Void doInBackground(Void... voids) {
            try {
                int start = 0;
                int end = 0;
                ArrayList<WarnniLocation> locationArrayList = dbHelper.getAllLocationRecords();
                int locationGroupSize = (int) Math.ceil((double) locationArrayList.size() / (double) 60);
                for (int i = 0; i < locationGroupSize; i++) {
                    MultipartUtility multipartUtility = new MultipartUtility(Constants.ADD_LOCATION_DATA, "UTF-8");
                    multipartUtility.addFilePart("image", new File(imagesPaths.get(i)));
                    multipartUtility.addFormField("driverId", String.valueOf(warnniSharedPreference.getKey("id")));
                    if (i == 0) {
                        end = 59;
                    } else {
                        end = i * 60 + 59;
                        if (end >= locationArrayList.size()) {
                            end = locationArrayList.size() - 1;
                        }
                    }
                    multipartUtility.addFormField("locations", new Gson().toJson(locationArrayList.subList(start, end)));
                    response = multipartUtility.finish();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }

请指教 在此先感谢,任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

嗨,在服务中使用asynctask没有问题。您需要做的只是使用doin后台方法,因为它在后台运行。但onPostExecute方法在ui线程上运行。所以删除onPostExecute方法。