服务试图使用Volley库来处理请求响应但是回调永远不会被调用

时间:2016-09-27 20:21:19

标签: android android-service android-volley

VolleyRequest内未正确处理Service

public class StatusService extends Service {
  private static final String TAG = StatusService.class.getSimpleName();

  @Override
  public void onStart(Intent intent, int startId) {
    // check the global background data setting
    ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    if (!cm.getBackgroundDataSetting()) {
      stopSelf();
      return;
    }

    RequestQueue mRequestQueue;
    { // setup mRequestQueue
      // Instantiate the cache
      Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap

      // Set up the network to use HttpURLConnection as the HTTP client.
      Network network = new BasicNetwork(new HurlStack());

      // Instantiate the RequestQueue with the cache and network.
      mRequestQueue = new RequestQueue(cache, network);

      // Start the queue
      mRequestQueue.start();
    }

    // do the actual work, in a separate thread
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, "http://mydomain/something", null, new Response.Listener<JSONObject>() {
      @Override
      public void onResponse(JSONObject response) {
        // I am sure the server side is working properly
        Log.d(TAG, "This never gets called! -> On response: " + response);
      }
    }, new Response.ErrorListener() {
      @Override
      public void onErrorResponse(VolleyError error) {
        Log.e(TAG, "error", error);
      }
    });
    mRequestQueue.add(request);
    Log.d(TAG, "This will be logged successfully");
  }

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    handleIntent(intent);
    return START_NOT_STICKY;
  }
}

请求已发送,但提供的回调操作未被调用。当服务器关闭时,将使用TimeOutError调用错误回调。这是线程问题吗?如果是的话,可能出现什么问题?

1 个答案:

答案 0 :(得分:0)

不太确定为什么要打电话而不打另一个。但是根据文档,即使这可能与您的问题完全无关,也会在主线程上调用回调。