AsyncTaskLoader onLoadFinished与待处理的任务和配置变化(AsyncTa

2019-07-30 11:32发布

我试图使用AsyncTaskLoader在后台加载数据响应于被选择的列表项目来填充的详细视图。 我已经得到了它主要是工作,但我仍然有一个问题。 如果我选择在列表中的第二个项目, 然后第一个选择项加载完成之前旋转设备,那么onLoadFinished()调用的活动报告被停止,而不是新的活动。 选择只是一个单一的项目,然后在旋转时也能正常工作。

下面是我使用的代码。 活动:

public final class DemoActivity extends Activity
        implements NumberListFragment.RowTappedListener,
                   LoaderManager.LoaderCallbacks<String> {

    private static final AtomicInteger activityCounter = new AtomicInteger(0);

    private int myActivityId;

    private ResultFragment resultFragment;

    private Integer selectedNumber;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        myActivityId = activityCounter.incrementAndGet();
        Log.d("DemoActivity", "onCreate for " + myActivityId);

        setContentView(R.layout.demo);

        resultFragment = (ResultFragment) getFragmentManager().findFragmentById(R.id.result_fragment);

        getLoaderManager().initLoader(0, null, this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("DemoActivity", "onDestroy for " + myActivityId);
    }

    @Override
    public void onRowTapped(Integer number) {
        selectedNumber = number;
        resultFragment.setResultText("Fetching details for item " + number + "...");
        getLoaderManager().restartLoader(0, null, this);
    }

    @Override
    public Loader<String> onCreateLoader(int id, Bundle args) {
        return new ResultLoader(this, selectedNumber);
    }

    @Override
    public void onLoadFinished(Loader<String> loader, String data) {
        Log.d("DemoActivity", "onLoadFinished reporting to activity " + myActivityId);
        resultFragment.setResultText(data);
    }

    @Override
    public void onLoaderReset(Loader<String> loader) {

    }

    static final class ResultLoader extends AsyncTaskLoader<String> {

        private static final Random random = new Random();

        private final Integer number;

        private String result;

        ResultLoader(Context context, Integer number) {
            super(context);
            this.number = number;
        }

        @Override
        public String loadInBackground() {
            // Simulate expensive Web call
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return "Item " + number + " - Price: $" + random.nextInt(500) + ".00, Number in stock: " + random.nextInt(10000);
        }

        @Override
        public void deliverResult(String data) {
            if (isReset()) {
                // An async query came in while the loader is stopped
                return;
            }

            result = data;

            if (isStarted()) {
                super.deliverResult(data);
            }
        }

        @Override
        protected void onStartLoading() {
            if (result != null) {
                deliverResult(result);
            }

            // Only do a load if we have a source to load from
            if (number != null) {
                forceLoad();
            }
        }

        @Override
        protected void onStopLoading() {
            // Attempt to cancel the current load task if possible.
            cancelLoad();
        }

        @Override
        protected void onReset() {
            super.onReset();

            // Ensure the loader is stopped
            onStopLoading();

            result = null;
        }

    }

}

清单片段:

public final class NumberListFragment extends ListFragment {

    interface RowTappedListener {

        void onRowTapped(Integer number);

    }

    private RowTappedListener rowTappedListener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        rowTappedListener = (RowTappedListener) activity;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(getActivity(),
                                                                  R.layout.simple_list_item_1,
                                                                  Arrays.asList(1, 2, 3, 4, 5, 6));
        setListAdapter(adapter);

    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        ArrayAdapter<Integer> adapter = (ArrayAdapter<Integer>) getListAdapter();
        rowTappedListener.onRowTapped(adapter.getItem(position));
    }

}

结果片段:

public final class ResultFragment extends Fragment {

    private TextView resultLabel;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.result_fragment, container, false);

        resultLabel = (TextView) root.findViewById(R.id.result_label);
        if (savedInstanceState != null) {
            resultLabel.setText(savedInstanceState.getString("labelText", ""));
        }

        return root;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putString("labelText", resultLabel.getText().toString());
    }

    void setResultText(String resultText) {
        resultLabel.setText(resultText);
    }

}

我已经能够用简单的得到这个工作AsyncTask秒,但我想更多地了解Loader小号,因为他们自动处理配置更改。


编辑 :我想我可能已经通过查看源问题追查LoaderManager 。 当initLoader在配置更改后调用, LoaderInfo对象有mCallbacks与为实施新的活动领域更新LoaderCallbacks ,正如我所期望的。

