Download-Image-AsyncTask







📋
function doGet(e) {
    var json = convertSheet2JsonText();
    var stringified = JSON.stringify(json);
    return ContentService.createTextOutput(stringified)
    .setMimeType(ContentService.MimeType.JSON);
  
}
function convertSheet2JsonText() {
 //XXXX is the id of the spreadsheet.ID is in the spreadsheet url - https://docs.google.com/spreadsheets/d/XXXX/edit#gid=0  
 var sheet = SpreadsheetApp.openById("1b_mq5EuTpID6MnXKbZ3URzOhRqUEjPj3neadD-NhV-I").getActiveSheet();
  var colStartIndex = 1;
  var rowNum = 1;
  var firstRange = sheet.getRange(1, 1, 1, sheet.getLastColumn());
  var firstRowValues = firstRange.getValues();
  var titleColumns = firstRowValues[0];
  
  // after the second line(data)  var lastRow = sheet.getLastRow();
  var rowValues = [];
  for(var rowIndex=2; rowIndex<=lastRow; rowIndex++) {
    var colStartIndex = 1;
    var rowNum = 1;
    var range = sheet.getRange(rowIndex, colStartIndex, rowNum, sheet.getLastColumn());
    var values = range.getValues();
  
    rowValues.push(values[0]);
  }
 
  var jsonArray = [];
  for(var i=0; i<rowValues.length; i++) {
    var line = rowValues[i];
    var json = new Object();
    for(var j=0; j<titleColumns.length; j++) {
      json[titleColumns[j]] = line[j];
    }
    jsonArray.push(json);
  }
  return jsonArray ;
}
  



📋
image
sim
https://3.bp.blogspot.com/-PEB72IInj9A/WlFd-DWRLfI/AAAAAAAAImw/XTzTzskSBRMvnOj__sOz2-oh3jnJZq_BACLcBGAs/s1600/mail.png
https://2.bp.blogspot.com/-FG1Jdw6dx1M/WlFd-NxO6aI/AAAAAAAAIms/SOfwgy0wt7g5LmO_MSGfUw1MM3Thx47kgCLcBGAs/s1600/mao.png
https://4.bp.blogspot.com/-tm53UIwP8zU/V_VpR_hUdoI/AAAAAAAAAm0/pXYNuj_B4YA8bvk77p584YY_4k0GF7rnACLcB/s1600/ic_launcher.jpg
https://3.bp.blogspot.com/-XE1DAUgoqSo/V_kA7svxuNI/AAAAAAAAAoo/A70jXHIBvfEOCyCnY6x5wQFshFGfSlmIQCEw/s1600/eng.png
https://1.bp.blogspot.com/-vIMcDaQ1bvI/V_kA6jtt10I/AAAAAAAAAoI/-9ElWtdtCGoJ6nLMDYFgLD5LqF1fdxBxQCEw/s1600/blogspot.png
https://4.bp.blogspot.com/-4VMWTSTplBU/V_kA7lXp1qI/AAAAAAAAAos/BIjDCG4f1yIUuzchF8F1D_p97H_o1toiQCEw/s1600/face.png
https://2.bp.blogspot.com/-zWbEYPdIFD4/V_kA77IKPxI/AAAAAAAAAo4/hQwRwbu-nwQbiYDvOVKAJLWUtV9QvrMAQCEw/s1600/m.png
https://2.bp.blogspot.com/-BNRBcD9MOfM/V_kA8CgtZ6I/AAAAAAAAApA/RHTU5nksVc46bGL28-SFkB7f41FXLyjcQCEw/s1600/twitter.png
https://2.bp.blogspot.com/-Uqvk2fqNQ_I/V_kA78STq_I/AAAAAAAAAo0/1EijLaSFGGIl--mdiYqzDUS6zZ3FP013QCEw/s1600/linked.png
https://4.bp.blogspot.com/-ENbs6ajzpbs/V_kA8L8XREI/AAAAAAAAAo8/ym9uJs7EWXMPzlBWL9Ryo4EXQkWJDwzFQCEw/s1600/tube.png
https://1.bp.blogspot.com/-3s4i7Kl7kpU/V_kA7vMyFQI/AAAAAAAAAok/_duknemlbqQPjqSQt9pYgn7urKF9YqPKACEw/s1600/def.png



