logo
down
shadow

Android Workmanger PeriodicWorkRequest API work only once?


Android Workmanger PeriodicWorkRequest API work only once?

Content Index :

Android Workmanger PeriodicWorkRequest API work only once?
Tag : android , By : user119605
Date : November 19 2020, 04:01 AM

Any of those help Work Manager Not not based on system time. You can make a periodic work request of 15 minutes. This way you can test your code.
here's an example:
private static final String TAG = "PeriodicWorkTag";
private static final int PERIODIC_WORK_INTERVAL = 15;

public static void schedulePeriodicWork() {
    androidx.work.PeriodicWorkRequest periodicWorkRequest = new androidx.work.PeriodicWorkRequest.Builder(PeriodicWorkRequest.class, PERIODIC_WORK_INTERVAL,
            TimeUnit.MINUTES)
            .addTag(TAG)
            .build();
    WorkManager.getInstance().enqueueUniquePeriodicWork(TAG, ExistingPeriodicWorkPolicy.KEEP, periodicWorkRequest);
}

public static void cancelPeriodicWork() {
    WorkManager.getInstance().cancelAllWorkByTag(TAG);
}
public static final String CHANNEL_ID = "VERBOSE_NOTIFICATION" ;
public PeriodicWorkRequest(@NonNull Context context, @NonNull WorkerParameters workerParams) {
    super(context, workerParams);
}

@NonNull
@Override
public Result doWork() {
    showNotification(getApplicationContext());
    return Result.SUCCESS;
}

