firebase-jobdispatcher-android | DEPRECATED please see the README.md below for details | Image Editing library
kandi X-RAY | firebase-jobdispatcher-android Summary
Support
Quality
Security
License
Reuse
- Handle start command
- Extract the IBinder information from the Bundle
- Decodes the job invocation
- Executes the given job
- Handle the incoming message
- Handle a start execution message
- Handles a stop execution message
- Sends a job finish
- Called when a service is connected
- Called when a job is finished
- Processes the job finished message
- Checks if the given JobInvocation matches the given JobInvocation
- Handle the onUnbind event
- Registers a job
- Handles a stop job request
- Compares this object to another object
- Starts a job
- Stops a job
firebase-jobdispatcher-android Key Features
firebase-jobdispatcher-android Examples and Code Snippets
Trending Discussions on firebase-jobdispatcher-android
Trending Discussions on firebase-jobdispatcher-android
QUESTION
Why do we need the new Android WorkManager if we already have a JobScheduler along with a few nifty backports (AndroidJob and FirebaseJobDispatcher) with the same functionality? Does it have any killer-features or something? Because I don't see anything that makes me want to migrate to the yet another scheduler.
ANSWER
Answered 2018-May-10 at 23:49WorkManager just seems like Google's answer to Evernote's Android-Job library, but with a few improvements. It uses JobScheduler, Firebase JobDispatcher and AlarmManager just like Android-Job depending on the device's API level. Their usage of tags looks pretty much the same and assigning constraints to jobs/work are similar enough.
The two features that I am excited about are: being able to chain work and the ability to be opportunistic on work with constraints. The first will allow work (jobs) to be broken up and more modular for me. And with more modular work, each piece of work may have fewer constraints improving the chance they will complete earlier (opportunistic). For example, the majority of processing work can complete before the work with a network constraint needs to be met.
So if you're happy with your current scheduler implementation and the two features I mentioned don't add value, I don't see a huge benefit to making the switch just yet. But if you're writing something new, it'll probably be worth it to use WorkManager.
QUESTION
So per the documentation Firebase JobDispatcher is deprecated and should be migrated to use the WorkManager. I was following the migration guide which said the functionality implemented in a JobService should be migrated to a ListenableWorker. However I am stumped on how to implement startWork()
, the guide only says
override fun startWork(): ListenableFuture {
// Do your work here.
TODO("Return a ListenableFuture")
}
I have done a lot of googling but i have not been able to figure out how to implement/use the ListenableFuture in this context to implement the functionality of the JobService, where I called jobFinished
and returned a Boolean value to represent if work was still going on. Any help is appreciated
ANSWER
Answered 2019-May-17 at 09:37You need to use ListenableWorker if you need to execute asynchronous code. There's a Threading in ListenableWorker documentation page that covers this:
If you wanted to execute some work based on an asynchronous callback, you would do something like this:
public class CallbackWorker extends ListenableWorker {
public CallbackWorker(Context context, WorkerParameters params) {
super(context, params);
}
@NonNull
@Override
public ListenableFuture startWork() {
return CallbackToFutureAdapter.getFuture(completer -> {
Callback callback = new Callback() {
int successes = 0;
@Override
public void onFailure(Call call, IOException e) {
completer.setException(e);
}
@Override
public void onResponse(Call call, Response response) {
++successes;
if (successes == 100) {
completer.set(Result.success());
}
}
};
for (int i = 0; i < 100; ++i) {
downloadAsynchronously("https://www.google.com", callback);
}
return callback;
});
}
}
A simpler alternative, if you're using kotlin, is to use a CoroutineWorker
class.
If what you need to execute is synchronous, using a Worker
class is probably simpler and enough for your use case. This is documented in Threading in Worker.
QUESTION
i have to download json response from web server on every night,previously i have used AlarmManager
for scheduling tasks but i think for this kind of situation JobDispatcher
is great because it auto perform task if network available so i don't have to manage this kind of stuf.But i have found many examples of JobDispatcher
and JobScheduler
in all of them a simple job is scheduled or scheduled for some time delay but there is nothing relevant to my requirements, if anyone have idea of this please help or provide any link related to this, it will be very helpful.
UPDATE
1. How to make this to work every night,because currently it is only set alarm to midnight for once , how to make it repeted for every night at same time ?
ANSWER
Answered 2017-Oct-11 at 09:04This is how you need to schedule time-based jobs
FirebaseJobDispatcher jobDispatcher = new FirebaseJobDispatcher(
new GooglePlayDriver(this));
Calendar now = Calendar.getInstance();
Calendar midNight = Calendar.getInstance();
midNight.set(Calendar.HOUR, 12);
midNight.set(Calendar.MINUTE, 0);
midNight.set(Calendar.SECOND, 0);
midNight.set(Calendar.MILLISECOND, 0);
midNight.set(Calendar.AM_PM, Calendar.AM);
long diff = now.getTimeInMillis() - midNight.getTimeInMillis();
if (diff < 0) {
midNight.add(Calendar.DAY_OF_MONTH, 1);
diff = midNight.getTimeInMillis() - now.getTimeInMillis();
}
int startSeconds = (int) (diff / 1000); // tell the start seconds
int endSencods = startSeconds + 300; // within Five minutes
Job networkJob = jobDispatcher.newJobBuilder()
.setService(NetworkJob.class)
.setTag(NetworkJob.ID_TAG)
.setRecurring(true)
.setTrigger(Trigger.executionWindow(startSeconds, endSencods))
.setLifetime(Lifetime.FOREVER)
.setReplaceCurrent(true)
.setConstraints(Constraint.ON_ANY_NETWORK)
.build();
jobDispatcher.schedule(networkJob);
QUESTION
As From Firebase JobDispatcher Documentation Firebase JobDispatcher
setTrigger(Trigger.executionWindow(0, 60))
// start between 0 and 60 seconds
but why my sevice running two time
Firebase JobDispacther Code
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
Job job = dispatcher.newJobBuilder()
.setTag("testing job")
.setService(TestingJob.class)
.setReplaceCurrent(true)
.setRecurring(true)
.setTrigger(Trigger.executionWindow(0,1))
.setConstraints(Constraint.ON_ANY_NETWORK)
.setLifetime(Lifetime.FOREVER)
.build();
dispatcher.mustSchedule(job);
Testing class (Job Service)
public class TestingJob extends JobService {
private static final String TAG = "TestingJob";
private int i =0;
@Override
public boolean onStartJob(JobParameters job) {
Log.d(TAG, "onStartJob Testing Job: "+new Date().toString());
Log.d(TAG, "onStartJob: i = "+String.valueOf(i));
i+=1;
return false;
}
@Override
public boolean onStopJob(JobParameters job) {
Log.d(TAG, "onStopJob Testing Job: Stopped");
return false;
}
}
Log Cat
11-28 00:08:57.666 11793-11793: onStartJob Testing Job: Tue Nov 28 00:08:57 GMT+05:00 2017
11-28 00:08:57.666 11793-11793: onStartJob: i = 0
11-28 00:08:57.791 11793-11793: onStartJob Testing Job: Tue Nov 28 00:08:57 GMT+05:00 2017
11-28 00:08:57.791 11793-11793: onStartJob: i = 0
Manifest
Can i use my Job Service Again mean int i
should increment every time.
Thnx For Your Help
ANSWER
Answered 2017-Nov-29 at 14:27I think the reason why it runs 2 times is your execution window.
.setTrigger(Trigger.executionWindow(0,1))
There is only a 1 second time window. Try with a broader interval, like (0, 60)
, that should do the trick.
To answer your other question about your variable i
, you have to make it static:
private static int i = 0;
QUESTION
In an Android app (with minSdkVersion 16
) I use the nv-websocket-client library:
public class MainActivity extends AppCompatActivity {
private WebSocket mWs;
private WebSocketFactory mWsFactory = new WebSocketFactory();
private WebSocketListener mWsListener = new WebSocketAdapter() {
@Override
public void onConnected(WebSocket ws, Map> headers) throws Exception {
mReconnectDispatcher.cancelAll();
}
// connection on the background thread has failed (onDisconnected will not be called!)
@Override
public void onConnectError(WebSocket ws, WebSocketException ex) throws Exception {
reconnect();
}
@Override
public void onDisconnected(WebSocket ws,
WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame,
boolean closedByServer) throws Exception {
reconnect();
}
@Override
public void onTextMessage(WebSocket ws, String str) throws Exception {
// here the WebSockets communication happens
}
};
@Override
public void onResume() {
super.onResume();
reconnect();
}
@Override
public void onPause() {
super.onPause();
if (mWs != null) {
mWs.disconnect();
}
}
And Firebase JobDispatcher (version 0.8.4) for reconnecting the WebSocket:
private FirebaseJobDispatcher mReconnectDispatcher;
public class ReconnectService extends JobService {
@Override
public boolean onStartJob(JobParameters job) {
try {
mWs = mWsFactory.createSocket("ws://demos.kaazing.com/echo");
mWs.addListener(mWsListener);
mWs.connectAsynchronously(); // uses background thread
} catch (Exception ex) {
Log.w(TAG, "Can not create WebSocket connection", ex);
}
return true; // Answers the question: "Is there still work going on?"
}
@Override
public boolean onStopJob(JobParameters job) {
return false; // Answers the question: "Should this job be retried?"
}
}
private void reconnect() {
Job myJob = mReconnectDispatcher.newJobBuilder()
.setService(ReconnectService.class)
.setTag(ReconnectService.class.getSimpleName())
.setRecurring(false)
.setLifetime(Lifetime.UNTIL_NEXT_BOOT)
.setTrigger(Trigger.executionWindow(0, 60))
.setReplaceCurrent(true)
.setConstraints(Constraint.ON_ANY_NETWORK)
.build();
mReconnectDispatcher.mustSchedule(myJob);
}
And in AndroidManifest.xml I have:
Unfortunately, I get the runtime error after 60 seconds:
16998-16998/de.slova E/AndroidRuntime: FATAL EXCEPTION: main
Process: de.slova, PID: 16998
java.lang.RuntimeException: Unable to instantiate service de.slova.MainActivity$ReconnectService: java.lang.InstantiationException: java.lang.Class has no zero argument constructor
at android.app.ActivityThread.handleCreateService(ActivityThread.java:3389)
at android.app.ActivityThread.-wrap4(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1683)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.InstantiationException: java.lang.Class has no zero argument constructor
at java.lang.Class.newInstance(Native Method)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:3386)
at android.app.ActivityThread.-wrap4(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1683)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
1472-1487/? I/ActivityManager: Showing crash dialog for package de.slova u0
I have tried adding a default constructor to my class, but the error persists:
public class ReconnectService extends JobService {
public ReconnectService() {
}
Does anybody please have an idea, what is wrong here?
I have also submitted my problem as issue #189.
ANSWER
Answered 2017-Nov-19 at 17:30Put ReconnectService
in its own class (not an inner class to MainActivity
). Alternatively, try making the inner class static
.
The way non-static inner classes work in Java is that they can only be instantiated by an instance of the outer class. This is what allows instances of the inner class to access members of the outer class. So, when Android is trying to create an instance of the inner class, it can't do so because it doesn't know what instance of the outer class it should be a part of. The error message is a bit misleading.
QUESTION
I am using Firebase Job Dispatcher and setting it up like described in https://github.com/firebase/firebase-jobdispatcher-android/blob/master/README.md.
The job to be scheduled is a http request. The http request could run while the app is on the foreground (the user is looking at it), or while the app is in the background/not started.
Should the http request (using the okhttp library) be put in a separate thread / asynchronous or can I just call it directly from the JobService?
ANSWER
Answered 2017-Oct-02 at 08:45JobService
extends Service
so it runs on the main thread. Therefore, you shouldn't be able to make network calls directly. However, there is SimpleJobService
where you can make direct calls.
I think using SimpleJobService
is better than using AsyncTask
within JobService
because it already does it in its own way as you can see here.
QUESTION
I have an app that to displays new data in a notification. This data is provided by a network device. I can query this device and compare it the cached data in my service to determine if the notification needs to be updated. My app has a service that has local variables in which it caches the data. If the device has newer data, I present that in a notification to the user. Now I started to get IllegalStateException because Android O doesn't allow startService() gets called when the app is in background mode. I know I can start the service in Foreground mode, but since Android is providing less resource intensive ways, I would like to try something new. Next to the data being cached in local variables it gets stored in Firebase Database.
My requirements:
- Check every 10 seconds (if the screen is on) if there's new data
- Check if there's new data when the screen is switched on
- If there is new data, update the notification
- Needs to be long running and be able to compare new data to old (cached or from firebase) data.
- Can run when the app is in background mode
My thoughts: I've looked at Firebase job-dispatcher (https://github.com/firebase/firebase-jobdispatcher-android#user-content-firebase-jobdispatcher-). Maybe I can configure it to run every time the screen is switched on, and every 10 seconds, to retrieve the new data from the network device and match that up with the data in Firebase database. But maybe it will cost a lot of performance to query the database that often.
ANSWER
Answered 2017-Sep-28 at 12:48Try Object based Database like Realm, SnappyDB(Uber uses it) etc. Queries are super fast
QUESTION
I am trying to add Firebase Job Dispatcher to my project, but I am unable to build because of this error:
Gradle sync failed: Could not find com.firebase:firebase-jobdispatcher:[version]. Required by: project :[module]
My build.gradle
file looks like this:
apply plugin: 'com.android.application'
apply plugin: 'android-apt'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
minSdkVersion 16
targetSdkVersion 25
versionCode 2
versionName "1.0.1"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
zipAlignEnabled true
}
}
}
repositories {
mavenCentral()
maven {url "https://clojars.org/repo/"}
}
dependencies {
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
compile 'com.firebase:firebase-jobdispatcher:0.5.2'
compile 'com.facebook.stetho:stetho:1.4.2'
compile 'com.jakewharton:butterknife:8.4.0'
apt 'com.jakewharton:butterknife-compiler:8.4.0'
compile 'frankiesardo:icepick:3.2.0'
provided 'frankiesardo:icepick-processor:3.2.0'
compile 'org.greenrobot:eventbus:3.0.0'
compile 'com.android.support:appcompat-v7:25.3.0'
compile 'com.android.support:design:25.3.0'
compile 'com.android.support:support-v13:25.3.0'
compile 'com.google.code.gson:gson:2.7'
compile fileTree(dir: 'libs', include: ['*.jar'])
compile files('libs/volley.jar')
}
Additionally, I have version 45 of the Google Repository and version 39 of Google Play Services installed via the SDK manager.
According to the documentation on the firebase-jobdispatcher Github page, this should be the only thing I need to add the dependency. My project does not rely on GCM, so I'm not sure what is going on. Is there something I'm missing here?
ANSWER
Answered 2017-Apr-02 at 03:22Apparently, Gradle could not resolve the dependency using Maven Central alone. Adding JCenter to my list of repositories fixed the issue:
repositories {
jcenter() // new
mavenCentral()
maven {url "https://clojars.org/repo/"}
}
QUESTION
I have implemented job scheduling using Firebase job dispatcher. In which it was given in the doc that an IntentFilter
with a specific action Action
should be added to the job service as below
What is the use of the adding the above IntentFilter
while the jobscheduling is working fine even without that
ANSWER
Answered 2017-Mar-14 at 19:37An intent filter specifies the types of intents that an activity, service, or broadcast receiver can respond to. It allows service to start when it receives intent of specific type while ignoring others which are not meaningful for the service. So, if you are NOT specifying intent filter jobscheduling will work but there is no restriction on the service for the type of intent it should respond to.
Intents sends signals to the Android system telling it that some action needs to be performed by another component in the same app or a different app.
So, when you have scheduled job and added intent filter ,your service will respond to event with action com.firebase.jobdispatcher.ACTION_EXECUTE
only.
QUESTION
I would like to know if it's possible to use Firebase jobdispatcher to schedule an url hit and get the response in order to update the db. I would like it to run once per day at night. Does anyone know if this is possible?
I can't find any good example of doing this. I already read android documentation and https://github.com/firebase/firebase-jobdispatcher-android#user-content-firebase-jobdispatcher- .
I need to use Firebase jobdispatcher because I'm targeting API 16.
Thanks in advance.
UPDATE
This is what I did to schedule it once per day.
final int periodicity = (int) TimeUnit.HOURS.toSeconds(24);
final int toleranceInterval = (int) TimeUnit.HOURS.toSeconds(1);
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
Job job = dispatcher.newJobBuilder()
.setService(UpdateTVJobService.class)
.setTag(JOB_TAG)
.setTrigger(Trigger.executionWindow(periodicity, periodicity + toleranceInterval))
.setLifetime(Lifetime.FOREVER)
.setRecurring(true)
.setReplaceCurrent(true)
.build();
int result = dispatcher.schedule(job);
if (result != FirebaseJobDispatcher.SCHEDULE_RESULT_SUCCESS) {
Log.d("JOB_TAG", "ERROR ON SCHEDULE");
}
ANSWER
Answered 2017-Feb-02 at 03:47You can schedule a recurring job by telling the Job.Builder to create a recurring job with a Trigger that has an execution window according to your needs.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install firebase-jobdispatcher-android
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page