androidandroid-wallpaper

How do I change wallpaper periodically using WorkManager?


I am trying to change the wallpaper of Android, in some periodic interval.

I used WorkManager to run a worker, that downloads the wallpaper in the background and sets it.

As long as the app is running, the wallpaper is changed. When I close the wallpaper, it stops. I am using PeriodcWork in Workmanager.

This is my code

public class OneTimeWorker extends Worker {
Context context = getApplicationContext();
private String URL;
@NonNull
@Override
public Result doWork() {
    new FetchWallpaper().execute();
    return Result.SUCCESS;
}
private class FetchWallpaper extends AsyncTask<Void, Void, Bitmap>
{
    @Override
    protected Bitmap doInBackground(Void... voids) {
        String imageUrl="";
        Bitmap result = null;
        try
        {
            URL = "myurl.com";
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(URL)
                    .build();
            Response responses = null;
            try {
                responses = client
                        .newCall(request)
                        .execute();
                String jsonData = responses.body().string();

                JSONArray jsonArr = new JSONArray(jsonData);
                JSONObject c = jsonArr.getJSONObject(new Random().nextInt(jsonArr.length()));

                imageUrl = c.getString("wallpaper");

                result = Picasso.with(getApplicationContext())
                        .load(imageUrl)
                        .get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        catch (Exception e)
        {
        }
        return result;
    }
    @Override
    protected void onPostExecute(Bitmap bitmap) {
        super.onPostExecute(bitmap);
            WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
            try {
                wallpaperManager.setBitmap(bitmap);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
    }

}
}

Solution

  • You better use Android-Job by Evernote.

    Internally uses WorkManager, provides smooth, nice - chained methods & reliability while it's easy to implement.

    Automatically chooses between JobManager/WorkManager/GCM/AlarmManager to ensure that your code must execute.

    I myself using this and it's good.