2011-05-08 36 views
2

所以,我有我的onCreate方法在这里填充用户安装的应用程序ListView。这需要很长时间才能完成,我试图找出在哪里创建新线程来完成一些繁重的工作,以便在列表加载时显示ProgressDialog。这里是我的代码有:Android:适当的线程化ListActivity

protected void onCreate(Bundle savedInstanceState) {   
    super.onCreate(savedInstanceState); 

    // Find out which prefs to update 
    Bundle extras = getIntent().getExtras(); 
    if(extras !=null){ 
     buttonPressed = extras.getString("buttonPressed"); 
     loadNumber = extras.getString("loads"); 
    } 

    buttonPressedAppName = buttonPressed + "AppName" + loadNumber; 
    buttonPressedAppPack = buttonPressed + "AppPack" + loadNumber; 
    humanNamePrefs = buttonPressed + "AppText" + loadNumber; 

    // Get shared preferences 
    settings = getSharedPreferences(PREFS_NAME, 0); 

    // Do in another thread to not slow the UI down...eventually 
    adapter = createAdapter(); 
    setListAdapter(adapter); 
} 

public ListAdapter createAdapter() { 
    namesArray = new String[] { "Loading" }; 
    names = new ArrayList<String>(); 

    PackageManager pm = this.getPackageManager(); 
    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); 
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); 
    appList = pm.queryIntentActivities(mainIntent, 0); 
    Collections.sort(appList, new ResolveInfo.DisplayNameComparator(pm)); 

    // Now, appList contains all of the ResolveInfo stuff 

    for (int i = 0; i < appList.size(); i++) {   
     names.add(appList.get(i).loadLabel(pm).toString()); 
    } 

    namesArray = maker(names); 

    ListAdapter adapter = new ArrayAdapter<String>(this, 
      android.R.layout.simple_list_item_1, namesArray); 
    setListAdapter(adapter);   
    return adapter; 
} 

我有一个线程处理列表和这样的排序,但ProgressDialog我根本不会露面,直到列表完全填充,哪种击败目的在于拥有ProgressDialog

我的问题,简而言之,我应该把这个线程用于显示ProgressDialog WHILE列表正在完成填充?

以下内容得到

@Femi上AsyncTask提供了一个极好的教程和我的应用程序列表中的加载过程中有我ProgressDialog捻转。谢谢!

链接:http://labs.makemachine.net/2010/05/android-asynctask-example/

+0

你看过使用asynctask吗?在执行前显示进度,然后关闭onPostExecute – jkhouw1 2011-05-08 02:22:27

+0

查看本教程以查看工作实施。 http://p-xr.com/android-tutorial-how-to-make-a-progress-dialog/ – 2011-05-08 05:15:24

回答

0

推荐的方法是使用的AsyncTask:

  1. 显示进度对话框。
  2. 启动异步任务并在doInBackground方法中构建names ArrayList。
  3. 将数组列表传递给postExecute中的createAdapter方法,然后关闭进度对话框。
+0

好吧,我把一些日志命令在那里,我发现它是Collections.sort(appList,新的ResolveInfo.DisplayNameComparator(pm));调用这么久,所以我想我需要在doInBackground方法中执行此操作。我在ASyncTask中遇到了泛型问题。处理这个问题的正确方法是什么? – SemperGumbee 2011-05-08 05:20:48

+0

不确定你在AsyncTask中的泛型是什么意思,但是我AsyncTask的例子是http://labs.makemachine.net/2010/05/android-asynctask-example/:它带有一个完全可行的例子,你可以修改以适应。看一看,看看这是否无助于解决您的问题。如果它没有发布一些代码,而这些代码不工作,我们可以看到你被卡住了。 – Femi 2011-05-08 05:47:27

+0

你在链接中的例子正是我所需要的。多谢,伙计! – SemperGumbee 2011-05-08 06:39:04