2017-09-07 51 views
0

我有一次应用程序停止应发位置, 一个应用程序我重写的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; 
     } 
    } 

,请提前通知 感谢和任何帮助将不胜感激

+0

为什么在服务中使用'AsyncTask'?服务已经在后台运行。 – Yupi

+0

那我应该直接发送请求吗? –

+0

我得到了android.os.NetworkOnMainThreadException –

回答

0

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

+0

感谢您的时间,以及我的活动已经运行了一项服务,我无法在同一活动中运行两项服务? –

+0

哪些服务您使用意向服务或正常服务? –