private void showNotification(Context context) {
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("My notification")
            .setContentText("ddd")
            .setStyle(new NotificationCompat.BigTextStyle()
                    .bigText("ddd"))
            .setPriority(NotificationCompat.PRIORITY_DEFAULT);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = "Channel_name";
        String description = "description";
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
        channel.setDescription(description);
        NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
    notificationManager.notify(100, mBuilder.build());
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Android Workmanager PeriodicWorkRequest is not unique


Tag : development , By : Nickolas
Date : March 29 2020, 07:55 AM
help you fix your problem The IllegalStateException you see was a bug we fixed in alpha01. Use the alpha02 library, and you won't see that problem. For more information, take a look at the release notes here.

How to register a periodic work request with WorkManger system-wide once (i.e. after boot or installation)


Tag : android , By : jbcrail
Date : March 29 2020, 07:55 AM
To fix the issue you can do In the first part, I simply present the solution as snippets of code without much explanation. In the second part, I elaborate on the solution, explain why it is not an exact solution, but the best possible one and point out some errors in Google documentation which led me to the question in the first place.
The Solution
public class WatchDogWorker extends Worker {
  private static final String uniqueWorkName = "my.package.name.watch_dog_worker";
  private static final long repeatIntervalMin = 30;
  private static final long flexIntervalMin = 10;

  public WatchDogWorker( @NonNull Context context, @NonNull WorkerParameters params) {
    super( context, params );
  }

  private static PeriodicWorkRequest getOwnWorkRequest() {
    return new PeriodicWorkRequest.Builder(
      WatchDogWorker.class, repeatIntervalMin, TimeUnit.MINUTES, flexIntervalMin, TimeUnit.MINUTES
    ).build();
  }

  public static void enqueueSelf() {
    WorkManager.getInstance().enqueueUniquePeriodicWork( uniqueWorkName, ExistingPeriodicWorkPolicy.KEEP, getOwnWorkRequest() );
  }

  public Worker.Result doWork() {
    // Put the actual code of the watchdog that needs to be run every 30mins here
    return Result.SUCCESS;
  }
}
public class BootCompleteReceiver extends BroadcastReceiver {
  public void onReceive( Context context, Intent intent ) {
    if( intent.getAction() == null || !intent.getAction().equals( "android.intent.action.BOOT_COMPLETED" ) ) return;
    WatchDogWorker.enqueueSelf();
  }
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  package="...">

  ...

  <application>
    ...
    <receiver
      android:name=".BootCompleteReceiver"
      android:enabled="true"
      android:exported="true">
      <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
      </intent-filter>
    </receiver>
  </application>
</manifest>
public class MainActivity extends AppCompatActivity {
  ...
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...

    // Schedule WatchDogWorker (after a fresh install we must not rely on the BootCompleteReceiver)
    WatchDogWorker.enqueueSelf();
  }
}

PeriodicWorkRequest Does not Work No Matter What


Tag : android , By : nagre
Date : March 29 2020, 07:55 AM
this will help You are setting the repetition interval to 900000 minutes, to set it 15 minutes, if you use PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLI then use TimeUnit.MILLISECONDS:
val oneTimeADayReq: PeriodicWorkRequest = PeriodicWorkRequest.Builder(
        StepCountNotificationWorker::class.java, 
        PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS,
        TimeUnit.MILLISECONDS).build()

WorkManager - PeriodicWorkRequest not working on android api 21


Tag : android , By : Arnaud Goudsmit
Date : March 29 2020, 07:55 AM
This might help you Sorry, I just verified that this is a bug on our end. We should have a fix in alpha04. Stay tuned.

WorkManger in Android is executing doWork() more than once


Tag : android , By : kaart
Date : March 29 2020, 07:55 AM
wish helps you When you enqueue a PeriodicWorkRequest, that does not cancel any existing PeriodicWorkRequest that you have previously enqueued. Therefore as you have written your app, every time your activity starts, you add yet periodic work request, slowly going from 1 to 2 to 3 onward.
You instead want to use enqueueUniquePeriodicWork():
final PeriodicWorkRequest pwr = new PeriodicWorkRequest
        .Builder(MyWorker.class, 16, TimeUnit.MINUTES)
        .setConstraints(Constraints.NONE)
        .build();

WorkManager.getInstance().enqueueUniquePeriodicWork(
    "my_worker",
    ExistingPeriodicWorkPolicy.REPLACE,
    pwr);
Related Posts Related QUESTIONS :
  • Best layout for form-style screen
  • How To create multiple function in Adapter Class Android with Retrofit
  • Can the Android Flow virtual layout handle variable-width Views
  • How to fix "Unable to load class 'dagger.Multibindings'" due to problems with gradle
  • VpnService always-on "not supported by this app"
  • Android Studio - Gradle "Sync now" is not Available
  • How do i get my code to give my current location?
  • Could not initialize class sun.util.calendar.ZoneInfoFile while using Flutter firebase-notifications
  • How to implement circular to check / tick animation in Android?
  • Toolbar shadow not showing
  • Android Sqlite get rows where first character is not an Alphabet
  • why I receive "bad request" in my request by retrofit
  • Intercept NavigationUI.onNavDestinationSelected() to make backstack pop with "inclusive = true"
  • I have a problem with the navigation fragments in my proyect, it sais that I need a defaut nav host atribute but I alrea
  • How can I keep a BottomSheetDialogFragment height to always match_parent?
  • How to reference a timerPicker in android studio using kotlin
  • Firebase Crashlytics - get stacktrace info to display during CrashlyticsListener.crashlyticsDidDetectCrashDuringPrevious
  • Schedule a repeating alarm clock
  • Can't assign values outside onTouchListener
  • Is setContentView() needed to inflate a fragment?
  • Why instead of string method returns Kotlin.Unit?
  • Retrofit slash as Query
  • When does onCreateView() get called in this app?
  • Fragment is reloaded each time after rejecting location permission
  • How to read ViewModel data from sttrings.xml list of items
  • Flutter doctor does not see vs code ,VS code does not detect flutter/bin
  • How to build aar in flutter
  • Is displayMetrix xdpi and ydpi accurate?
  • How to detect doubletap on a View?
  • how to play an encrypted file in Android
  • Android: keytool error on the command line when locating debug.keystore
  • Android paint/canvas issue; drawing smooth curves
  • Problems with starting an activity in onStart
  • Performance of map overlay in conjunction with ItemizedOverlay is very poor
  • How to change android indeterminate ProgressBar color?
  • How do I change the Mobile Country Code (MCC) in the Android Emulator?
  • Stop Progressbar manual scrolling in Android
  • Android: download large file
  • Android : uploaded .apk file to server but cant download that .apk file
  • How do I distribute Android app to beta tester without using Market
  • Android Unable to launch the Inbox from a notification
  • Android: Ringer mode changed to silent doesn't stop the phone vibrating
  • Change the side the text appears on a radio button
  • Check the memory usage anp cpu and power of an application in android
  • What is the String 'volumeName' argument of MediaStore.Audio.Playlists.Members.getContentUri referring to?
  • Playing Multiple sounds at the same time in Android
  • Android: how to change the time in emulator?
  • close the soft key pad when i click on other views in android
  • Setting the position within a spinner
  • How to play ringtone/alarm sound in Android
  • How to adjust text font size to fit textview
  • "Android 2.x" vs "Google APIs" for Android AVD Setup
  • How to center buttons on screen horizontally and vertically plus equidistant apart?
  • Discrete seekbar in Android app?
  • Gradle Build Fails - Illegal exception table range in class file com/google/wireless/android/sdk/stats/GradleBuildMemory
  • register has type Long (High Half) but expected Long (Low Half)
  • Is it good idea to use Dispatcher.Main with delay( )?
  • WebView and Advanced View is Not loading partiucalr URL
  • How to show three dots at the end of text view
  • Is it possible to run macros within Android Studio project?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com