我在 JobService 中使用 Volley 向服务器发送请求。我的问题是,由于服务在主线程上运行,我应该在服务内创建一个单独的线程并在那里调用我的 Volley 请求,还是简单地调用 volley 请求?这是我的一些代码。
public class JobService extends android.app.job.JobService {
static int count = 0;
@Override
public boolean onStartJob(final JobParameters jobParameters) {
Log.d("Job Service", "onStartJob " + count);
final SharedPreferences prefs = getSharedPreferences(LOGIN_PREFS, MODE_PRIVATE);
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("Job Service", "onResponse");
try {
writeFileToCache(response);
jobFinished(jobParameters, true);
} catch (Exception e) {
e.printStackTrace();
jobFinished(jobParameters, true);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Volley error job", error.toString());
jobFinished(jobParameters, true);
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
params.put("regno", prefs.getString(REG_NO, ""));
params.put("bdate", prefs.getString(DATE_OF_BIRTH, ""));
return params;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(12000, 0, 0f));
queue.add(request);
return true;
}
private void writeFileToCache(String response) throws IOException {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
return;
}
File file = new File(getExternalCacheDir() + CACHE_FILE);
FileOutputStream fout = new FileOutputStream(file);
Log.d("Writing to cache job", response);
fout.write(response.getBytes());
fout.close();
}
@Override
public boolean onStopJob(JobParameters jobParameters) {
Log.d("Job Service", "onStopJob");
return false;
}