8

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

这是我的主要活动:

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);
}

}

这是我的工作方法:

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 分钟运行一次?我想念什么?

4

2 回答 2

40

根据PeriodicWorkRequest.Builder 文档

intervalMillis 必须大于或等于PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS

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

于 2018-06-30T20:54:33.050 回答
1

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

//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());
    }
}

现在阅读SECTION IMP点此代码在模拟器、Pixel 手机、三星手机、Moto 手机、华硕手机、一加手机中完美运行,但我在小米设备和华为设备上测试过的代码相同,它们都不是每个设备都运行代码我在代码中定义的特定时间间隔(它们都运行代码,但时间可能会更改)。我不知道为什么这两种设备都会发生这种情况。也许有些优化。检查此链接以获取更多信息https://www.reddit.com/r/androiddev/comments/9ra0iq/workmanager_reliability_for_periodic_tasks_on/ 我尚未在 vivo 和 Oppo 设备中测试过此代码。

于 2019-01-16T12:57:11.943 回答