📋


// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'        
        
// NOTE: Do not place your application dependencies here; they belong        
// in the individual module build.gradle files    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}




📋

apply plugin: 'com.android.application'
android {
    compileSdkVersion 27    
 useLibrary 'org.apache.http.legacy'
     defaultConfig {
        applicationId "aksr.downloadfilewithasynctask"        
  minSdkVersion 16        
  targetSdkVersion 27        
  versionCode 1        
  versionName "1.0"        
  testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
      }
    buildTypes {
        release {
            minifyEnabled false            
   proguardFiles getDefaultProguardFile('proguard-android.txt'), 
   'proguard-rules.pro'        
   }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.mcxiaoke.volley:library:1.0.19'
 compile 'com.google.code.gson:gson:2.8.2'
 compile 'com.squareup.okhttp3:okhttp:3.9.1'
    compile 'com.android.support:appcompat-v7:+'   
 }






📋
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"    
package="aksr.downloadfilewithasynctask">
<uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name='android.permission.WRITE_EXTERNAL_STORAGE' />
    <uses-permission android:name='android.permission.WRITE_INTERNAL_STORAGE'/>
    <uses-permission android:name='android.permission.READ_EXTERNAL_STORAGE'/>
    <uses-permission android:name='android.permission.READ_INTERNAL_STORAGE'/>
    <application
 android:allowBackup="true"
 android:name=".App"        
 android:icon="@drawable/folder"        
 android:label="@string/app_name"        
 android:roundIcon="@drawable/folder"        
 android:supportsRtl="true"        
 android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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







📋

package aksr.downloadfilewithasynctask.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import aksr.downloadfilewithasynctask.MainActivity;
import aksr.downloadfilewithasynctask.R;

public class CustomAdapter extends BaseAdapter{
    String [] result;
    String[] imageId;
    private Activity ctx;
    private static LayoutInflater inflater=null;
    public CustomAdapter(MainActivity mainActivity, String[] prgmNameList, String[] prgmImages) {
        result=prgmNameList;
        ctx=mainActivity;
        imageId=prgmImages;
        inflater = ( LayoutInflater )ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
public int getCount() {
        return result.length;
    }

    @Override
public Object getItem(int position) {
        return position;
    }

    @Override
public long getItemId(int position) {
        return position;
    }

    public class Holder {
        TextView tv;
        ImageView img;
    }
    @Override
public View getView(final int position, View convertView, ViewGroup parent) {
        Holder viewHolder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(ctx).inflate(R.layout.lista, null);
            viewHolder = new Holder();

            viewHolder.tv =  (TextView)convertView.findViewById(R.id.Itemname);
            viewHolder.img=  (ImageView)convertView.findViewById(R.id.icon);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (Holder) convertView.getTag();
        }

        viewHolder.tv.setText(result[position]);
        Bitmap bitmap = BitmapFactory.decodeFile(String.valueOf(imageId[position]));
        viewHolder.img.setImageBitmap(bitmap);

        convertView.setOnClickListener(new OnClickListener() {
            @Override
public void onClick(View v) {
                Toast.makeText(ctx, ""+result[position], Toast.LENGTH_LONG).show();
            }
        });
        return convertView;
    }
}







📋

package aksr.downloadfilewithasynctask.json.dataModel;

public class DummyObject {

  private String mImage;
  private String mBaixar;

  public String getImage() {
    return mImage;
  }

  public void setImage(String Image) {
    this.mImage = Image;
  }

  public String getBaixar() {
    return mBaixar;
  }

  public void setBaixar(String Baixar) {
    this.mBaixar = Baixar;
  }
}



📋

package aksr.downloadfilewithasynctask.json.dataModel;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
public class DummyObjectDeserializer implements JsonDeserializer<DummyObject> {
  @Override  
public DummyObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    final DummyObject dummyObject = new DummyObject();
    final JsonObject jsonObject = json.getAsJsonObject();

    if(jsonObject.has("baixar")){
      if(!jsonObject.get("baixar").toString().equals("null")){
        dummyObject.setBaixar(jsonObject.get("baixar").getAsString());
      }else{
        dummyObject.setBaixar("null");
      }
    }

    if(jsonObject.has("image")){
      if(!jsonObject.get("image").toString().equals("null")){
        dummyObject.setImage(jsonObject.get("image").getAsString());
      }else{
        dummyObject.setImage("null");
      }
    }

    return dummyObject;
  }
}





