我的应用程序定位到Android 7,最低限度为Android Android 4。
因此,听CONNECTIVITY_CHANGE
(即使应用程序被杀)也不再有效。我想做的是
我尝试使用以下代码实现
@Override
public void onPause() {
super.onPause();
installJobService();
}
private void installJobService() {
// Create a new dispatcher using the Google Play driver.
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
Job myJob = dispatcher.newJobBuilder()
// the JobService that will be called
.setService(MyJobService.class)
// uniquely identifies the job
.setTag("my-unique-tag")
// one-off job
.setRecurring(true)
// persist forever
.setLifetime(Lifetime.FOREVER)
// start between 0 and 60 seconds from now
.setTrigger(Trigger.executionWindow(0, 60))
// overwrite an existing job with the same tag
.setReplaceCurrent(true)
// retry with exponential backoff
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
// constraints that need to be satisfied for the job to run
.setConstraints(
// only run on any network
Constraint.ON_ANY_NETWORK
)
.build();
dispatcher.mustSchedule(myJob);
}
然而,
import android.content.Context;
import com.firebase.jobdispatcher.JobParameters;
import com.firebase.jobdispatcher.JobService;
import org.yccheok.jstock.gui.JStockApplication;
/**
* Created by yccheok on 21/5/2017.
*/
public class MyJobService extends JobService {
@Override
public boolean onStartJob(JobParameters jobParameters) {
Context context = this.getApplicationContext();
android.util.Log.i("CHEOK", "Internet -> " + Utils.isInternetAvailable(context));
// Answers the question: "Is there still work going on?"
return false;
}
@Override
public boolean onStopJob(JobParameters jobParameters) {
// Answers the question: "Should this job be retried?"
return true;
}
}
但是,上述代码并不可靠。我如何测试
MyJobService
。有没有可靠的方法,使用FirebaseJobDispatcher可靠地替换CONNECTIVITY_CHANGE?
我经历过Firebase JobDispatcher - how does it work compared to previous APIs (JobScheduler and GcmTaskService)?,但我仍然无法找到让它可靠运行的方法。
答案 0 :(得分:0)
不确定您是如何通过FirebaseJobDispatcher检测CONNECTIVITY_CHANGE的,但同样的情况我使用了广播
public class ConnectivityStateReceiver extends BroadcastReceiver {
String TAG = "MyApp";
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, NetworkService.class);
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm == null) {
return;
} else if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
Log.e(TAG, "Connected!");
context.startService(serviceIntent);
} else {
Log.e(TAG, "Not Connected!");
context.stopService(serviceIntent);
}
}
}