2015-12-03 103 views
2

我正在測試一個應用程序下載按鈕單擊文件。但是,當按鈕被點擊時,沒有任何反應。對話框出現並在幾分之一秒內消失。不知道什麼是錯 這裏是我的代碼下載沒有得到執行後按下按鈕

mainactivity

public class MainActivity extends Activity 
{ 
public static final int DIALOG_DOWNLOAD_PROGRESS = 0; 
private Button startBtn; 
    private ProgressDialog mProgressDialog; 

@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    startBtn = (Button) findViewById(R.id.mainButton); 

    startBtn.setOnClickListener(new OnClickListener(){ 

      @Override 
      public void onClick(View p1) 
      { 
       // TODO: Implement this method 
       startDownload(); 
      } 

     }); 
} 

private void startDownload() 
{ 
String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg"; 
new DownloadFileAsync().execute(url); 
} 
@Override protected Dialog onCreateDialog(int id) 
{ 
    switch (id) 
    { 
     case DIALOG_DOWNLOAD_PROGRESS: mProgressDialog = new ProgressDialog(this); 
     mProgressDialog.setMessage("Downloading file.."); 
     mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
     mProgressDialog.setCancelable(false); 
     mProgressDialog.show(); 
     return mProgressDialog; 
     default: return null; 
     } 
     } 
     class DownloadFileAsync extends AsyncTask<String, String, String> 
{ 
@Override protected void onPreExecute() 
    { 
     super.onPreExecute(); 
     showDialog(DIALOG_DOWNLOAD_PROGRESS); 
     } 
     @Override protected String doInBackground(String... aurl) 
    { 
    int count; 
    try 
     { 
     URL url = new URL(aurl[0]); 
     URLConnection conexion = url.openConnection(); conexion.connect(); 
     int lenghtOfFile = conexion.getContentLength(); 
     Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile); 
      InputStream input = new BufferedInputStream(url.openStream()); 
      OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg"); 
      byte data[] = new byte[1024]; 
      long total = 0; while ((count = input.read(data)) != -1) 
      { 
       total += count; 
       publishProgress("" + (int)((total * 100)/lenghtOfFile)); 
       output.write(data, 0, count); 
      } 
      output.flush(); 
      output.close(); 
      input.close(); 
     } 
     catch (Exception e) 
     { 
     } 
     return null; 
    } protected void onProgressUpdate(String... progress) 
    { 
     Log.d("ANDRO_ASYNC", progress[0]); 
     mProgressDialog.setProgress(Integer.parseInt(progress[0])); 
    } @Override protected void onPostExecute(String unused) 
    { 
     dismissDialog(DIALOG_DOWNLOAD_PROGRESS); 
    } 
    } 
} 

Android清單

<?xml version="1.0" encoding="utf-8"?> 

uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  


<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
     android:name=".MainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
</application> 

</manifest> 
+0

添加以下權限它顯示有些東西..'Log.d(「ANDRO_ASYNC」,「文件的長度:」+ lenghtOfFile);' –

+0

嘗試使用'InputStream input = conexion.getInputStream()'而不是'InputStream input =新的BufferedInputStream(url.openStream());'。 –

+0

@sourabhbans嘗試過,但同樣的問題,感謝您抽出寶貴的興趣 – user5524159

回答

0
Handler handler = new Handler(); 

    class DownloadFileAsync extends AsyncTask<Void, Integer, String> { 
     ProgressDialog progressDialog; 
     Context context; 
     String downloadUrl; 
     // shared preferences 
     SharedPreferences sharedPreferences; 
     int state; 

     public DownloadFileAsync(Context context, String downloadUrl) { 
      this.context = context; 
      this.downloadUrl = downloadUrl; 
     } 

     @Override 
     protected void onPreExecute() { 

       handler.post(new Runnable() { 
        @Override 
        public void run() { 
         progressDialog = new ProgressDialog(context); 
         progressDialog.setMessage("Downloading file. Please wait......"); 
         progressDialog.setIndeterminate(false); 
         progressDialog.setMax(100); 
         progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
         progressDialog.show(); 
        } 
       }); 
     } 

     @Override 
     protected void onProgressUpdate(Integer... values) { 
      super.onProgressUpdate(values); 
      progressDialog.setProgress(values[0]); 
     } 

     @Override 
     protected String doInBackground(Void... params) { 
      int count; 
      try { 
       URL url = new URL(downloadUrl.toString()); 
       URLConnection conection = url.openConnection(); 
       conection.setReadTimeout(5000); 
       conection.connect(); 
       // getting file length 
       int lenghtOfFile = conection.getContentLength(); 
       if (lenghtOfFile > 0) { 
        // input stream to read file - with 8k buffer 
        InputStream input = new BufferedInputStream(url.openStream(), 8192); 

        // Output stream to write file 
        OutputStream output = new FileOutputStream(
          Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) 
            + "/data.jpg"); 
        byte data[] = new byte[1024]; 

        long total = 0; 
        Log.d("lenghtOfFile", "---" + lenghtOfFile); 
        while ((count = input.read(data)) != -1) { 
         total += count; 
         // writing data to file 
         output.write(data, 0, count); 
         // publishing the progress. After this onProgressUpdate 
         // will be called 
         publishProgress((int) ((total * 100)/lenghtOfFile)); 
        } 

        // flushing output 
        output.flush(); 

        // closing streams 
        output.close(); 

        input.close(); 
       } 
      } catch (Exception e) { 
       Log.e("Error: ", e.getMessage()); 
      } 

      return null; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      super.onPostExecute(result); 

      if (progressDialog != null && progressDialog.isShowing()) { 
       progressDialog.dismiss(); 
      } 
     } 

    } 