📋
package aksr.downloadfilewithasynctask.json.others;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.toolbox.HttpStack;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicStatusLine;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;


public class OkHttp3Stack implements HttpStack {

  public OkHttp3Stack() {
  }

  private static HttpEntity entityFromOkHttpResponse(Response r) throws IOException {
    BasicHttpEntity entity = new BasicHttpEntity();
    ResponseBody body = r.body();

    assert body != null;
    entity.setContent(body.byteStream());
    entity.setContentLength(body.contentLength());
    entity.setContentEncoding(r.header("Content-Encoding"));

    if (body.contentType() != null) {
      //noinspection ConstantConditions      entity.setContentType(body.contentType().type());
    }
    return entity;
  }

  @SupspanssWarnings("despancation")
  private static void setConnectionParametersForRequest(okhttp3.Request.Builder builder,
      com.android.volley.Request<?> request)
      throws IOException, AuthFailureError {
    switch (request.getMethod()) {
      case Request.Method.DEPRECATED_GET_OR_POST:
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
          builder.post(RequestBody
              .create(MediaType.parse(request.getPostBodyContentType()), postBody));
        }
        break;
      case Request.Method.GET:
        builder.get();
        break;
      case Request.Method.DELETE:
        builder.delete();
        break;
      case Request.Method.POST:
        //noinspection ConstantConditions        builder.post(createRequestBody(request));
        break;
      case Request.Method.PUT:
        //noinspection ConstantConditions        builder.put(createRequestBody(request));
        break;
      case Request.Method.HEAD:
        builder.head();
        break;
      case Request.Method.OPTIONS:
        builder.method("OPTIONS", null);
        break;
      case Request.Method.TRACE:
        builder.method("TRACE", null);
        break;
      case Request.Method.PATCH:
        //noinspection ConstantConditions        builder.patch(createRequestBody(request));
        break;
      default:
        throw new IllegalStateException("Unknown method type.");
    }
  }

  private static ProtocolVersion parseProtocol(final Protocol p) {
    switch (p) {
      case HTTP_1_0:
        return new ProtocolVersion("HTTP", 1, 0);
      case HTTP_1_1:
        return new ProtocolVersion("HTTP", 1, 1);
      //noinspection despancation      case SPDY_3:
        return new ProtocolVersion("SPDY", 3, 1);
      case HTTP_2:
        return new ProtocolVersion("HTTP", 2, 0);
    }

    throw new IllegalAccessError("Unkwown protocol");
  }

  private static RequestBody createRequestBody(Request r) throws AuthFailureError {
    final byte[] body = r.getBody();
    if (body == null) {
      return null;
    }

    return RequestBody.create(MediaType.parse(r.getBodyContentType()), body);
  }

  @Override  public HttpResponse performRequest(com.android.volley.Request<?> request,
      Map<String, String> additionalHeaders)
      throws IOException, AuthFailureError {

    OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
    int timeoutMs = request.getTimeoutMs();

    clientBuilder.connectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    clientBuilder.readTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    clientBuilder.writeTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    okhttp3.Request.Builder okHttpRequestBuilder = new okhttp3.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
      okHttpRequestBuilder.addHeader(name, headers.get(name));
    }
    for (final String name : additionalHeaders.keySet()) {
      okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    OkHttpClient client = clientBuilder.build();
    okhttp3.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()),
        okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
      final String name = responseHeaders.name(i), value = responseHeaders.value(i);
      if (name != null) {
        response.addHeader(new BasicHeader(name, value));
      }
    }
    return response;
  }
}






📋
package aksr.downloadfilewithasynctask.json;


