我是第一次与Work Manager合作,并且已经成功实施。
我每30分钟要去一次位置以跟踪员工。
当数据库第一次同步时,我已经启动了工作管理器,但是我想每天晚上都要停止它。
这里是MyWorker.java
public class MyWorker extends Worker {
private static final String TAG = "MyWorker";
/**
* The desired interval for location updates. Inexact. Updates may be more or less frequent.
*/
private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
/**
* The fastest rate for active location updates. Updates will never be more frequent
* than this value.
*/
private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
UPDATE_INTERVAL_IN_MILLISECONDS / 2;
/**
* The current location.
*/
private Location mLocation;
/**
* Provides access to the Fused Location Provider API.
*/
private FusedLocationProviderClient mFusedLocationClient;
private Context mContext;
private String fromRegRegCode, fromRegMobile, fromRegGUID, fromRegImei, clientIP;
/**
* Callback for changes in location.
*/
private LocationCallback mLocationCallback;
public MyWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
mContext = context;
}
@NonNull
@Override
public Result doWork() {
Log.d(TAG, "doWork: Done");
//mContext.startService(new Intent(mContext, LocationUpdatesService.class));
Log.d(TAG, "onStartJob: STARTING JOB..");
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(mContext);
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
}
};
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
try {
mFusedLocationClient
.getLastLocation()
.addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
if (task.isSuccessful() && task.getResult() != null) {
mLocation = task.getResult();
String currentTime = CommonUses.getDateToStoreInLocation();
String mLatitude = String.valueOf(mLocation.getLatitude());
String mLongitude = String.valueOf(mLocation.getLongitude());
LocationHistoryTable table = new LocationHistoryTable();
table.setLatitude(mLatitude);
table.setLongitude(mLongitude);
table.setUpdateTime(currentTime);
table.setIsUploaded(CommonUses.PENDING);
LocationHistoryTableDao tableDao = SohamApplication.daoSession.getLocationHistoryTableDao();
tableDao.insert(table);
Log.d(TAG, "Location : " + mLocation);
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
/**
* Upload on server if network available
*/
if (Util.isNetworkAvailable(mContext)) {
checkForServerIsUP();
}
} else {
Log.w(TAG, "Failed to get location.");
}
}
});
} catch (SecurityException unlikely) {
Log.e(TAG, "Lost location permission." + unlikely);
}
try {
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
null);
} catch (SecurityException unlikely) {
//Utils.setRequestingLocationUpdates(this, false);
Log.e(TAG, "Lost location permission. Could not request updates. " + unlikely);
}
return Result.success();
}
}
启动工作者代码:
PeriodicWorkRequest periodicWork = new PeriodicWorkRequest.Builder(MyWorker.class, repeatInterval, TimeUnit.MINUTES)
.addTag("Location")
.build();
WorkManager.getInstance().enqueueUniquePeriodicWork("Location", ExistingPeriodicWorkPolicy.REPLACE, periodicWork);
每天晚上有什么特别的方法可以阻止它吗?
您的帮助将不胜感激。
您无法在一段时间内停止Workmanager。
这里是技巧,只需在doWork()
方法中添加此条件
基本上,您需要检查当前时间,即是晚上还是晚上,如果是,则不执行任务。
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
if(timeOfDay >= 16 && timeOfDay < 21){
// this condition for evening time and call return here
return Result.success();
}
else if(timeOfDay >= 21 && timeOfDay < 24){
// this condition for night time and return success
return Result.success();
}
您无法暂停PeriodicWorkRequest,唯一的选择是您必须取消该请求。
解决方案:最好在dowork()方法内添加条件检查,无论当前系统时间是否在下午6点至凌晨6点之间,都不需要做任何其他事情,您必须添加条件检查。
或您可以使用警报管理器在指定的时间启动服务,然后以指定的时间间隔重复警报。警报响起时,您可以启动服务并连接到服务器,然后执行所需的操作
[如果您想在特定时间执行某些操作,可以使用AlarmManager
这样的代码:
Intent alaramIntent = new Intent(LoginActivity.this, AutoLogoutIntentReceiver.class);
alaramIntent.setAction("LogOutAction");
Log.e("MethodCall","AutoLogOutCall");
alaramIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alaramIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 18);
calendar.set(Calendar.MINUTE, 01);
calendar.set(Calendar.SECOND, 0);
AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
Log.e("Logout", "Auto Logout set at..!" + calendar.getTime());
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
创建BroadcastReceiver
类:
public class AutoLogoutIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent)
{
if("LogOutAction".equals(intent.getAction())){
Log.e("LogOutAuto", intent.getAction());
//Stops the visit tracking service
Intent stopIntent = new Intent(context, VisitTrackingService.class);
stopIntent.setAction(VisitTrackingService.ACTION_STOP_FOREGROUND_SERVICE);
context.startService(stopIntent);
//logs user out of the app and closes it
SharedPrefManager.getInstance(context).logout();
exit(context);
}
}
并且不要忘记在清单(在应用程序标签内)添加接收器:
<receiver android:name=".AutoLogoutIntentReceiver" />
有关警报管理器的更多信息,请检查此link
希望有帮助!
我要用两个工人。首先进行管理,其次获得位置。首先是定期工作-晚上每24小时工作一次。它将停止LocationService并延迟再次调用它。