上點擊按鈕調用它像下面

new DownloadFileAsync(MainActivity.this, url).execute(); 

它的工作原理,並在清單

<uses-permission android:name="android.permission.INTERNET"/> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
+0

有加下劃線下面記錄 – user5524159

+0

錯誤與此 //輸入流嘗試讀取文件中的註釋 - 具有8K緩衝 \t \t \t的InputStream輸入=新的BufferedInputStream(url.openStream( ),8192); –

+0

試過但同樣的問題 – user5524159

0

這裏是工作的代碼..

import java.io.DataOutputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 

import android.app.ProgressDialog; 
import android.media.AudioManager; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.os.Environment; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.widget.TextView; 

public class MainActivity extends AppCompatActivity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 


     try { 
      Thread.sleep(3000); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     Log.e("Starting : ", "Starting..."); 
     ((TextView) findViewById(R.id.status)).setText("Starting..."); 



     // execute this when the downloader must be fired 
     final getAppInfo downloadTask = new getAppInfo(); 
     downloadTask.execute("http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg"); 



    } 





     private class getAppInfo extends AsyncTask<String, String, String> { 
      /** The system calls this to perform work in a worker thread and 
       * delivers it the parameters given to AsyncTask.execute() */ 
      ProgressDialog dialog; 


      @Override 
      protected void onPreExecute() { 
        dialog = new ProgressDialog(MainActivity.this); 
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
        dialog.setMessage("Loading"); 
        dialog.setIndeterminate(false); 
        dialog.setCancelable(false); 
        dialog.setMax(100); 
        dialog.setProgress(100); 
        dialog.show(); 
       } 



      @Override 
      protected String doInBackground(String... urls) {      
       InputStream input = null; 
       OutputStream output = null; 
       HttpURLConnection connection = null; 
       try { 
        URL url = new URL(urls[0]); 
        connection = (HttpURLConnection) url.openConnection(); 

        connection.setDoOutput(true); 
        connection.setDoInput(true); 
        connection.setRequestMethod("POST"); 
        connection.setRequestProperty("Content-Type", "application/json"); 
        connection.setUseCaches(false); 
        connection.connect(); 


        String length = connection.getHeaderField("Content-length"); 
        Log.e("fileLength : ",""+length); 

        // expect HTTP 200 OK, so we don't mistakenly save error report 
        // instead of the file 
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { 
         return "Server returned HTTP " + connection.getResponseCode() 
           + " " + connection.getResponseMessage(); 
        } 

        // this will be useful to display download percentage 
        // might be -1: server did not report the length 
        int fileLength = connection.getContentLength(); 

        Log.e("fileLength : ",""+fileLength); 

        // download the file 
        input = connection.getInputStream(); 

//     final String resultt = org.apache.commons.io.IOUtils.toString(input, "UTF-8"); 
//     Log.e("Response : ",""+resultt); 

        output = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/testsql.jpg"); 

        byte data[] = new byte[4096]; 
        long total = 0; 
        int count; 
        while ((count = input.read(data)) != -1) { 
         // allow canceling with back button 
         if (isCancelled()) { 
          input.close(); 
          return null; 
         } 
         total += count; 
         // publishing the progress.... 
         if (fileLength > 0) // only if total length is known 
          publishProgress(""+(int) (total * 100/fileLength)); 
         output.write(data, 0, count); 
        } 
       } catch (Exception e) { 
        Log.e("exception : ",""+e.getMessage()); 
        return e.toString(); 
       } finally { 
        try { 
         if (output != null) 
          output.close(); 
         if (input != null) 
          input.close(); 
        } catch (IOException ignored) { 
        } 

        if (connection != null) 
         connection.disconnect(); 
       } 
       return null; 
      } 


      @Override 
      protected void onProgressUpdate(String... progress) { 
       Log.v("count",progress[0]); 
       dialog.setProgress(Integer.parseInt(progress[0])); 
      } 

      /** The system calls this to perform work in the UI thread and delivers 
       * the result from doInBackground() */ 
      @Override 
      protected void onPostExecute(String result) {  
       //dialog.setProgress(100); 
        if(dialog!=null) dialog.dismiss(); 
       } 
      } 

}