import android.support.annotation.NonNull;
import com.android.volley.Response;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import aksr.downloadfilewithasynctask.json.dataModel.DummyObject;
import aksr.downloadfilewithasynctask.json.dataModel.DummyObjectDeserializer;

public class ApiRequests {
  private static final Gson gson = new GsonBuilder()
      .registerTypeAdapter(DummyObject.class, new DummyObjectDeserializer())
      .create();

  public static GsonGetRequest<DummyObject> getDummyObjectOBJECT
      (@NonNull final Response.Listener<DummyObject> listener,
          @NonNull final Response.ErrorListener errorListener
      ) {
      final String url = "url";//OBJECT
       return new GsonGetRequest<>
        (
            url,
            new TypeToken<DummyObject>() {
            }.getType(),
            gson,
            listener,
            errorListener
        );
  }

    public static GsonGetRequest<ArrayList<DummyObject>> getDummyObjectARRAY
            (@NonNull final Response.Listener<ArrayList<DummyObject>> listener,
             @NonNull final Response.ErrorListener errorListener
            ) {

        final String url ="https://script.google.com/macros/s/AKfycbzSfFoKjJXduXjJFVc36ZGXpD0601EuUjqCiFbqURZj0ZS6PH0/exec";//ARRAY
          return new GsonGetRequest<>
                (
                        url,
                        new TypeToken<ArrayList<DummyObject>>() {
                        }.getType(),
                        gson,
                        listener,
                        errorListener
                );
    }

}







📋
package aksr.downloadfilewithasynctask.json;

import android.support.annotation.NonNull;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;

public class GsonGetRequest<T> extends Request<T> {

  private final Gson gson;
  private final Type type;
  private final Response.Listener<T> listener;

  public GsonGetRequest
      (
          @NonNull final String url,
          @NonNull final Type type,
          @NonNull final Gson gson,
          @NonNull final Response.Listener<T> listener,
          @NonNull final Response.ErrorListener errorListener
      ) {
    super(Method.GET, url, errorListener);

    this.gson = gson;
    this.type = type;
    this.listener = listener;
  }

  @Override  protected void deliverResponse(T response) {
    listener.onResponse(response);
  }

  @Override  protected Response<T> parseNetworkResponse(NetworkResponse response) {
    try {
      String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));

      //noinspection unchecked      return (Response<T>) Response.success          (
              gson.fromJson(json, type),
              HttpHeaderParser.parseCacheHeaders(response)
          );
    } catch (UnsupportedEncodingException e) {
      return Response.error(new ParseError(e));
    } catch (JsonSyntaxException e) {
      return Response.error(new ParseError(e));
    }
  }
}








📋
package aksr.downloadfilewithasynctask.json;

import android.support.annotation.NonNull;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;

public class GsonPostRequest<T> extends JsonRequest<T> {

  private final Gson gson;
  private final Type type;
  private final Response.Listener<T> listener;
  public GsonPostRequest
      (
          @NonNull final String url,
          @NonNull final String body,
          @NonNull final Type type,
          @NonNull final Gson gson,
          @NonNull final Response.Listener<T> listener,
          @NonNull final Response.ErrorListener errorListener
      ) {
    super(Method.POST, url, body, listener, errorListener);

    this.gson = gson;
    this.type = type;
    this.listener = listener;
  }

  @Override
  protected void deliverResponse(T response) {
    listener.onResponse(response);
  }

  @Override  protected Response<T> parseNetworkResponse(NetworkResponse response) {
    try {
      String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
      //noinspection unchecked
      return (Response<T>) Response.success          (
              gson.fromJson(json, type),
              HttpHeaderParser.parseCacheHeaders(response)
          );
    } catch (UnsupportedEncodingException e) {
      return Response.error(new ParseError(e));
      return Response.error(new ParseError(e));
    } catch (JsonSyntaxException e) {
      return Response.error(new ParseError(e));
    }
  }
}








📋
package aksr.downloadfilewithasynctask;

import android.app.Application;
import android.support.annotation.NonNull;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import aksr.downloadfilewithasynctask.json.others.OkHttp3Stack;

