他の誰かを助ける場合に備えて、サーバーからxmlデータファイルをダウンロードする非アクティビティクラスを呼び出すアクティビティがあります。進行状況インジケーターを表示したかったのです。私はこのようにしました(これはクラスの完全な実装ではありませんが、良いアイデアを与えるはずです):
/*Setup Activity Class */
public class MySetup extends Activity implements ThreadCompleteListener{
Button btnLogin, btnItems, btnConfig, btnStart;
ProgressDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setup_activity);
//set up links to buttons, etc
}
public void onBtnClicked(View v){
Intent intent;
switch(v.getId()){
case R.id.btn_download_items:
final Context ctx = this;
startProgressIndicator();
//async read a list of items from a server
myList=ItemsList.getItemsListInstance(ctx);
btnConfig.setEnabled(true);
break;
//other options here
}
}
public void startProgressIndicator(){
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading items...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
public void endProgressIndicator(){
pDialog.dismiss();
}
}
次に、アクティビティ以外のクラスで、ダウンロードを行います
public class ItemsList implements ThreadCompleteListener{
//create a list of MyItem
private ArrayList<MyItem> items = new ArrayList<MyItem>();
//create a single static instance
private static ItemsList itemsListInstance;
String baseUrl; //to connect to webservice
Context ctx;
public ItemsList(Context context){
readJSONFeed("http://someurl/", context);
ctx=context;
}
public void readJSONFeed(String theURL, Context context) {
//Read JSON string from URL
final Context ctx = context;
setBaseUrl();
//NotifyThread is a class I found in a Stack Overflow answer
//that provides a simple notification when the async process has completed
NotifyThread getItemsThread = new NotifyThread(){
@Override
public void doRun(){
try {
//do the JSON read stuff here...
}catch (Exception e) {
}
};
getItemsThread.addListener(this);
getItemsThread.start();
}
//Overload the NotifyThread method
public void notifyOfThreadComplete(final Thread thread){
//CALL the method in the calling activity to stop the progress indicator
((MySetup)ctx).endProgressIndicator();
}
public static AuctionItemsList getItemsListInstance(Context context) {
if (itemsListInstance == null){
itemsListInstance = new itemsList(context);
}
return itemsListInstance;
}
}