Пример #1
0
  private boolean unpackFile(ZipFile zip, byte[] buf, ZipEntry fileEntry, String name)
      throws IOException, FileNotFoundException {
    if (fileEntry == null) fileEntry = zip.getEntry(name);
    if (fileEntry == null)
      throw new FileNotFoundException("Can't find " + name + " in " + zip.getName());

    File outFile = new File(sGREDir, name);
    if (outFile.lastModified() == fileEntry.getTime() && outFile.length() == fileEntry.getSize())
      return false;

    File dir = outFile.getParentFile();
    if (!dir.exists()) dir.mkdirs();

    InputStream fileStream;
    fileStream = zip.getInputStream(fileEntry);

    OutputStream outStream = new FileOutputStream(outFile);

    while (fileStream.available() > 0) {
      int read = fileStream.read(buf, 0, buf.length);
      outStream.write(buf, 0, read);
    }

    fileStream.close();
    outStream.close();
    outFile.setLastModified(fileEntry.getTime());
    return true;
  }
Пример #2
0
  private void checkAndLaunchUpdate() {
    Log.i(LOG_FILE_NAME, "Checking for an update");

    int statusCode = 8; // UNEXPECTED_ERROR
    File baseUpdateDir = null;
    if (Build.VERSION.SDK_INT >= 8)
      baseUpdateDir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
    else baseUpdateDir = new File(Environment.getExternalStorageDirectory().getPath(), "download");

    File updateDir = new File(new File(baseUpdateDir, "updates"), "0");

    File updateFile = new File(updateDir, "update.apk");
    File statusFile = new File(updateDir, "update.status");

    if (!statusFile.exists() || !readUpdateStatus(statusFile).equals("pending")) return;

    if (!updateFile.exists()) return;

    Log.i(LOG_FILE_NAME, "Update is available!");

    // Launch APK
    File updateFileToRun = new File(updateDir, getPackageName() + "-update.apk");
    try {
      if (updateFile.renameTo(updateFileToRun)) {
        String amCmd =
            "/system/bin/am start -a android.intent.action.VIEW "
                + "-n com.android.packageinstaller/.PackageInstallerActivity -d file://"
                + updateFileToRun.getPath();
        Log.i(LOG_FILE_NAME, amCmd);
        Runtime.getRuntime().exec(amCmd);
        statusCode = 0; // OK
      } else {
        Log.i(LOG_FILE_NAME, "Cannot rename the update file!");
        statusCode = 7; // WRITE_ERROR
      }
    } catch (Exception e) {
      Log.i(LOG_FILE_NAME, "error launching installer to update", e);
    }

    // Update the status file
    String status = statusCode == 0 ? "succeeded\n" : "failed: " + statusCode + "\n";

    OutputStream outStream;
    try {
      byte[] buf = status.getBytes("UTF-8");
      outStream = new FileOutputStream(statusFile);
      outStream.write(buf, 0, buf.length);
      outStream.close();
    } catch (Exception e) {
      Log.i(LOG_FILE_NAME, "error writing status file", e);
    }

    if (statusCode == 0) System.exit(0);
  }
Пример #3
0
  public static final HTTPStream createHTTPStream(
      String address,
      boolean isPost,
      byte[] postData,
      String headers,
      int timeOutMs,
      int[] statusCode,
      StringBuffer responseHeaders,
      int numRedirectsToFollow) {
    // timeout parameter of zero for HttpUrlConnection is a blocking connect (negative value for
    // juce::URL)
    if (timeOutMs < 0) timeOutMs = 0;
    else if (timeOutMs == 0) timeOutMs = 30000;

    // headers - if not empty, this string is appended onto the headers that are used for the
    // request. It must therefore be a valid set of HTML header directives, separated by newlines.
    // So convert headers string to an array, with an element for each line
    String headerLines[] = headers.split("\\n");

    for (; ; ) {
      try {
        HttpURLConnection connection = (HttpURLConnection) (new URL(address).openConnection());

        if (connection != null) {
          try {
            connection.setInstanceFollowRedirects(false);
            connection.setConnectTimeout(timeOutMs);
            connection.setReadTimeout(timeOutMs);

            // Set request headers
            for (int i = 0; i < headerLines.length; ++i) {
              int pos = headerLines[i].indexOf(":");

              if (pos > 0 && pos < headerLines[i].length()) {
                String field = headerLines[i].substring(0, pos);
                String value = headerLines[i].substring(pos + 1);

                if (value.length() > 0) connection.setRequestProperty(field, value);
              }
            }

            if (isPost) {
              connection.setRequestMethod("POST");
              connection.setDoOutput(true);

              if (postData != null) {
                OutputStream out = connection.getOutputStream();
                out.write(postData);
                out.flush();
              }
            }

            HTTPStream httpStream = new HTTPStream(connection, statusCode, responseHeaders);

            // Process redirect & continue as necessary
            int status = statusCode[0];

            if (--numRedirectsToFollow >= 0
                && (status == 301 || status == 302 || status == 303 || status == 307)) {
              // Assumes only one occurrence of "Location"
              int pos1 = responseHeaders.indexOf("Location:") + 10;
              int pos2 = responseHeaders.indexOf("\n", pos1);

              if (pos2 > pos1) {
                String newLocation = responseHeaders.substring(pos1, pos2);
                // Handle newLocation whether it's absolute or relative
                URL baseUrl = new URL(address);
                URL newUrl = new URL(baseUrl, newLocation);
                String transformedNewLocation = newUrl.toString();

                if (transformedNewLocation != address) {
                  address = transformedNewLocation;
                  // Clear responseHeaders before next iteration
                  responseHeaders.delete(0, responseHeaders.length());
                  continue;
                }
              }
            }

            return httpStream;
          } catch (Throwable e) {
            connection.disconnect();
          }
        }
      } catch (Throwable e) {
      }

      return null;
    }
  }
