// It is very easy to subscribe to changes to the battery state, but you can get the current// state by simply passing null in as your receiver. Nifty, isn't that?IntentFilterfilter=newIntentFilter(Intent.ACTION_BATTERY_CHANGED);IntentbatteryStatus=this.registerReceiver(null,filter);intchargePlug=batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED,-1);booleanacCharge=(chargePlug==BatteryManager.BATTERY_PLUGGED_AC);if(acCharge){Log.v(LOG_TAG,“Thephoneischarging!”);}
/** * This method checks for power by comparing the current battery state against all possible * plugged in states. In this case, a device may be considered plugged in either by USB, AC, or * wireless charge. (Wireless charge was introduced in API Level 17.) */privatebooleancheckForPower(){// It is very easy to subscribe to changes to the battery state, but you can get the current// state by simply passing null in as your receiver. Nifty, isn't that?IntentFilterfilter=newIntentFilter(Intent.ACTION_BATTERY_CHANGED);IntentbatteryStatus=this.registerReceiver(null,filter);// There are currently three ways a device can be plugged in. We should check them all.intchargePlug=batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED,-1);booleanusbCharge=(chargePlug==BatteryManager.BATTERY_PLUGGED_USB);booleanacCharge=(chargePlug==BatteryManager.BATTERY_PLUGGED_AC);booleanwirelessCharge=false;if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN_MR1){wirelessCharge=(chargePlug==BatteryManager.BATTERY_PLUGGED_WIRELESS);}return(usbCharge||acCharge||wirelessCharge);}
publicclassMyJobServiceextendsJobService{privatestaticfinalStringLOG_TAG="MyJobService";@OverridepublicvoidonCreate(){super.onCreate();Log.i(LOG_TAG,"MyJobService created");}@OverridepublicvoidonDestroy(){super.onDestroy();Log.i(LOG_TAG,"MyJobService destroyed");}@OverridepublicbooleanonStartJob(JobParametersparams){// 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()){newSimpleDownloadTask().execute(params);returntrue;}else{Log.i(LOG_TAG,"No connection on job "+params.getJobId()+"; sad face");}returnfalse;}@OverridepublicbooleanonStopJob(JobParametersparams){// 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());returnfalse;}/** * Determines if the device is currently online. */privatebooleanisNetworkConnected(){ConnectivityManagerconnectivityManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfonetworkInfo=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. */privateclassSimpleDownloadTaskextendsAsyncTask<JobParameters,Void,String>{protectedJobParametersmJobParam;@OverrideprotectedStringdoInBackground(JobParameters...params){// cache system provided job requirementsmJobParam=params[0];try{InputStreamis=null;// Only display the first 50 characters of the retrieved web page content.intlen=50;URLurl=newURL("https://www.google.com");HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setReadTimeout(10000);//10secconn.setConnectTimeout(15000);//15secconn.setRequestMethod("GET");//Starts the queryconn.connect();intresponse=conn.getResponseCode();Log.d(LOG_TAG,"The response is: "+response);is=conn.getInputStream();// Convert the input stream to a stringReaderreader=null;reader=newInputStreamReader(is,"UTF-8");char[]buffer=newchar[len];reader.read(buffer);returnnewString(buffer);}catch(IOExceptione){return"Unable to retrieve web page.";}}@OverrideprotectedvoidonPostExecute(Stringresult){jobFinished(mJobParam,false);Log.i(LOG_TAG,result);}}}
publicclassFreeTheWakelockActivityextendsActionBarActivity{publicstaticfinalStringLOG_TAG="FreeTheWakelockActivity";TextViewmWakeLockMsg;ComponentNamemServiceComponent;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_wakelock);mWakeLockMsg=(TextView)findViewById(R.id.wakelock_txt);mServiceComponent=newComponentName(this,MyJobService.class);IntentstartServiceIntent=newIntent(this,MyJobService.class);startService(startServiceIntent);ButtontheButtonThatWakelocks=(Button)findViewById(R.id.wakelock_poll);theButtonThatWakelocks.setText(R.string.poll_server_button);theButtonThatWakelocks.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){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. */publicvoidpollServer(){JobSchedulerscheduler=(JobScheduler)getSystemService(Context.JOB_SCHEDULER_SERVICE);for(inti=0;i<10;i++){JobInfojobInfo=newJobInfo.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);}}}