public class App extends Application {
    private RequestQueue mRequestQueue;
    private static App sInstance;
    public static App getInstance() {
        return sInstance;
    }
    private static void addRequest(@NonNull final Request<?> request) {
        getInstance().getVolleyRequestQueue().add(request);
    }
    public static void addRequest(@NonNull final Request<?> request, @NonNull final String tag) {
        request.setTag(tag);
        addRequest(request);
    }
    public static void cancelAllRequests(@NonNull final String tag) {
        getInstance().getVolleyRequestQueue().cancelAll(tag);
    }
    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;
    }
    @NonNull
    public RequestQueue getVolleyRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(this, new OkHttp3Stack());
        }
        return mRequestQueue;
    }
    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }
    @Override
    public void onTerminate() {
        super.onTerminate();
    }


}




📋
package aksr.downloadfilewithasynctask;

import aksr.downloadfilewithasynctask.adapter.*;
import aksr.downloadfilewithasynctask.json.*;
import aksr.downloadfilewithasynctask.json.dataModel.*;
import android.*;
import android.annotation.*;
import android.content.*;
import android.content.pm.*;
import android.net.*;
import android.os.*;
import android.support.annotation.*;
import android.support.v4.app.*;
import android.support.v4.content.*;
import android.support.v7.app.*;
import android.view.*;
import android.widget.*;
import com.android.volley.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class MainActivity extends AppCompatActivity {
    int permission;
    SeekBar progressBar4;
    public static File folder;
    private String[] mFileStrings;
    private String[] mFileImages;
    public static String[] imageURLArray;
    public static OutputStream output;
    Button permissao;
    Button Folder;
    long totalNumFiles;
    ListView list;
    CustomAdapter listAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        permission = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        folder = new File(Environment.getExternalStorageDirectory() + File.separator + "/MyAppName");
        if(folder.canRead()){ totalNumFiles = folder.listFiles().length; CarregarDados();}
        Folder =  (Button)findViewById(R.id.folder);
        if (totalNumFiles>0) {
            Folder.setVisibility(View.VISIBLE);
        }
        Folder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Folder();
            }
        });
        permissao =  (Button)findViewById(R.id.permissao);
        permissao.setVisibility(View.GONE);
        permissao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                performRequest();
            }
        });
        
        progressBar4 =  (SeekBar)findViewById(R.id.progressBar4);
        progressBar4.setClickable(false);
        progressBar4.setEnabled(false);
        progressBar4.setMax(100);
        progressBar4.setVisibility(View.GONE);

        if (totalNumFiles==0) {
            performRequest();
        }
        
    }
    public void performRequest() {
         GsonGetRequest<ArrayList<DummyObject>> gsonGetRequest =
                ApiRequests.getDummyObjectARRAY                        (
    new Response.Listener<ArrayList<DummyObject>>() {
        @Override
        public void onResponse(ArrayList<DummyObject> dummyObjectArrayList) {

            if (dummyObjectArrayList.get(0).getImage().equals("sim")) {
                if (Build.VERSION.SDK_INT >= 23) {
                    if (permission != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                    } if (permission == PackageManager.PERMISSION_GRANTED) {
                        for (int i = 0; i < dummyObjectArrayList.size(); i++) {
                            if (dummyObjectArrayList.get(i).getImage().equals("sim")) {
                                progressBar4.setVisibility(View.VISIBLE);

                                for (int j = 1; j < dummyObjectArrayList.size(); j++) {
                                    imageURLArray = new String[]{dummyObjectArrayList.get(j).getImage()};
                                    DownloadFile dloadFAsync = new DownloadFile(imageURLArray);
                                    dloadFAsync.execute(imageURLArray);
                                }
                            }
                        }
                    }
                }else{
                    for (int i = 0; i < dummyObjectArrayList.size(); i++) {
                        if (dummyObjectArrayList.get(i).getImage().equals("sim")) {
                            progressBar4.setVisibility(View.VISIBLE);

                            for (int j = 1; j < dummyObjectArrayList.size(); j++) {
                                imageURLArray = new String[]{dummyObjectArrayList.get(j).getImage()};
                                DownloadFile dloadFAsync = new DownloadFile(imageURLArray);
                                dloadFAsync.execute(imageURLArray);
                            }
                        }
                    }
                }
            }
        }
    }
                                ,
                                new Response.ErrorListener() {
                                    @Override
                                            public void onErrorResponse(VolleyError error) {
                                        Toast.makeText(MainActivity.this, ""+error, Toast.LENGTH_SHORT).show();
                                    }
                                }
                        );
        App.addRequest(gsonGetRequest, "JSON");
    }
    @Override
    protected void onStop() {
        App.cancelAllRequests("JSON");

        super.onStop();
    }

    @SupspanssLint("StaticFieldLeak")
    public class DownloadFile extends AsyncTask<String, String, String> {
        int current=0;
        String[] paths;
        String fpath;

        DownloadFile(String[] paths) {
            super();
            this.paths = paths;
            for(int i=0; i<paths.length; i++)
                System.out.println((i+1)+":  "+paths[i]);
        }

        @Override
        protected String doInBackground(String... f_url) {
            folder = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "/MyAppName");
            if (!folder.exists()) {
                //noinspection ResultOfMethodCallIgnored                folder.mkdirs();
            }

            int rows = f_url.length;
            while(current < rows)
            {
                int count;
                try {
                    fpath = getFileName(this.paths[current]);
                    URL url = new URL(this.paths[current]);
                    URLConnection conexion = url.openConnection();
                    conexion.connect();
                    int lenghtOfFile = conexion.getContentLength();
                    InputStream input = new BufferedInputStream(url.openStream(), 512);
                    output = new FileOutputStream(folder+"/"+fpath);

                    byte data[] = new byte[512];
                    long total = 0;
                    while ((count = input.read(data)) != -1) {
                        total += count;
                        output.write(data, 0, count);
                        progressBar4.setProgress((int)((total*100)/lenghtOfFile));
                    }
                    output.flush();
                    output.close();
                    input.close();

                    current++;
                } catch (Exception ignored) {}
            }
            return null;
        }

        @Override
        protected void onPostExecute(String file_url) {
            progressBar4.setVisibility(View.GONE);
            Folder.setVisibility(View.VISIBLE);
            totalNumFiles = folder.listFiles().length;
            CarregarDados();
        }
    }

    String getFileName(String wholePath)
    {
        String name=null;
        int start,end;
        start=wholePath.lastIndexOf('/');
        end=wholePath.length();
        name=wholePath.substring((start+1),end);

        return name;
    }

    public void Folder()
    {
        try        {
            Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + File.separator + "/MyAppName");
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(selectedUri, "resource/folder");
            startActivity(intent);
        }
        catch (Exception e)
        {
            Toast.makeText(MainActivity.this, String.valueOf(getString(R.string.gerenciador)), Toast.LENGTH_LONG).show();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    recreate();
                    permissao.setVisibility(View.GONE);
                } else {
                    permissao.setVisibility(View.VISIBLE);
                    permissao.setText(String.valueOf(getString(R.string.Permissao23)));

                }
            }
        }
    }


    public void CarregarDados() {
        if (folder.isDirectory()) {
            File[] listFile = folder.listFiles();
            mFileStrings = new String[listFile.length];
            mFileImages = new String[listFile.length];
            for (int i = 0; i < listFile.length; i++) {
                mFileStrings[i] = listFile[i].getName();
                mFileImages[i] = listFile[i].getAbsolutePath();
            }
        }
        list= (ListView)findViewById(R.id.list);
        listAdapter = new CustomAdapter(MainActivity.this, mFileStrings,mFileImages);
        list.setAdapter(listAdapter);

    }

}




