带有下载进度条的启动画面 [英] Splash Screen with Download Progress Bar

查看:84
本文介绍了带有下载进度条的启动画面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在从Internet上下载2个xml文件时,会出现一个进度条作为初始屏幕的情况,我对此感到困惑.

So I'm stuck by getting a progress bar as a splash screen while downloading 2 xml files from the Internet.

到目前为止,一切对我来说都很正常-但目前我不知道如何进行.我的目标是让用户在启动屏幕上等待",直到完成下载应用程序为止.

So far so good, everything works fine for me - but at this point I don't know how to proceed. My Goal is let the User "wait" on a Splash Screen until the App is done with the Download.

我尝试将int"lenghtOfFile"从类传递给我的Main Activity.它对我没有任何作用.同样,在下载内容时,将进度条置于线程基础上似乎也不正确.

I tried passing the int "lenghtOfFile" from the class to my Main Activity. It doesn't work out for me in any way. Also basing my Progress Bar on the Thread seems not the right way when Downloading stuff.

因此,现在我正在考虑将Downloader作为AsyncTask放在MainActivity的末尾-但是对于2个单独的文件,是否有任何经典的方法可以进行两次下载?然后,获取一个从0 -100开始的进度条而不是两个从0-100开始计数的进度条是否很棘手?

So now I'm thinking of putting the Downloader as a AsyncTask at the End of my MainActivity - but for 2 separate files, is there any classy way to do the downloading twice? And afterwards, is it tricky to get one Progress Bar which goes from 0 -100 instead of two Bars counting each from 0-100?

***更新

好吧,我得到了启动画面和TextView,该文件在下载第一个文件后便进行了更新. 那么,现在如何以较少的代码获得第二次下载?我可以使用任何"while"或其他方式来做到这一点吗?

Ok I got my Splash Screen and my TextView which is updated after the first File was downloaded. So, how can I now get a second download in less as possible code? Can I use any "while" or something to do this?

我实现了splashTread.start()是否正确?在onPostExecute()上?我希望我的启动屏幕在下载完成后退出

Is it correct how I implemented the splashTread.start(); on onPostExecute()? I want my Splash Screen to quit after the downloading is complete

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

Optional: Can I update my TextView with a Download Status from 0 - 100%?

公共类Splashscreen扩展了活动{

public class Splashscreen extends 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 ::

:: 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

注意,必须编辑一些值:

NOTE, had to edit some values:

        @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]));
    }

,这里的日志正在进行:

and here the logging going on:

                    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));

推荐答案

这是一个非常漂亮的问题,因此我将尝试提供一些指导,而无需编写大量代码...

This is a pretty loaded question, so I'll try to provide some guidance without writing a ton of code...

您的直觉是正确的,您应该为此使用ASyncTask而不是使用Threads实现某种IPC.具体来说,您可以结合使用 publishProgress( ) onProgressUpdate()(在UI线程上运行)以更新视图中的ProgressBar.

Your intuition is right that you should use ASyncTask for this rather than implementing some sort of IPC using Threads. Specifically, you can use a combination of publishProgress() and onProgressUpdate() (which runs on the UI thread) to update a ProgressBar in your view.

您可以使用ASyncTask的 onPostExecute()下载完成后回调以执行某些操作(退出初始屏幕).

You can use the ASyncTask's onPostExecute() callback to do something (exit the splashscreen) after the download has finished.

就一次完成两个下载而言,没有理由不能像现在一样在ASyncTask中依次下载两个文件.在这种情况下,您如何处理ProgressBar是我认为很有趣的部分.我可能只将ProgressBar的前50%作为第一个文件,将后半部分作为第二个文件.如果您愿意,我可以发布一些准系统代码.

In terms of doing doing both downloads at once, there is no reason you can't just download them both sequentially in the ASyncTask like you do already. How you handle the ProgressBar in this case though is I guess the interesting part. I would probably just have the first 50% of the ProgressBar be the first file and the second half be the second file. I can post some barebones code if you'd like.

更新:

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

I think the following is a pretty elegant way of handling this. Could easily be extended to more than 2 files. I made some assumptions about the rest of your code, so it will require edits. There could be errors in this, I have not run it, but it should give you an idea where to go:

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());
    }
}

这篇关于带有下载进度条的启动画面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