public <D> Loader<D> initLoader(int id, Bundle args, LoaderManager.LoaderCallbacks<D> callback) {
    if (mCreatingLoader) {
        throw new IllegalStateException("Called while creating a loader");
    }

    LoaderInfo info = mLoaders.get(id);

    if (DEBUG) Log.v(TAG, "initLoader in " + this + ": args=" + args);

    if (info == null) {
        // Loader doesn't already exist; create.
        info = createAndInstallLoader(id, args,  (LoaderManager.LoaderCallbacks<Object>)callback);
        if (DEBUG) Log.v(TAG, "  Created new loader " + info);
    } else {
        if (DEBUG) Log.v(TAG, "  Re-using existing loader " + info);
        info.mCallbacks = (LoaderManager.LoaderCallbacks<Object>)callback;
    }

    if (info.mHaveData && mStarted) {
        // If the loader has already generated its data, report it now.
        info.callOnLoadFinished(info.mLoader, info.mData);
    }

    return (Loader<D>)info.mLoader;
}

然而,当存在未决装载机,主要LoaderInfo对象也有一个mPendingLoader与一个参考场LoaderCallbacks还有,这个对象是永远不会在新的活动更新mCallbacks场。 我希望看到的代码看起来像这个:

// This line was already there
info.mCallbacks = (LoaderManager.LoaderCallbacks<Object>)callback;
// This line is not currently there
info.mPendingLoader.mCallbacks = (LoaderManager.LoaderCallbacks<Object>)callback;

这似乎是因为这样,未决加载器调用onLoadFinished在老年活动实例。 如果我在这个方法中断点,并拨打电话,我觉得使用调试器丢失,一切工作如我所料。

新的问题是:有没有我发现了一个bug,或者这是预期的行为?

Answer 1:

在大多数情况下,你应该忽略这样的报告,如果活动已被销毁。

public void onLoadFinished(Loader<String> loader, String data) {
    Log.d("DemoActivity", "onLoadFinished reporting to activity " + myActivityId);
    if (isDestroyed()) {
       Log.i("DemoActivity", "Activity already destroyed, report ignored: " + data);
       return;
    }
    resultFragment.setResultText(data);
}

你也应该检查插入isDestroyed()在任何内部类。 Runnable接口 - 是最常用的情况。

例如:

// UI thread
final Handler handler = new Handler();
Executor someExecutorService = ... ;
someExecutorService.execute(new Runnable() {
    public void run() {
        // some heavy operations
        ...
        // notification to UI thread
        handler.post(new Runnable() {
            // this runnable can link to 'dead' activity or any outer instance
            if (isDestroyed()) {
                return;
            }

            // we are alive
            onSomeHeavyOperationFinished();
        });
    }
});

但在这种情况下,最好的方法是避免将活性强引用另一个线程 (AsynkTask,装载机,执行器等)。

最可靠的解决方案是在这里:

// BackgroundExecutor.java
public class BackgroundExecutor {
    private static final Executor instance = Executors.newSingleThreadExecutor();

    public static void execute(Runnable command) {
        instance.execute(command);
    }
}

// MyActivity.java
public class MyActivity extends Activity {
    // Some callback method from any button you want
    public void onSomeButtonClicked() {
        // Show toast or progress bar if needed

        // Start your heavy operation
        BackgroundExecutor.execute(new SomeHeavyOperation(this));
    }

    public void onSomeHeavyOperationFinished() {
        if (isDestroyed()) {
            return;
        }

        // Hide progress bar, update UI
    }
}

// SomeHeavyOperation.java
public class SomeHeavyOperation implements Runnable {
    private final WeakReference<MyActivity> ref;

    public SomeHeavyOperation(MyActivity owner) {
        // Unlike inner class we do not store strong reference to Activity here
        this.ref = new WeakReference<MyActivity>(owner);
    }

    public void run() {
        // Perform your heavy operation
        // ...
        // Done!

        // It's time to notify Activity
        final MyActivity owner = ref.get();
        // Already died reference
        if (owner == null) return;

        // Perform notification in UI thread
        owner.runOnUiThread(new Runnable() {
            public void run() {
                owner.onSomeHeavyOperationFinished();
            }
        });
    }
}


Answer 2:

也许不是最好的解决办法,但...这个代码重新加载每一次,这是不好的,但只是解决的作品 - 如果你想使用的装载机。

Loader l = getLoaderManager().getLoader(MY_LOADER);
if (l != null) {
    getLoaderManager().restartLoader(MY_LOADER, null, this);
} else {
    getLoaderManager().initLoader(MY_LOADER, null, this);
}

BTW。 我使用Cursorloader ...



Answer 3:

一种可能的解决办法是启动的AsyncTask在自定义singleton对象和访问onFinished()从你的活动中单身的结果。 每次旋转屏幕的时候,走的onPause()或的onResume(),最新的结果将被用来/访问。 如果你还没有在你的单件对象的结果,你知道它是仍然忙,或者你可以重新启动的任务。

另一种方法是与像奥托服务坐公交车上下班,或与服务工作。



Answer 4:

好吧我想明白这一点原谅我,如果我误解了什么,但是当设备旋转时,你正在失去参考的东西。

以某刺...

会增加

android:configChanges="orientation|keyboardHidden|screenSize"

在您的清单该活动改正错误? 或防止onLoadFinished()从话说,活动停止了?



文章来源: AsyncTaskLoader onLoadFinished with a pending task and config change