带下载进度条的启动画面

时间:2017-08-09 21:13:19

标签: android android-asynctask

所以当我从互联网上下载2个xml文件时,我会被一个进度条作为启动画面而停滞不前。

到目前为止一切顺利,一切对我来说都很好 - 但此时我不知道如何继续。我的目标是让用户在启动画面上“等待”,直到应用程序完成下载。

我尝试将int“lenghtOfFile”从类传递给我的Main Activity。它对我来说无论如何都没有用。在下载内容时,基于​​Thread的进度条也不是正确的方法。

所以现在我想把Downloader作为AsyncTask放在我的MainActivity的末尾 - 但对于2个单独的文件,是否有任何优雅的方式进行两次下载?然后,获得一个进度条从0到100而不是两个条形从0到100计数是不是很棘手?

***更新

好的,我的Splash Screen和我的TextView在第一个File下载后更新了。 那么,我现在怎样才能在尽可能少的代码中进行第二次下载?我可以使用任何“while”或其他东西来做这件事吗?

我实现splashTread.start()的方法是否正确; on onPostExecute()?我希望在下载完成后我的启动画面退出

可选:我可以使用0 - 100%的下载状态更新TextView吗?

公共类Splashscreen扩展了Activity {

final String urlone = config.DL_DJ;

public boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}


public void onAttachedToWindow() {
    super.onAttachedToWindow();
    Window window = getWindow();
    window.setFormat(PixelFormat.RGBA_8888);

}
/** Called when the activity is first created. */
Thread splashTread;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splashscreen);
    TextView splashstatus = (TextView) findViewById(R.id.spstatus);

    if (isNetworkAvailable()) {
        splashstatus.setText("ONLINE");
    } else
    {
        splashstatus.setText("OFFLINE");
    }
    new MyTask().execute();
    StartAnimations();
}
private void StartAnimations() {
    Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
    anim.reset();
    LinearLayout l=(LinearLayout) findViewById(R.id.lin_lay);
    l.clearAnimation();
    l.startAnimation(anim);

    anim = AnimationUtils.loadAnimation(this, R.anim.translate);
    anim.reset();
    ImageView iv = (ImageView) findViewById(R.id.splash);
    iv.clearAnimation();
    iv.startAnimation(anim);

    splashTread = new Thread() {
        @Override
        public void run() {
            try {
                 Intent intent = new Intent(Splashscreen.this,
                        MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivity(intent);
                Splashscreen.this.finish();
            }   finally {
                Splashscreen.this.finish();
            }

        }
    };


}


private class MyTask extends AsyncTask<Void, Void, Void> {



    @Override
    protected Void doInBackground(Void... params) {



        try {
            URL url1 = new URL(urlone);

            URLConnection ucon = url1.openConnection();
            int lenghtOfFile = ucon.getContentLength();

            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            Log.i("SPLASH LOGGER", "Got InputStream and BufferedInputStream");
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("Events.xml"),Context.MODE_PRIVATE);
            Log.i("SPLASH LOGGER", "Got FileOutputStream and BufferedOutputStream");


            byte data[] = new byte[1024];
            //long total = 0;
            int count;
            //loop and read the current chunk
            while ((count = bis.read(data)) != -1) {

                //keep track of size for progress.
                //total += count;
                //write this chunk
                bos.write(data, 0, count);
            }
            //Have to call flush or the  file can get corrupted.
            bos.flush();
            bos.close();



        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }

        return null;

    }

    @Override
    protected void onPostExecute(Void result) {
        TextView splashstatus = (TextView) findViewById(R.id.spstatus);
    splashstatus.setText("Done Downloading");
    splashTread.start();
  }

    @Override
    protected void onPreExecute()
    {TextView splashstatus = (TextView) findViewById(R.id.spstatus);
        splashstatus.setText("Start Downloading");
    }



}



}

:: LOGCAT ::

 08-17 22:15:23.154 32443-32505/? I/SPLASH LOGGER: Got InputStream and BufferedInputStream
