fazil tm
fazil tm

Reputation: 299

How to add pause and resume for android file upload to aws s3 server

I am developing an android app to upload files to amazon s3 server. It works fine. Now, I want to add pause and resume function to the app. I am using transferutility function. Is there any solution or how it possible with shared preference? Please help me.

MainActivity.java

public class MainActivity extends AppCompatActivity {



Button button;
Button pause;
Button resume;

TextView size;
TextView completed;
TextView per;


static String filePath = "";
static String extension = "";
static String fileTempName = "";

float percentage = 0;
Uri selectedFileUri = null;

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

    button = (Button) findViewById(R.id.button);
    pause = (Button) findViewById(R.id.pause);
    resume = (Button) findViewById(R.id.resume);
    size = (TextView) findViewById(R.id.size);
    completed = (TextView) findViewById(R.id.completed);
    per = (TextView) findViewById(R.id.per);


    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent();

            intent.setType("*/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select File"), 1);


        }
    });


    pause.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this, "clicked",Toast.LENGTH_SHORT).show();
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1 && resultCode == RESULT_OK) {
        selectedFileUri = data.getData();
        filePath = new PathUtils().getPath(MainActivity.this, selectedFileUri);
        extension = filePath.substring(filePath.lastIndexOf("."));
        Log.d("LOGTAG", "extension : "+extension);
        fileUpload();
    }
}
private void fileUpload() {
    File file = new File(filePath);
    String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    Random Number = new Random();
    int Rnumber = Number.nextInt(10000000);
    fileTempName = Rnumber  +timeStamp+extension;
    Log.d("LOGTAG", "timestamp" + fileTempName);// Initialize the Amazon Cognito credentials provider
    CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
            getApplicationContext(),
            "xxxxx:xxx-xxxxxxx-xxx-xxxxxxx", // Identity Pool ID
            Regions.REGION // Region
    );
    AmazonS3 s3 = new AmazonS3Client(credentialsProvider);
    s3.setRegion(com.amazonaws.regions.Region.getRegion(Regions.AP_SOUTH_1));
    try {

        s3.putObject(new PutObjectRequest(
                BUCKET-NAME, fileTempName, file).withCannedAcl(CannedAccessControlList.PublicRead)); // this will set the permission as PublicRead
    } catch (Exception ex) {
        ex.getMessage();
    }
    TransferUtility transferUtility = new TransferUtility(s3, this);
    TransferObserver transferObserver = transferUtility.upload("BUCKET-NAME",fileTempName,file);
    putObjectRequest.withCannedAcl(CannedAccessControlList.PublicRead); // public for all
    s3.putObject(putObjectRequest); // upload file*/
    transferObserver.setTransferListener(new TransferListener() {
        @Override
        public void onStateChanged(int id, TransferState state) {
            if(state == TransferState.COMPLETED) {
                Toast.makeText(MainActivity.this,"Error",Toast.LENGTH_SHORT).show();
            }
        }
        @Override
        public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
            /*int percentage = (int) (bytesCurrent / bytesTotal * 100);
            Log.d("LOGTAG", "Percentage : " + percentage);*/
            long _bytesCurrent = bytesCurrent;
            long _bytesTotal = bytesTotal;
            percentage =  ((float)_bytesCurrent /(float)_bytesTotal * 100);
            String pr = String.format("%.2f", percentage);
            per.setText(pr + "%");
            completed.setText(Long.toString(bytesCurrent));
            size.setText(Long.toString(bytesTotal));
            Log.d("percentage","Per1 : " +percentage);
            Log.d("LOGTAG", String.format("onProgressChanged: %d, total: %d, current: %d ",
                    id, bytesTotal, bytesCurrent));
        }

        @Override
        public void onError(int id, Exception ex) {
            Log.e("LOGTAG", "Error : " + ex.getMessage());

        }
    });
}
}

Upvotes: 0

Views: 1390

Answers (2)

Piyush Kumar
Piyush Kumar

Reputation: 113

If someone is still looking for the solution, you can pause and resume the transfer by using TransferUtility's pause and resume methods. These methods take input as transferId which you get in onStateChanged method of TransferListener class.

TransferUtility class - https://github.com/aws-amplify/aws-sdk-android/blob/main/aws-android-sdk-s3/src/main/java/com/amazonaws/mobileconnectors/s3/transferutility/TransferUtility.java

Upvotes: 0

fazil tm
fazil tm

Reputation: 299

I got the answer from https://github.com/awslabs/aws-sdk-android-samples/tree/master/S3TransferUtilitySample

In this link containing the codes of pause and resume function of file upload. I get the result as correctly.

Upvotes: 0

Related Questions