📋
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"    
android:width="108dp"    
android:height="108dp"    
android:viewportHeight="108"    
android:viewportWidth="108">
    <path android:fillColor="#26A69A" android:pathData="M0,0h108v108h-108z" />
    <path android:fillColor="#00000000" android:pathData="M9,0L9,108" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M19,0L19,108" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M29,0L29,108" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M39,0L39,108" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M49,0L49,108" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M59,0L59,108" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M69,0L69,108" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M79,0L79,108" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M89,0L89,108" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M99,0L99,108" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M0,9L108,9" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M0,19L108,19" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M0,29L108,29" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M0,39L108,39" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M0,49L108,49" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M0,59L108,59" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M0,69L108,69" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M0,79L108,79" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M0,89L108,89" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M0,99L108,99" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M19,29L89,29" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M19,39L89,39" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M19,49L89,49" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M19,59L89,59" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M19,69L89,69" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M19,79L89,79" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M29,19L29,89" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M39,19L39,89" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M49,19L49,89" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M59,19L59,89" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M69,19L69,89" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
    <path android:fillColor="#00000000" android:pathData="M79,19L79,89" android:strokeColor="#33FFFFFF" android:strokeWidth="0.8" />
</vector>





📋
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="5dip" />
            <stroke android:width="1dp" android:color="#fba317" />
            <gradient android:angle="135" android:centerColor="#404040" android:endColor="#101010" android:startColor="#101010" android:type="linear" />
        </shape>
    </item>

    <item android:id="@android:id/secondaryProgress">
        <clip> 
            <shape>
                <corners android:radius="5dip" />

                <solid android:color="@android:color/white" />
            </shape>
        </clip>
    </item>


    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <corners android:radius="5dip" />
                <stroke android:width="1dp" android:color="#fba317" />
                <gradient android:angle="135" android:centerColor="#ff0000" android:endColor="#dd0000" android:startColor="#aa0000" android:type="linear" />
            </shape>
        </clip>
    </item>
