onResume()
設定アクティビティで次のことができます。
- を開始
async call
します...
- 値がフェッチされているというヒントを使用して、設定を無効に設定します
- 値を取得するためのネットワーク (値がない場合、または常に) - 非同期であるため、再開を停止しません。
- 取得した値で設定エントリを更新します
- 設定を有効にしてデフォルトのヒントを表示する
この場合の欠点は、設定があまりにも頻繁に更新されることです (たとえば、設定画面が開始されたときに常に)。ただし、これにより、ネットワーク呼び出しの結果が前に選択された値ではないリストを生成する場合に対処できます。 (たとえば、ユーザーの選択が利用できなくなったことを示すダイアログをユーザーに表示します)。
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()
どこにでもバインドできます( でこれを行う必要はありません)。Button
onCreate()
onResume()