未触发异步任务

Posted

技术标签:

【中文标题】未触发异步任务【英文标题】: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 线程上运行 是的,据我了解,我怎么能保证触发异步任务? 【参考方案1】:

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

【讨论】:

感谢您的宝贵时间,我的活动已经运行了一项服务,但我无法在同一个活动中运行两项服务? 你使用的是intent服务还是普通服务?

以上是关于未触发异步任务的主要内容,如果未能解决你的问题,请参考以下文章

详解异步任务:函数计算的任务触发去重

CompletableFuture异步编排(两任务组合——两个任务必须都完成才触发另一个任务 )

CompletableFuture异步编排(两任务组合——两个任务必须都完成才触发另一个任务 )

CompletableFuture异步编排(两任务组合——两个任务必须都完成才触发另一个任务 )

什么是 C++ 11 触发异步任务并忘记它的方法?

异步任务未加载数据