您可以onResume()
在您的偏好活动中执行以下操作:
- 开始
async call
...
- 将首选项设置为禁用,并提示正在获取值
- 获取值的网络(无论是没有值还是总是) - 异步,因此它不会停止恢复
- 使用您获取的值更新首选项条目
- 启用首选项并显示默认提示
如果这样做的缺点是,您的首选项要么会过于频繁地更新(例如,总是在您的首选项屏幕开始时),但是这样您就可以处理网络调用的结果产生一个列表的情况,其中之前选择的值不是不再存在(例如,向用户显示一个对话框,其中说他的选择不再可用)。
此外,这是一项相当复杂的任务(因为您必须定义 a Handler
,因为异步执行存在于另一个线程中......)
它看起来像这样(假设你在你PreferenceActivity
的
import android.os.Handler;
import android.os.AsyncTask;
import android.os.Message;
public class xyz extends PreferenceActivity {
...
// define a handler to update the preference state
final Handler handler = new Handler() {
public void handleMessage( Message msg ) {
ListPreference dpref = (ListPreference) getPreferenceManager().findPreference("debug");
dpref.setEnabled( msg.getData().getBoolean("enabled") );
dpref.setSummary( msg.getData().getString("summary") );
}
};
private class updatePref extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg) {
Message msg = handler.obtainMessage();
Bundle data = new Bundle();
data.putBoolean("enabled", false ); // disable pref
data.putString("summary", "Getting vals from network..." ); // set summary
msg.setData( data );
handler.sendMessage(msg); // send it do the main thread
ListPreference dpref = (ListPreference) getPreferenceManager().findPreference("debug");
String values[];
// call network function and let it fill values[]
// do things according to the returned values,
// eg check if there are any, check if the user has
// already selected one, display a message if the
// user has selected one before but the values do not
// contain them anymore, ...
// set the new values
dpref.setEntries(values);
dpref.setEntryValues(values);
data.putBoolean("enabled", true ); // enable pref
data.putString("summary", "Please choose" ); // set summary
msg.setData( data );
handler.sendMessage(msg); // send it do the main thread
return null;
}
}
public void onResume() {
....
new updatePref().execute();
}
}
当然你可以new updatePref().execute()
在任何地方调用,所以你也可以将它绑定到 aButton
或onCreate()
任何地方(无需在 中执行此操作onResume()
)。