0

我想编写一个下载管理器应用程序,在activity我添加一个进度条,向用户显示当前进度,现在如果用户触摸后退按钮并重新打开,activityProgressBar将不会被更新。

为了避免这个问题,我为每个下载创建一个具有唯一名称的单个线程,以保持进度可运行并检查该线程是否在onResume函数中运行,如果它是然后将其克隆到当前线程并再次重新运行新线程,但它也不会更新我的用户界面,有什么想法!?

@Override
public void onResume() 
{
    super.onResume();
    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
    for (int i = 0; i < threadArray.length; i++)
        if (threadArray[i].getName().equals(APPLICATION_ID))
        {
            mBackground = new Thread(threadArray[i]);
            mBackground.start();
            downloadProgressBar.setVisibility(View.VISIBLE);
            Toast.makeText(showcaseActivity.this
                    , "Find that thread - okay", Toast.LENGTH_LONG).show();
        }
}

private void updateProgressBar()
{
    Runnable runnable = new updateProgress();
    mBackground  = new Thread(runnable);
    mBackground.setName(APPLICATION_ID);
    mBackground.start();
}

private class updateProgress implements Runnable
{
    public void run() 
    {
        while (Thread.currentThread() == mBackground)
            try 
            {
                Thread.sleep(1000); 
                Message setMessage = new Message();
                setMessage.what = mDownloadReceiver.getProgressPercentage();        
                mHandler.sendMessage(setMessage);
            }
            catch (InterruptedException e) 
            {
                Thread.currentThread().interrupt();
            } 
            catch (Exception e) 
            {/* Do Nothing */}
    }
}

private Handler mHandler = new Handler()
{
    @Override
    public void handleMessage(Message getMessage) 
    {
        downloadProgressBar.setIndeterminate(false);
        downloadProgressBar.setProgress(getMessage.what);
        if (getMessage.what == 100)
            downloadProgressBar.setVisibility(View.GONE);
    }
};

下载按钮代码:

downloadBtn.setOnClickListener(new View.OnClickListener()
{
    @Override
    public void onClick(View arg0) 
    {
        downloadProgressBar.setVisibility(View.VISIBLE);
        downloadProgressBar.setIndeterminate(true);
        downloadProgressBar.setMax(100);    
        Intent intent = new Intent(showcaseActivity.this, downloadManagers.class);
        intent.putExtra("url", "http://test.com/t.zip");
        intent.putExtra("receiver", mDownloadReceiver);
        startService(intent);
        updateProgressBar();
    }
});
4

1 回答 1

2

我强烈建议您阅读有关Painless Threading的 Android 开发人员博客文章。正如它所说,从另一个线程更新 UI 的最简单方法是使用Activity.runOnUiThread

于 2013-03-09T00:21:54.030 回答