Advertisement
pawelnowacki

Untitled

Jun 30th, 2016
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.38 KB | None | 0 0
  1. import java.io.FileInputStream;
  2. import java.io.FileNotFoundException;
  3. import java.io.IOException;
  4.  
  5. import org.json.JSONArray;
  6. import org.json.JSONException;
  7. import org.json.JSONObject;
  8.  
  9. import com.google.gson.Gson;
  10.  
  11. import android.net.Uri;
  12. import android.os.Bundle;
  13. import android.os.Environment;
  14. import android.os.ParcelFileDescriptor;
  15. import android.app.Activity;
  16. import android.app.DownloadManager;
  17. import android.app.DownloadManager.Query;
  18. import android.content.BroadcastReceiver;
  19. import android.content.Context;
  20. import android.content.Intent;
  21. import android.content.IntentFilter;
  22. import android.database.Cursor;
  23. import android.view.Gravity;
  24. import android.view.Menu;
  25. import android.view.View;
  26. import android.view.View.OnClickListener;
  27. import android.widget.Button;
  28. import android.widget.TextView;
  29. import android.widget.Toast;
  30.  
  31. public class DownloadDataActivity extends Activity implements OnClickListener{
  32.  
  33.  private DownloadManager downloadManager;
  34.  private long downloadReference;
  35.  
  36.  @Override
  37.  public void onCreate(Bundle savedInstanceState) {
  38.   super.onCreate(savedInstanceState);
  39.   setContentView(R.layout.activity_download_data);
  40.  
  41.   //start download button
  42.   Button startDownload = (Button) findViewById(R.id.startDownload);
  43.   startDownload.setOnClickListener(this);
  44.  
  45.   //display all download button
  46.   Button displayDownload = (Button) findViewById(R.id.displayDownload);
  47.   displayDownload.setOnClickListener(this);
  48.  
  49.   //check download status button
  50.   Button checkStatus = (Button) findViewById(R.id.checkStatus);
  51.   checkStatus.setOnClickListener(this);
  52.   checkStatus.setEnabled(false);
  53.  
  54.   //cancel download button
  55.   Button cancelDownload = (Button) findViewById(R.id.cancelDownload);
  56.   cancelDownload.setOnClickListener(this);
  57.   cancelDownload.setEnabled(false);
  58.  
  59.   //set filter to only when download is complete and register broadcast receiver
  60.   IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
  61.   registerReceiver(downloadReceiver, filter);
  62.  }
  63.  
  64.  public void onClick(View v) {
  65.  
  66.   switch (v.getId()) {
  67.  
  68.   //start the download process
  69.   case R.id.startDownload:
  70.  
  71.    downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
  72.    Uri Download_Uri = Uri.parse("http://demo.mysamplecode.com/Sencha_Touch/CountryServlet?start=0&limit=999");
  73.    DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
  74.    
  75.    //Restrict the types of networks over which this download may proceed.
  76.    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
  77.    //Set whether this download may proceed over a roaming connection.
  78.    request.setAllowedOverRoaming(false);
  79.    //Set the title of this download, to be displayed in notifications (if enabled).
  80.    request.setTitle("My Data Download");
  81.    //Set a description of this download, to be displayed in notifications (if enabled)
  82.    request.setDescription("Android Data download using DownloadManager.");
  83.    //Set the local destination for the downloaded file to a path within the application's external files directory
  84.    request.setDestinationInExternalFilesDir(this,Environment.DIRECTORY_DOWNLOADS,"CountryList.json");
  85.  
  86.    //Enqueue a new download and same the referenceId
  87.    downloadReference = downloadManager.enqueue(request);
  88.    
  89.    TextView showCountries = (TextView) findViewById(R.id.countryData);
  90.    showCountries.setText("Getting data from Server, Please WAIT...");
  91.    
  92.    Button checkStatus = (Button) findViewById(R.id.checkStatus);
  93.    checkStatus.setEnabled(true);
  94.    Button cancelDownload = (Button) findViewById(R.id.cancelDownload);
  95.    cancelDownload.setEnabled(true);
  96.    break;
  97.  
  98.   //display all downloads
  99.   case R.id.displayDownload:
  100.  
  101.    Intent intent = new Intent();
  102.    intent.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
  103.    startActivity(intent);
  104.    break;
  105.  
  106.   //check the status of a download
  107.   case R.id.checkStatus:
  108.  
  109.    Query myDownloadQuery = new Query();
  110.    //set the query filter to our previously Enqueued download
  111.    myDownloadQuery.setFilterById(downloadReference);
  112.  
  113.    //Query the download manager about downloads that have been requested.
  114.    Cursor cursor = downloadManager.query(myDownloadQuery);
  115.    if(cursor.moveToFirst()){
  116.     checkStatus(cursor);
  117.    }
  118.    break;
  119.  
  120.   //cancel the ongoing download
  121.   case R.id.cancelDownload:
  122.  
  123.    downloadManager.remove(downloadReference);
  124.    checkStatus = (Button) findViewById(R.id.checkStatus);
  125.    checkStatus.setEnabled(false);
  126.    showCountries = (TextView) findViewById(R.id.countryData);
  127.    showCountries.setText("Download of the file cancelled...");
  128.    
  129.    break;
  130.  
  131.    // More buttons go here (if any) ...
  132.  
  133.   }
  134.  }
  135.  
  136.  @Override
  137.  public boolean onCreateOptionsMenu(Menu menu) {
  138.   getMenuInflater().inflate(R.menu.activity_download_data, menu);
  139.   return true;
  140.  }
  141.  
  142.  private void checkStatus(Cursor cursor){
  143.  
  144.   //column for status
  145.   int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
  146.   int status = cursor.getInt(columnIndex);
  147.   //column for reason code if the download failed or paused
  148.   int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
  149.   int reason = cursor.getInt(columnReason);
  150.   //get the download filename
  151.   int filenameIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
  152.   String filename = cursor.getString(filenameIndex);
  153.  
  154.   String statusText = "";
  155.   String reasonText = "";
  156.  
  157.   switch(status){
  158.   case DownloadManager.STATUS_FAILED:
  159.    statusText = "STATUS_FAILED";
  160.    switch(reason){
  161.    case DownloadManager.ERROR_CANNOT_RESUME:
  162.     reasonText = "ERROR_CANNOT_RESUME";
  163.     break;
  164.    case DownloadManager.ERROR_DEVICE_NOT_FOUND:
  165.     reasonText = "ERROR_DEVICE_NOT_FOUND";
  166.     break;
  167.    case DownloadManager.ERROR_FILE_ALREADY_EXISTS:
  168.     reasonText = "ERROR_FILE_ALREADY_EXISTS";
  169.     break;
  170.    case DownloadManager.ERROR_FILE_ERROR:
  171.     reasonText = "ERROR_FILE_ERROR";
  172.     break;
  173.    case DownloadManager.ERROR_HTTP_DATA_ERROR:
  174.     reasonText = "ERROR_HTTP_DATA_ERROR";
  175.     break;
  176.    case DownloadManager.ERROR_INSUFFICIENT_SPACE:
  177.     reasonText = "ERROR_INSUFFICIENT_SPACE";
  178.     break;
  179.    case DownloadManager.ERROR_TOO_MANY_REDIRECTS:
  180.     reasonText = "ERROR_TOO_MANY_REDIRECTS";
  181.     break;
  182.    case DownloadManager.ERROR_UNHANDLED_HTTP_CODE:
  183.     reasonText = "ERROR_UNHANDLED_HTTP_CODE";
  184.     break;
  185.    case DownloadManager.ERROR_UNKNOWN:
  186.     reasonText = "ERROR_UNKNOWN";
  187.     break;
  188.    }
  189.    break;
  190.   case DownloadManager.STATUS_PAUSED:
  191.    statusText = "STATUS_PAUSED";
  192.    switch(reason){
  193.    case DownloadManager.PAUSED_QUEUED_FOR_WIFI:
  194.     reasonText = "PAUSED_QUEUED_FOR_WIFI";
  195.     break;
  196.    case DownloadManager.PAUSED_UNKNOWN:
  197.     reasonText = "PAUSED_UNKNOWN";
  198.     break;
  199.    case DownloadManager.PAUSED_WAITING_FOR_NETWORK:
  200.     reasonText = "PAUSED_WAITING_FOR_NETWORK";
  201.     break;
  202.    case DownloadManager.PAUSED_WAITING_TO_RETRY:
  203.     reasonText = "PAUSED_WAITING_TO_RETRY";
  204.     break;
  205.    }
  206.    break;
  207.   case DownloadManager.STATUS_PENDING:
  208.    statusText = "STATUS_PENDING";
  209.    break;
  210.   case DownloadManager.STATUS_RUNNING:
  211.    statusText = "STATUS_RUNNING";
  212.    break;
  213.   case DownloadManager.STATUS_SUCCESSFUL:
  214.    statusText = "STATUS_SUCCESSFUL";
  215.    reasonText = "Filename:\n" + filename;
  216.    break;
  217.   }
  218.  
  219.  
  220.   Toast toast = Toast.makeText(DownloadDataActivity.this,
  221.     statusText + "\n" +
  222.     reasonText,
  223.     Toast.LENGTH_LONG);
  224.   toast.setGravity(Gravity.TOP, 25, 400);
  225.   toast.show();
  226.  
  227.  }
  228.  
  229.  private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
  230.  
  231.   @Override
  232.   public void onReceive(Context context, Intent intent) {
  233.    
  234.    //check if the broadcast message is for our Enqueued download
  235.    long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
  236.    if(downloadReference == referenceId){
  237.    
  238.     Button cancelDownload = (Button) findViewById(R.id.cancelDownload);
  239.     cancelDownload.setEnabled(false);
  240.    
  241.     int ch;
  242.     ParcelFileDescriptor file;
  243.     StringBuffer strContent = new StringBuffer("");
  244.     StringBuffer countryData = new StringBuffer("");
  245.    
  246.     //parse the JSON data and display on the screen
  247.     try {
  248.      file = downloadManager.openDownloadedFile(downloadReference);
  249.      FileInputStream fileInputStream
  250.      = new ParcelFileDescriptor.AutoCloseInputStream(file);
  251.  
  252.      while( (ch = fileInputStream.read()) != -1)
  253.       strContent.append((char)ch);
  254.      
  255.      JSONObject responseObj = new JSONObject(strContent.toString());
  256.      JSONArray countriesObj = responseObj.getJSONArray("countries");
  257.  
  258.      for (int i=0; i<countriesObj.length(); i++){
  259.       Gson gson = new Gson();
  260.       String countryInfo = countriesObj.getJSONObject(i).toString();
  261.       Country country = gson.fromJson(countryInfo, Country.class);
  262.       countryData.append(country.getCode() + ": " + country.getName() +"\n");
  263.      }
  264.      
  265.      TextView showCountries = (TextView) findViewById(R.id.countryData);
  266.      showCountries.setText(countryData.toString());
  267.      
  268.      Toast toast = Toast.makeText(DownloadDataActivity.this,
  269.        "Downloading of data just finished", Toast.LENGTH_LONG);
  270.      toast.setGravity(Gravity.TOP, 25, 400);
  271.      toast.show();
  272.      
  273.     } catch (FileNotFoundException e) {
  274.      e.printStackTrace();
  275.     } catch (IOException e) {
  276.      e.printStackTrace();
  277.     } catch (JSONException e) {
  278.      e.printStackTrace();
  279.     }
  280.  
  281.    }
  282.   }
  283.  };
  284. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement