Skip to content

Instantly share code, notes, and snippets.

public class MyService extends Service {
private static final String TAG = MyService.class.getSimpleName();
private ArrayList<Object> objects;
public MyService() {
}
@Override public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
public class MyIntentService extends IntentService {
private static final String TAG = MyIntentService.class.getSimpleName();
private ArrayList<Object> objects;
private long timeMillisInBackground;
public MyIntentService() {
super("MyIntentService");
}
@Override protected void onHandleIntent(Intent intent) {
<receiver
android:name=".login.NetworkHttpUnauthorizedReceiver">
<intent-filter>
<action android:name="com.startup.network.http_unauthorized"/>
</intent-filter>
</receiver>
public class NetworkHttpUnauthorizedReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
int httpCode = intent.getIntExtra(IntentExtras.HTTP_CODE, -1);
if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
LoginActivity.logOut(context);
}
}
}
int threads = Runtime.getRuntime().availableProcessors();
ExecutorService executor = Executors.newFixedThreadPool(threads);
executor.submit(myWork);
ComponentName service = new ComponentName(this, MyJobService.class);
JobScheduler mJobScheduler = (JobScheduler)getSystemService(Context.JOB_SCHEDULER_SERVICE);
JobInfo.Builder builder = new JobInfo.Builder(jobId, serviceComponent)
.setRequiredNetworkType(jobInfoNetworkType)
.setRequiresCharging(false)
.setRequiresDeviceIdle(false)
.setExtras(extras).build();
mJobScheduler.schedule(jobInfo);
Job myJob = firebaseJobDispatcher.newJobBuilder()
.setService(SmartService.class)
.setTag(SmartService.LOCATION_SMART_JOB)
.setReplaceCurrent(false)
.setConstraints(ON_ANY_NETWORK)
.build();
firebaseJobDispatcher.mustSchedule(myJob);
public class LocationUploadWorker extends Worker {
@Override
public WorkerResult doWork() {
Location location = LocationRepository.getLastLocation();
ServerReport serverReport = new ServerReport(location);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef =
database.getReference("WorkerReport v" + android.os.Build.VERSION.SDK_INT);
myRef.push().setValue(serverReport);
return WorkerResult.SUCCESS;
//Create constraints
Constraints constraints = new Constraints.Builder().setRequiredNetworkType
(NetworkType.CONNECTED).build();
//create work
Work uploadWork = new Work.Builder(LocationUploadWorker.class).withConstraints
(constraints).build();
//schedule work
WorkManager.getInstance(this).enqueue(uploadWork);
WorkManager.getInstance(context).getStatusById(work.getId())
.observe(lifecycleOwner, status -> {
// Do something with the status
if (status != null && status.getState().isFinished()) { … }
});