我需要在后台从Web Service获取信息,并且此过程必须以指定的间隔重复(例如,每3个小时)。 我使用BroadcastReceiver来确保我有互联网连接。
public class NetworkChangeReceiver extends BroadcastReceiver {
private Context mContext;
private JobScheduler mJobScheduler;
@Override
public void onReceive(final Context context, final Intent intent) {
try {
boolean isVisible = AppController.isActivityVisible();// Check if
Log.i("Activity is Visible ", "Is activity visible : " + isVisible);
// If it is visible then trigger the task else do nothing
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager
.getActiveNetworkInfo();
// Check internet connection and accrding to state change the
// text of activity by calling method
if (networkInfo != null && networkInfo.isConnected()) {
mContext = context;
mJobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
JobInfo.Builder builder = new JobInfo.Builder(1,
new ComponentName(MainActivity.PACKAGE_NAME, Job.class.getName()));
builder.setPeriodic(3000);
builder.build();
if (mJobScheduler.schedule(builder.build()) == JobScheduler.RESULT_FAILURE) {
Log.i("mJobScheduler", "If something goes wrong ");
}
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}}
这是我的JobService类:
public class Job extends JobService {
private static final String TAG = "SyncService";
@Override
public boolean onStartJob(JobParameters params) {
// fake work
Log.i(TAG, "on start job: " + params.getJobId());
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
Log.i(TAG, "on start job: " + params.getJobId());
return true;
}
}
和Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<service
android:name=".Job"
android:exported="true"
android:permission="android.permission.BIND_JOB_SERVICE" />
<receiver
android:name=".NetworkChangeReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
没有错误。 NetworkChangeReceiver类也得到了很好的处理,但Job类没有运行。