gpt4 book ai didi

java - 使用 dagger2 将类注入(inject)到 workmanager (java)

转载 作者:行者123 更新时间:2023-12-02 17:51:23 24 4
gpt4 key购买 nike

问题是我无法使用java将带有dagger2的类注入(inject)到worker(WorkManager)中。

我试图在这里理解它的解释:https://proandroiddev.com/dagger-2-setup-with-workmanager-a-complete-step-by-step-guild-bb9f474bde37我不知道为什么 - 但就我而言,这是行不通的。

public class SimpleWorker extends androidx.work.Worker {

private String TAG = "SimpleWorker";

SomeModel someModel; // this is injected model

public SimpleWorker(@NonNull Context context, @NonNull WorkerParameters
workerParams) {
super(context, workerParams);
}

@NonNull
@Override
public Result doWork() {
Log.d(TAG, someModel.toString()); // but here always null
return Result.success(); }
}

我希望它运行良好!

是的 - 这是我的问题的重复 WorkManager Java Android Dagger2但它被版主关闭了,我没有时间回答。我真的很想为其他人节省一些时间。附:请 - 不要删除它。

最佳答案

对于像我这样的人来说,答案是:

这是 Worker 类:

import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;

import androidx.work.ListenableWorker;
import androidx.work.WorkerParameters;

import javax.inject.Inject;
import javax.inject.Provider;

import com.sampleapp.model.Model;

public class SimpleWorker extends androidx.work.Worker {

//dagger (what we want to Inject into worker) U CAN ADD WHATEVER NEEDED
private Model model;

//not dagger (just some fields)
private String someField;
private final String TAG = getClass().getSimpleName();

private SimpleWorker(@NonNull Context context,
@NonNull WorkerParameters workerParams,
Model model) {
super(context, workerParams);
this.model = model;

someField = "just some work";
}

@NonNull
@Override
public ListenableWorker.Result doWork() {
Log.d(TAG, "Worker starts");
Log.d(TAG, model.getClass().getSimpleName() + " doing some work");
Log.d(TAG, "Job done!");
return ListenableWorker.Result.success();
}

public static class Factory implements ChildWorkerFactory {

private final Provider<Model> modelProvider;

@Inject
public Factory(Provider<Model> modelProvider) {
this.modelProvider = modelProvider;
}

@Override
public ListenableWorker create(Context context, WorkerParameters workerParameters) {
return new SimpleWorker(context,
workerParameters,
modelProvider.get());
}
}
}

接口(interface)是:

public interface ChildWorkerFactory {
ListenableWorker create(Context appContext, WorkerParameters workerParameters);
}

worker 工厂:

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import java.util.Map;

import javax.inject.Inject;
import javax.inject.Provider;

import androidx.work.ListenableWorker;
import androidx.work.WorkerFactory;
import androidx.work.WorkerParameters;

import com.sampleapp.model.Model;
import com.sampleapp.model.CollectionsUtil;
public class SimpleWorkerFactory extends WorkerFactory {

private final Map<Class<? extends ListenableWorker>, Provider<ChildWorkerFactory>> workersFactories;

@Inject
public SimpleWorkerFactory(Map<Class<? extends ListenableWorker>, Provider<ChildWorkerFactory>> workersFactories) {
this.workersFactories = workersFactories;
}

@Nullable
@Override
public ListenableWorker createWorker(@NonNull Context appContext, @NonNull String workerClassName, @NonNull WorkerParameters workerParameters) {
Provider<ChildWorkerFactory> factoryProvider = CollectionsUtil.getWorkerFactoryProviderByKey(workersFactories, workerClassName);
return factoryProvider.get().create(appContext, workerParameters);
}
}

集合实用程序:

/**
*
* @param map workers
* @param key workers name (class name)
* @return
*/
public static Provider<ChildWorkerFactory> getWorkerFactoryProviderByKey(Map<Class<? extends ListenableWorker>, Provider<ChildWorkerFactory>> map, String key) {
for (Map.Entry<Class<? extends ListenableWorker>, Provider<ChildWorkerFactory>> entry : map.entrySet()) {
if (Objects.equals(key, entry.getKey().getName())) {
return entry.getValue();
}
}
return null;
}

worker 绑定(bind):

import dagger.Binds;
import dagger.Module;
import dagger.multibindings.IntoMap;

@Module
public interface WorkerBindingModule {
@Binds
@IntoMap
@WorkerKey(SimpleWorker.class)
ChildWorkerFactory bindHelloWorldWorker(SimpleWorker.Factory factory);
}

WorkerKey注释:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import androidx.work.ListenableWorker;
import dagger.MapKey;

@MapKey
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface WorkerKey {
Class<? extends ListenableWorker> value();
}

应用程序类的一部分:

private static AppComponent component;

private void configureWorkManager() {
UpdaterWorkerFactory factory = component.factory();
Configuration config = new Configuration.Builder()
.setWorkerFactory(factory)
.build();

WorkManager.initialize(this, config);
}

AppComponent接口(interface)的一部分:

@Singleton
@Component(modules = {AppModule.class, WorkerBindingModule.class})
public interface AppComponent {
// Some other injects here
SimpleWorkerFactory factory();
}

以及 list 的一部分(在应用程序内部):

<provider
android:name="androidx.work.impl.WorkManagerInitializer"
android:authorities="${applicationId}.workmanager-init"
android:exported="false"
tools:node="remove"/>

gradle 中有什么:

// (Java only)
implementation ("android.arch.work:work-runtime:1.0.1")

ps。如果它会与 firebase 发生一些冲突

api 'com.google.guava:guava:27.1-android'

注意:在我的例子中,模型被注入(inject)了 throw 接口(interface)。像:

public class ModelImplementation implements Model {
private ModelImplementation() {
App.getComponent().inject(this);
}
}

在同一个AppComponent中!

要使用这个惊人的功能,只需使用类似的东西(例如在 Activity 中):

PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(SimpleWorker.class, 
Const.WORKER_PERIOD, TimeUnit.MINUTES).build();
WorkManager.getInstance().enqueue(periodicWorkRequest);

pps。 Const.WORKER_PERIOD - 以分钟为单位的一段时间(分钟 15)

目标SDK是27

关于java - 使用 dagger2 将类注入(inject)到 workmanager (java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56545821/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com