Android - 首先打开然后下载

时间:2011-09-11 03:44:10

标签: android download sharedpreferences

我正在尝试使用启动画面,然后在第一次打开应用程序时移动到下载屏幕。在应用程序第一次下载文件后,我希望它从启动画面到章节菜单屏幕再也不会打开下载程序活动

我有两个麻烦。

首先。我正在尝试使用共享偏好使其保存下载状态,并使用它来跳过下载器,如果以前曾经做过的话。我认为我不太了解共享偏好

二。下载进度脚本直接从0到100%。我尝试过使用Handler,我也试过使用runonUI但是没有运气。

任何帮助将不胜感激。我是java和android的新手。提前谢谢!

这是我的想法:

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

public class splashscreen extends Activity {
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle SavedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(SavedInstanceState);
    setContentView(R.layout.splashlayout);
    SharedPreferences myPrefs = this.getSharedPreferences("DOWNLOAD_STATUS", MODE_WORLD_READABLE);
    Update.storeDownloadStatusString(myPrefs.getString("DOWNLOAD_STATUS", "NotDownloaded"));
    Thread timer = new Thread(){
        public void run(){
            try{
                sleep(5000);
            }
            catch(InterruptedException e){
                e.printStackTrace();
            }
            finally{
                Intent checkDownloadIntentObject = new Intent("blah.blah.CHECKDOWNLOAD");
                Intent chapterMenuObject = new Intent("blah.blah.CHAPTERMENU");
                if (Update.getDownloadStatusString()=="NotDownloaded"){
                    startActivity(checkDownloadIntentObject);
                }else{
                    startActivity(chapterMenuObject);
                }
            }
        }

    };  
    timer.start();

    }

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    finish();
}
}

这是我的下载活动:

public class CheckDownload extends Activity {
    public static int downloadedSize;
    public static int totalSize;

// Called when the activity is first created. 
@Override
protected void onCreate(Bundle SavedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(SavedInstanceState);
    setContentView(R.layout.downloadscreen);
    SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
    final SharedPreferences.Editor prefsEditor = myPrefs.edit();
    Thread downloader = new Thread() {
        public void run() {
            try {
                // set the download URL, a url that points to a file on the
                // internet
                // this is the file to be downloaded
                URL url = new URL(
                        "http://insert.url.here.blah");

                // create the new connection
                HttpURLConnection urlConnection = (HttpURLConnection) url
                        .openConnection();

                // set up some things on the connection
                urlConnection.setRequestMethod("GET");
                urlConnection.setDoOutput(true);

                // and connect!
                urlConnection.connect();

                // set the path where we want to save the file
                // in this case, going to save it on the root directory of
                // the
                // sd card.

                File folderdestination = new File(
                        Environment.getExternalStorageDirectory()
                                + "/blah");
                folderdestination.mkdir();
                File file = new File(folderdestination, "blah.zip");

                // create a new file, specifying the path, and the filename
                // which we want to save the file as.
                String fileurl = file.getAbsolutePath();

                // this will be used to write the downloaded data into the
                // file we created
                FileOutputStream fileOutput = new FileOutputStream(file);

                // this will be used in reading the data from the internet
                InputStream inputStream = urlConnection.getInputStream();

                // this is the total size of the file
                int totalSize = urlConnection.getContentLength();
                // variable to store total downloaded bytes
                int downloadedSize = 0;

                // create a buffer...
                byte[] buffer = new byte[1024];
                int bufferLength = 0; // used to store a temporary size of
                                        // the buffer

                // now, read through the input buffer and write the contents
                // to the file
                while ((bufferLength = inputStream.read(buffer)) > 0) {
                    // add the data in the buffer to the file in the file
                    // output stream (the file on the sd card
                    fileOutput.write(buffer, 0, bufferLength);
                    // add up the size so we know how much is downloaded
                    downloadedSize += bufferLength;
                    // this is where you would do something to report the
                    // prgress, like this maybe
                    Update.setDS(downloadedSize);
                    Update.setTS(totalSize);
                    updateProgress();

                }
                // close the output stream when done
                fileOutput.close();
                Unzipper.unzip(fileurl);
                // catch some possible errors...
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                Intent chapterMenuIntentObject = new Intent(
                        "blah.blah.CHAPTERMENU");
                prefsEditor.putString("DOWNLOAD_STATUS", "Downloaded");
                prefsEditor.commit();
                startActivity(chapterMenuIntentObject);
            }

        }

    };
    downloader.start();

}

protected void updateProgress() {
    runOnUiThread(new Runnable() {
        public void run() {
            int dS=Update.getDS();
            int tS=Update.getTS();
            float percentage = dS / tS * 100;
            String stringy = "Downloading!\n\n" +
                    "This will only happen the first time you open this application.\n\n" +
                    "This may take several minutes. Please be patient.\n\n" +
                    "Download Progress: " + percentage + "%";
            TextView textytext = (TextView) findViewById(R.id.downloadscreentextview);
            textytext.setText(stringy);
        }
    });
}


@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    finish();
}

}

最后,这是update.java的代码:

public class Update{
public static int dsize;
public static int tsize;
public static String downloadStatusString;
public static void setDS(int ds){
    dsize=ds;
}
public static int getDS(){
    return dsize;
}
public static void setTS(int ts){
    tsize=ts;
}
public static int getTS(){
    return tsize;
}
public static void storeDownloadStatusString(String downloadStatus){
    downloadStatusString=downloadStatus;
}
public static String getDownloadStatusString(){
    return downloadStatusString;
}

}

1 个答案:

答案 0 :(得分:1)

您应该使用AsyncTask来正确处理下载。

您正在写一个偏好但是从另一个偏好中读取。