Пример #4
0
    @Override
    protected String doInBackground(String... sUrl) {

      File folders = new File(Environment.getExternalStorageDirectory() + "/pathofthefile/");
      folders.mkdirs();

      File file;
      file =
          new File(
              Environment.getExternalStorageDirectory()
                  + "/pathofthefile/"
                  + FirstSettings_two.file_video);

      if (!file.exists()) {
        try {
          file.createNewFile();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      } else {
        file.delete();
        try {
          file.createNewFile();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }

      try {
        URL url = new URL(sUrl[0]);
        URLConnection connection = url.openConnection();
        connection.connect();
        // this will be useful so that you can show a typical 0-100%
        // progress bar
        int fileLength = connection.getContentLength();

        // download the file
        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new FileOutputStream(file);

        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
          total += count;
          // publishing the progress....
          publishProgress((int) (total * 100 / fileLength));
          output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();
        return "Downloaded";
      } catch (Exception e) {
        //   Toast.makeText(context,
        //         "exeption",Toast.LENGTH_LONG).show();

        return null;
      }
    }
    protected Boolean doInBackground(ArrayList... params) {
      download_photos.this.runOnUiThread(
          new Runnable() {
            public void run() {
              mtext.setText(
                  getText(R.string.download_textview_message_1) + " " + path.toString() + ". ");
            }
          });

      if (resume_file.exists()) {
        initial_value = readProgress()[0];
      } else {
        initial_value = 1;
      }

      for (int i = initial_value - 1; i < links.size(); i++) {
        // asynctask expects more than one ArrayList<String> item, but we are sending only one,
        // which is params[0]
        Uri imageuri = Uri.parse(params[0].get(i).toString());
        URL imageurl = null;
        HttpURLConnection connection = null;
        total_files_to_download = links.size();
        completed_downloads = i + 1;
        try {
          imageurl = new URL(params[0].get(i).toString());
          connection = (HttpURLConnection) imageurl.openConnection();
          connection.connect();
        } catch (Exception e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }

        // extracts the real file name of the photo from url
        path_segments = imageuri.getPathSegments();
        int total_segments = path_segments.size();
        file_name = path_segments.get(total_segments - 1);

        path.mkdirs();

        // if(i==0)
        //	first_image = path.toString() + "/" + file_name;

        InputStream input;
        OutputStream output;
        try {
          input = new BufferedInputStream(imageurl.openStream());
          fully_qualified_file_name = new File(path, file_name);
          output = new BufferedOutputStream(new FileOutputStream(fully_qualified_file_name));
          byte data[] = new byte[1024];
          int count;
          while ((count = input.read(data)) != -1) {
            output.write(data, 0, count);
          }
          output.flush();
          output.close();
          input.close();
          connection.disconnect();

          new folder_scanner(getApplicationContext(), fully_qualified_file_name);

          publishProgress(completed_downloads, total_files_to_download);
          if (this.isCancelled()) {
            writeProgress(completed_downloads, total_files_to_download);
            break;
          }

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

        // creates required folders and subfolders if they do not exist already
        // boolean success = path.mkdirs();

        // makes request to download photos
        // DownloadManager.Request request = new DownloadManager.Request(imageuri);

        // set path for downloads
        // request.setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES,sub_path);

        // request.setDescription("Downloaded using Facebook Album Downloader");

        // DownloadManager dm = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);

        // download is enqueue in download list. it returns unique id for each download
        // download_id = dm.enqueue(request);

      }
      // returns the unique id. we are not using this id
      return true;
    }