Issue
Ok I am using JobScheduler to sync data with a database. I know you can set requirements in JobScheduler to run a job like unmetered network etc etc, but the problem is Jobscheduler doesnt checks if internet is working it just checks if you are connected to a network. I have 1 Job which is periodic that has several task. I created this aync task that checks if there is internet . I want to check if the http response (StatusCode)is not equal to 200 . I want to stop the job immediately and reschedule again. Because if Internet is not working I dont need to continue run the job. I cant figure out how to stop the job immediately and reschedule because after that async task is finished the next one begin to execute.
Here is my OnStartJob and OnStopJob
@Override
public boolean onStartJob(JobParameters jobParameters) {
Log.d(TAG, "onStartJob");
new ConnectCheck(getApplicationContext(), this, jobParameters).execute();
getRetrofitObject();
myLocation();
new MyToken(getApplicationContext(), this, jobParameters).execute();
Document newMemo = new Document();
new MyWorker(getApplicationContext(), this, jobParameters).execute(newMemo);
return true;
}
@Override
public boolean onStopJob(JobParameters jobParameters) {
Log.d(TAG, "onStopJob");
return true;
}
Here is my Async Task
private static class ConnectCheck extends AsyncTask<Void, Void, Boolean> {
private final Context mContext;
private final MyJobService mJobService;
private final JobParameters mJobParams;
public ConnectCheck(Context context, MyJobService myJobService, JobParameters jobParameters) {
mContext = context;
mJobService = myJobService;
mJobParams = jobParameters;
}
@Override
protected Boolean doInBackground(Void... voids) {
Log.d(TAG, "Connect Check start!");
int statusCode = 0;
URL url = null;
try {
url = new URL("http://google.com/");
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection http = null;
try {
http = (HttpURLConnection)url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
statusCode = http.getResponseCode();
Log.d(TAG, "" +statusCode);
} catch (IOException e) {
e.printStackTrace();
}
if(statusCode!=200)
{
// reschedule a jobscheduler
Log.d(TAG, "reschedule job");
mJobService.jobFinished(mJobParams, true);
}
return false;
}
@Override
public void onPostExecute(Boolean reschedule) {
if (reschedule) {
mJobService.jobFinished(mJobParams, true);
} else {
mJobService.jobFinished(mJobParams, false);
}
Log.d(TAG, "ConnectCheck finsished ------------------------");
}
}
Solution
What you are doing is almost on the right path.
Remember, of the internet isn't working, the connection will time out and throw an ioexception. When it does, just set your reschedule Boolean to true and your code should call
jobFinished(yourparams,rescheduletrue)
Answered By - Kushan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.