android l job scheduler api,Android JobScheduler API

本文讨论了在Android JobService中,如何合理安排在主线程还是子线程执行Volley网络请求的问题,作者提供了在JobService内部启动请求并处理响应的代码实例,着重于避免阻塞主线程和权限管理。
摘要由CSDN通过智能技术生成

I am sending a request to a server using Volley in a JobService. My question is, since the service runs on the main thread, should I create a seperate thread inside the service and call my Volley request there, or simple call the volley request? Here is some of my code.

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() {

@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 getParams() throws AuthFailureError {

HashMap 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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值