Created
December 22, 2016 09:22
-
-
Save talhahasanzia/947a0f5db16a0c039660f8d64f2cb38a to your computer and use it in GitHub Desktop.
Job scheduler snippet from Udacity course: Android Performance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FreeTheWakelockActivity extends ActionBarActivity { | |
public static final String LOG_TAG = "FreeTheWakelockActivity"; | |
TextView mWakeLockMsg; | |
ComponentName mServiceComponent; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_wakelock); | |
mWakeLockMsg = (TextView) findViewById(R.id.wakelock_txt); | |
mServiceComponent = new ComponentName(this, MyJobService.class); | |
Intent startServiceIntent = new Intent(this, MyJobService.class); | |
startService(startServiceIntent); | |
Button theButtonThatWakelocks = (Button) findViewById(R.id.wakelock_poll); | |
theButtonThatWakelocks.setText(R.string.poll_server_button); | |
theButtonThatWakelocks.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View v) { | |
pollServer(); | |
} | |
}); | |
} | |
/** | |
* This method polls the server via the JobScheduler API. By scheduling the job with this API, | |
* your app can be confident it will execute, but without the need for a wake lock. Rather, the | |
* API will take your network jobs and execute them in batch to best take advantage of the | |
* initial network connection cost. | |
* | |
* The JobScheduler API works through a background service. In this sample, we have | |
* a simple service in MyJobService to get you started. The job is scheduled here in | |
* the activity, but the job itself is executed in MyJobService in the startJob() method. For | |
* example, to poll your server, you would create the network connection, send your GET | |
* request, and then process the response all in MyJobService. This allows the JobScheduler API | |
* to invoke your logic without needed to restart your activity. | |
* | |
* For brevity in the sample, we are scheduling the same job several times in quick succession, | |
* but again, try to consider similar tasks occurring over time in your application that can | |
* afford to wait and may benefit from batching. | |
*/ | |
public void pollServer() { | |
JobScheduler scheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE); | |
for (int i=0; i<10; i++) { | |
JobInfo jobInfo = new JobInfo.Builder(i, mServiceComponent) | |
.setMinimumLatency(5000) // 5 seconds | |
.setOverrideDeadline(60000) // 60 seconds (for brevity in the sample) | |
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) // WiFi or data connections | |
.build(); | |
mWakeLockMsg.append("Scheduling job " + i + "!\n"); | |
scheduler.schedule(jobInfo); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyJobService extends JobService { | |
private static final String LOG_TAG = "MyJobService"; | |
@Override | |
public void onCreate() { | |
super.onCreate(); | |
Log.i(LOG_TAG, "MyJobService created"); | |
} | |
@Override | |
public void onDestroy() { | |
super.onDestroy(); | |
Log.i(LOG_TAG, "MyJobService destroyed"); | |
} | |
@Override | |
public boolean onStartJob(JobParameters params) { | |
// This is where you would implement all of the logic for your job. Note that this runs | |
// on the main thread, so you will want to use a separate thread for asynchronous work | |
// (as we demonstrate below to establish a network connection). | |
// If you use a separate thread, return true to indicate that you need a "reschedule" to | |
// return to the job at some point in the future to finish processing the work. Otherwise, | |
// return false when finished. | |
Log.i(LOG_TAG, "Totally and completely working on job " + params.getJobId()); | |
// First, check the network, and then attempt to connect. | |
if (isNetworkConnected()) { | |
new SimpleDownloadTask() .execute(params); | |
return true; | |
} else { | |
Log.i(LOG_TAG, "No connection on job " + params.getJobId() + "; sad face"); | |
} | |
return false; | |
} | |
@Override | |
public boolean onStopJob(JobParameters params) { | |
// Called if the job must be stopped before jobFinished() has been called. This may | |
// happen if the requirements are no longer being met, such as the user no longer | |
// connecting to WiFi, or the device no longer being idle. Use this callback to resolve | |
// anything that may cause your application to misbehave from the job being halted. | |
// Return true if the job should be rescheduled based on the retry criteria specified | |
// when the job was created or return false to drop the job. Regardless of the value | |
// returned, your job must stop executing. | |
Log.i(LOG_TAG, "Whelp, something changed, so I'm calling it on job " + params.getJobId()); | |
return false; | |
} | |
/** | |
* Determines if the device is currently online. | |
*/ | |
private boolean isNetworkConnected() { | |
ConnectivityManager connectivityManager = | |
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); | |
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); | |
return (networkInfo != null && networkInfo.isConnected()); | |
} | |
/** | |
* Uses AsyncTask to create a task away from the main UI thread. This task creates a | |
* HTTPUrlConnection, and then downloads the contents of the webpage as an InputStream. | |
* The InputStream is then converted to a String, which is logged by the | |
* onPostExecute() method. | |
*/ | |
private class SimpleDownloadTask extends AsyncTask<JobParameters, Void, String> { | |
protected JobParameters mJobParam; | |
@Override | |
protected String doInBackground(JobParameters... params) { | |
// cache system provided job requirements | |
mJobParam = params[0]; | |
try { | |
InputStream is = null; | |
// Only display the first 50 characters of the retrieved web page content. | |
int len = 50; | |
URL url = new URL("https://www.google.com"); | |
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); | |
conn.setReadTimeout(10000); //10sec | |
conn.setConnectTimeout(15000); //15sec | |
conn.setRequestMethod("GET"); | |
//Starts the query | |
conn.connect(); | |
int response = conn.getResponseCode(); | |
Log.d(LOG_TAG, "The response is: " + response); | |
is = conn.getInputStream(); | |
// Convert the input stream to a string | |
Reader reader = null; | |
reader = new InputStreamReader(is, "UTF-8"); | |
char[] buffer = new char[len]; | |
reader.read(buffer); | |
return new String(buffer); | |
} catch (IOException e) { | |
return "Unable to retrieve web page."; | |
} | |
} | |
@Override | |
protected void onPostExecute(String result) { | |
jobFinished(mJobParam, false); | |
Log.i(LOG_TAG, result); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment