【问题标题】:Async task is not triggered未触发异步任务
【发布时间】:2018-02-16 18:59:03
【问题描述】:

我有一个应用程序停止后应该发送位置, 我覆盖了 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;
        }
    }

请指教 提前感谢,任何帮助将不胜感激

【问题讨论】:

  • 为什么在服务中使用AsyncTask?服务已在后台运行。
  • 那我应该直接发送请求吗?
  • 我得到了 android.os.NetworkOnMainThreadException
  • @Yupi 服务在 UI 线程上运行
  • 是的,据我了解,我怎么能保证触发异步任务?

标签: android service android-asynctask


【解决方案1】:

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

【讨论】:

  • 感谢您的宝贵时间,我的活动已经运行了一项服务,但我无法在同一个活动中运行两项服务?
  • 你使用的是intent服务还是普通服务?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多