08-17 22:15:23.154 32443-32505/? I/SPLASH LOGGER: Got FileOutputStream and BufferedOutputStream
08-17 22:15:23.155 32443-32505/? I/URL LOGGER: LINK HERE
08-17 22:15:23.156 32443-32505/? I/URL LOGGER: Events.xml
08-17 22:15:23.157 32443-32505/? I/URL LOGGER: 3
08-17 22:15:23.157 32443-32505/? I/progress: 33.333336
08-17 22:15:23.158 32443-32443/? I/String.valueOf values: 37.37226
08-17 22:15:23.158 32443-32443/? I/String.valueOf values: 74.74452
08-17 22:15:23.158 32443-32443/? I/String.valueOf values: 100.0
08-17 22:15:23.162 32443-32505/? I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
08-17 22:15:23.162 32443-32505/? I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
08-17 22:15:23.170 32761-32761/? W/ContextImpl: Calling a method in the system process without a qualified user: android.app.ContextImpl.startService:1386 android.content.ContextWrapper.startService:656 android.content.ContextWrapper.startService:656 com.samsung.android.app.assistantmenu.AssistantMenuReceiver.onReceive:144 android.app.ActivityThread.handleReceiver:3309 
08-17 22:15:23.329 29472-29472/? I/oneconnect[1.6.03-45_2]: FeatureUtil.isQcSupportedMode - user: 0
08-17 22:15:23.336 29253-29253/? I/ThemeManagerReceiver: ThemeManagerReceiver onReceive android.intent.action.PACKAGE_REPLACED
08-17 22:15:23.347 32443-32505/? I/SPLASH LOGGER: Got InputStream and BufferedInputStream
08-17 22:15:23.347 32443-32505/? I/SPLASH LOGGER: Got FileOutputStream and BufferedOutputStream
08-17 22:15:23.348 32443-32505/? I/URL LOGGER: LINK HERE
08-17 22:15:23.349 32443-32505/? I/URL LOGGER:  overall.xml
08-17 22:15:23.349 32443-32505/? I/URL LOGGER: 3
08-17 22:15:23.349 32443-32505/? I/progress: 66.66667
08-17 22:15:23.350 32443-32505/? I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
08-17 22:15:23.351 32443-32505/? I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
08-17 22:15:23.353 32443-32443/? I/String.valueOf values: -68233.33
08-17 22:15:23.354 32443-32443/? I/String.valueOf values: -90099.99
08-17 22:15:23.480 32443-32505/? I/SPLASH LOGGER: Got InputStream and BufferedInputStream
08-17 22:15:23.480 32443-32505/? I/SPLASH LOGGER: Got FileOutputStream and BufferedOutputStream
08-17 22:15:23.482 32443-32443/? I/String.valueOf values: 100.0

注意,必须编辑一些值:

        @Override
    protected void onProgressUpdate(Float... values) {
        TextView splashstatus = (TextView) findViewById(R.id.spstatus);
        splashstatus.setText(String.valueOf(values[0]));
        Log.i("String.valueOf values", String.valueOf(values[0]));
    }

此处正在进行日志记录:

                    String urlStr = urls.keyAt(i);
                Log.i("URL LOGGER",urls.keyAt(i));
                OutputStream file = openFileOutput(urls.valueAt(i),Context.MODE_PRIVATE);
                Log.i("URL LOGGER",urls.valueAt(i));
                float fPercent = (((float)i)/urls.size())*100.0f;
                Log.i("URL LOGGER", String.valueOf(urls.size()));
                Log.i("progress", String.valueOf(fPercent));

1 个答案:

答案 0 :(得分:0)

这是一个非常复杂的问题,所以我会尝试提供一些指导,而无需编写大量代码...

你的直觉是对的,你应该使用ASyncTask而不是使用Threads实现某种类型的IPC。具体来说,您可以使用publishProgress()onProgressUpdate()(在UI线程上运行)的组合来更新视图中的ProgressBar。

您可以在下载完成后使用ASyncTask的onPostExecute()回调执行某些操作(退出启动画面)。

就同时进行两次下载而言,没有理由只能在ASyncTask中按顺序下载它们。在这种情况下你如何处理ProgressBar虽然我猜这是有趣的部分。我可能只是将ProgressBar的前50%作为第一个文件而后半部分是第二个文件。如果您愿意,我可以发布一些准系统代码。

更新:

我认为以下是处理此问题的一种非常优雅的方式。可以轻松扩展到2个以上的文件。我对其余代码做了一些假设,因此需要编辑。可能有错误,我没有运行它,但它应该给你一个想法去哪里:

private class MyTask extends AsyncTask<Void, Float, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        try {
            ArrayMap<String, String> urls = new ArrayMap<String, String>();
            urls.put(urlone, "Events.xml");
            urls.put(urltwo, "Whatever.xml");
            for (int i = 0; i < urls.size(); i ++) {
                String urlStr = urls.keyAt(i);
                String file = urls.valueAt(i);
                float fPercent = (((float)i)/urls.size())*100.0f;

                URL url = new URL(urlStr);
                URLConnection ucon = url.openConnection();
                int lengthOfFile = ucon.getContentLength();

                InputStream is = ucon.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                Log.i("SPLASH LOGGER", "Got InputStream and BufferedInputStream");
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file), Context.MODE_PRIVATE);
                Log.i("SPLASH LOGGER", "Got FileOutputStream and BufferedOutputStream");


                byte data[] = new byte[1024];
                long total = 0;
                int count;
                //loop and read the current chunk
                while ((count = bis.read(data)) != -1) {
                    //keep track of size for progress.
                    total += count;
                    publishProgress(fPercent + (((float)total)/lengthOfFile)*100.0f);
                    bos.write(data, 0, count);
                }
                //Have to call flush or the file can get corrupted.
                bos.flush();
                bos.close();
            }

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }

        return null;

    }

    @Override
    protected void onProgressUpdate(Float... values) {
        TextView splashstatus = (TextView) findViewById(R.id.spstatus);
        splashstatus.setText(values[0].toString());
    }
}