从AsyncTask更新UI并正确处理屏幕旋转



此代码在旋转屏幕时不起作用。我尝试使用处理程序,但消息被分派到以前的活动(之前旋转)和新的活动。

¿线程如何向新Activity发送消息?请不要建议避免旋转屏幕。

public class SampleActivity extends Activity {
    TextView text;
    Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        text = new TextView(this);
        text.setText("HELLO");
        layout.addView(text);
        if (savedInstanceState != null) {
            text.setText(savedInstanceState.getString("text"));
        }
        setContentView(layout);
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("text", text.getText().toString());
    }
    @Override
    protected void onStart() {
        super.onStart();
        new CounterTask().execute();
    }
    public class CounterTask extends AsyncTask<Void, String, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            for (int i = 0; i < 100; i++) {
                try {
                    Thread.sleep(100);
                    publishProgress("Hello " + i);
                } catch (Exception e) {
                }
            }
            return null;
        }
        @Override
        protected void onProgressUpdate(String... values) {
            String str = values[0];
            text.setText(str);
        }
    }
}

可以在保留的片段中运行AsyncTask

public class TaskFragment extends Fragment {
    private Callback mCallback;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mCallback = (Callback) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement TaskFragment.Callback");
        }
    }
    @Override
    public void onDetach() {
        super.onDetach();
        mCallback = null;
    }
    public void execute(){
        new CounterTask().execute();
    }
    public interface Callback {
        void onTaskUpdate(String value);
    }
    public class CounterTask extends AsyncTask<Void, String, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            for (int i = 0; i < 100; i++) {
                try {
                    Thread.sleep(100);
                    publishProgress("Hello " + i);
                } catch (Exception e) {
                }
            }
            return null;
        }
        @Override
        protected void onProgressUpdate(String... values) {
            if(mCallback != null) {
                String str = values[0];
                mCallback.onTaskUpdate(str);
            }
        }
    }
}

然后,在你的活动中实现回调,并通过片段管理器添加片段。

public class SampleActivity extends Activity implements
        TaskFragment.Callback {
    private static final String TAG_TASK_FRAGMENT = "task_fragment";
    private TaskFragment mTaskFragment;
    private TextView text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        text = new TextView(this);
        text.setText("HELLO");
        layout.addView(text);
        if (savedInstanceState != null) {
            text.setText(savedInstanceState.getString("text"));
        }
        setContentView(layout);
        FragmentManager fm = getFragmentManager();
        mTaskFragment = (TaskFragment) fm.findFragmentByTag(TAG_TASK_FRAGMENT);
        if(mTaskFragment == null){
            mTaskFragment = new TaskFragment();
            fm.beginTransaction()
                    .add(mTaskFragment, TAG_TASK_FRAGMENT)
                    .commit();
        }
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("text", text.getText().toString());
    }
    @Override
    protected void onStart() {
        super.onStart();
        mTaskFragment.execute();
    }
    @Override
    public void onTaskUpdate(String value) {
        text.setText(value);
    }
}

你可以使用AsyncTaskLoader。它将处理你的activity/fragment的所有旋转和生命周期事件

只要添加一些配置来防止在屏幕旋转时重新创建活动,那么一切都ok,因为只有一个活动实例

在AndroidManifest.xml中添加活动标签

android:configChanges="orientation|keyboardHidden|screenSize"

和SampleActivity.java

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // when screen rotated, this method will be called instead of onCreate
}

相关内容

  • 没有找到相关文章

最新更新