使用工作管理器的定期工作请求不起作用



>我正在尝试编写一个定期的工作管理器脚本,但它只是在我打开应用程序时运行,它只运行一次(不是周期性的(!

这是我的主要活动:

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_work);
Intent intent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this,0,intent,0);
NotifyWorker.pendingIntent = pendingIntent;
NotifyWorker.context = this;
PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(NotifyWorker.class, 1, TimeUnit.MINUTES).build();
WorkManager.getInstance().enqueue(periodicWorkRequest);
}

}

这是我的dowork方法:

public Result doWork() {
Log.i("wd","wd");
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context,"ctx")
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(),R.mipmap.ic_launcher))
.setSmallIcon(R.drawable.logo)
.setContentTitle("Title")
.setContentText("Desc")
.setContentIntent(pendingIntent);
android.app.NotificationManager notificationManager =
(android.app.NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 , notificationBuilder.build());
return Result.SUCCESS;
}

为什么它不是每 1 分钟运行一次? 我想念什么?

根据 PeriodicWorkRequest.Builder 文档:

间隔米利斯必须大于或等于 PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS

该值当前设置为900000- 即 15 分钟。

首先,你可以不同意我的回答,但这是我在我的项目中使用的黑客,这项工作非常准确地没有任何问题。 是时候看看代码了。我稍后指出的一件事,必须在代码之后阅读这一点。部分 IMP

//this code in your activity, fragment or any other class
notify_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
{
OneTimeWorkRequest track_share_market = new OneTimeWorkRequest.Builder(NotificationWorker.class).setInitialDelay(1,TimeUnit.MINUTES).addTag("Stock_Market").build();
WorkManager.getInstance().enqueue(track_share_market);
Log.d("RishabhNotification","SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSs");
}
else {
Log.d("RishabhNotification","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");
WorkManager.getInstance().cancelAllWorkByTag("Stock_Market");
}
}
});

现在您的Worker类代码

public class NotificationWorker extends Worker {
public NotificationWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
try {
//Some heavy operation as you want there is no need to make another thread here 
//track some website for weather changes or stock market changes
//In my case doWork takes only 10sec for executing this method  
ShowNotification("Market Up","Gold Price goes upto ₹25,000 ","Check the app for the new update");
StartNewRequest();
return Result.success();
} catch (Exception e) {
e.printStackTrace();
StartNewRequest();
Log.d("RishabhNotification","ERERERERERERERERERERERERERERERERERERERERERERERERERERERE");
return Result.failure();
}
}
private void StartNewRequest()
{
OneTimeWorkRequest track_market = new OneTimeWorkRequest.Builder(NotificationWorker.class).setInitialDelay(1,TimeUnit.MINUTES).addTag("Stock_Market").build();
WorkManager.getInstance().enqueue(track_market);
}
private void ShowNotification(String Message, String name, String Information)
{
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Stock Market", NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.GREEN);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationChannel.setSound(null,null );
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
notificationManager.createNotificationChannel(notificationChannel);
}

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), NOTIFICATION_CHANNEL_ID);
Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationBuilder.setAutoCancel(false)
.setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE|Notification.DEFAULT_LIGHTS)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setSound(uri)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setPriority(Notification.PRIORITY_MAX)
.setContentTitle(Message)
.setContentText(name)
.setContentInfo(Information);
notificationManager.notify(/*notification id*/1, notificationBuilder.build());
}
}

现在阅读部分IMP点 此代码在模拟器,Pixel手机,三星手机,Moto手机,华硕手机,One plus手机中完美运行,但是我在Xioami设备和华为设备中测试了相同的代码,它们都不是在每个特定的时间间隔内运行代码(它们都运行代码,但时间可能会更改(,这是我在代码中定义的。我不知道为什么在两台设备上都会发生这种情况。也许是一些优化。查看此链接以获取更多 https://www.reddit.com/r/androiddev/comments/9ra0iq/workmanager_reliability_for_periodic_tasks_on/我还没有在体内和 Oppo 设备中测试过这段代码。

最新更新