</layer-list>




📋







📋
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
tools:context="aksr.downloadfilewithasynctask.MainActivity">


    <SeekBar android:id="@+id/progressBar4" 
style="?android:attr/progressBarStyleHorizontal" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:layout_alignParentBottom="true" 
android:layout_alignParentLeft="true" 
android:layout_alignParentStart="true" 
android:indeterminate="false" 
android:progressDrawable="@drawable/progress_seekbar" 
android:thumb="@android:drawable/radiobutton_on_background" />

    <Button 
android:id="@+id/permissao" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_alignParentTop="true" 
android:layout_centerHorizontal="true" 
android:text="@string/Permissao" />

    <Button 
android:id="@+id/folder" 
android:layout_width="50dp" 
android:layout_height="50dp" 
android:layout_below="@+id/permissao" 
android:layout_centerHorizontal="true" 
android:background="@drawable/folder"
android:contentDescription="@string/folder" 
android:visibility="gone" />
    <ListView  
android:id="@+id/list" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:layout_below="@+id/folder" 
android:layout_centerHorizontal="true" />
</RelativeLayout>




📋
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="horizontal" >

    <ImageView 
android:id="@+id/icon" 
android:layout_width="50dp" 
android:layout_height="50dp" 
android:layout_marginBottom="5dp" 
android:layout_marginLeft="5dp" 
android:layout_marginRight="5dp" 
android:layout_marginTop="5dp" 
android:src="@drawable/ic_launcher_background" />

    <TextView 
android:id="@+id/Itemname" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_alignBottom="@+id/icon" 
android:layout_toEndOf="@+id/icon" 
android:layout_toRightOf="@+id/icon" 
android:paddingTop="5dp" 
android:text="Nome" 
android:textSize="20sp" />
</RelativeLayout>




📋
<?xml version="1.0" encoding="utf-8"?><resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
</resources>



📋
<resources>
    <string name="app_name">Download file with AsyncTask</string>
    <string name="Permissao">Permissao</string>
    <string name="PermissaoExplain">Para sincronizar, Precisamos baixar alguns arquivos na pasta MyAppName</string>
    <string name="Permissao23">Sem permissão para sincronizar</string>
    <string name="gerenciador">Instale um gerenciador de arquivos</string>
    <string name="folder">Pasta</string>
    <string name="pastaVazia">Pasta vazia!</string>
</resources>





📋
<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>










Nenhum comentário:

Postar um comentário

Obrigado por comentar, volte sempre!

Seguidores

Pages




Ajude continuar nossos projetos.    

Copie este código: [[address]]

Donation of [[value]] BTC Received. Thank You.
[[error]]






Copiado