Android OS - How to track Azure upload progress - android

I've been working with Azure on the Android OS and I managed to upload my video file (.mp4) to a Container I had already prepared for it.
I did this by getting a Shared Access Signature (SAS) first, which provided me with:
a temporary key
the name of the container to where I want to send the files
the server URI
Then, I started an AsyncTask to send the file to the container using the "upload".
I checked the container, and the file gets uploaded perfectly, no problems on that end.
My question is regarding the progress of the upload. Is it possible to track it? I would like to have an upload bar to give a better UX.
P.S - I'm using the Azure Mobile SDK
Here's my code:
private void uploadFile(String filename){
mFileTransferInProgress = true;
try {
Log.d("Funky Stuff", "Blob Azure Config");
final String gFilename = filename;
File file = new File(filename); // File path
String blobUri = blobServerURL + sharedAccessSignature.replaceAll("\"", "");
StorageUri storage = new StorageUri(URI.create(blobUri));
CloudBlobClient blobCLient = new CloudBlobClient(storage);
//Container name here
CloudBlobContainer container = blobCLient.getContainerReference(blobContainer);
blob = container.getBlockBlobReference(file.getName());
//fileToByteConverter is a method to convert files to a byte[]
byte[] buffer = fileToByteConverter(file);
ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer);
if (blob != null) {
new UploadFileToAzure().execute(inputStream);
}
} catch (StorageException e) {
Log.d("Funky Stuff", "StorageException: " + e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.d("Funky Stuff", "IOException: " + e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.d("Funky Stuff", "Exception: " + e.toString());
e.printStackTrace();
}
mFileTransferInProgress = false;
//TODO: Missing ProgressChanged method from AWS
}
private class UploadFileToAzure extends
AsyncTask <ByteArrayInputStream, Void, Void>
{
#Override
protected Void doInBackground(ByteArrayInputStream... params) {
try {
Log.d("Funky Stuff", "Entered UploadFileToAzure Async" + uploadEvent.mFilename);
//Method to upload, takes an InputStream and a size
blob.upload(params[0], params[0].available());
params[0].close();
} catch (StorageException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Thanks!

You can split your file and send its part using Block, there is a good example of your case in this link but it used C# so you should find the corresponding function in the android library reference.
Basically instead of sending you file as one big file, you split it to multiple files (bytes) and send it to azure so you can track the progress on how many bytes that already sent to azure

Related

new BlobStoreManager read write on Android 11

I previously used external storage to store specific data that I would like to share between my applications (without having any contentprovider "host")
File folder = new File(Environment.getExternalStorageDirectory(), "FOLDER_NAME");
File file = new File(folder, "FILE_NAME.dat");
FileOutputStream outputStream = new FileOutputStream(file);
That is why I am trying to use BlobStoreManager, as suggested in google's recommendation for targeting 30 (https://developer.android.com/training/data-storage/shared/datasets)
The read & write are based on a BlobHandle with 4 parameters, one being MessageDigest based on a "content". BlobHandle must use the same 4 parameters, or read will fail (SecurityException).
I managed to write data, and to read it, but it makes no sense:
It seems that in order to write, I need to use the data I want to write to generate the BlobHandle.
Then, to read, as BlobHandle must use the same 4 parameters, I also need the data I wrote to be able to read.
Totally illogic, as I wanted to read this data, I don't have it!
I must miss something or just do not understand how it work. If someone can help :)
Here are my sample:
If I set the following:
createBlobHandle: content = "mydata"
write: data = "mydata"
Then write will success, and read will success too. But it I can not know the value before reading it in a normal usecase :(
If I set the following (which would be logic, at least to me):
createBlobHandle: content = "somekey"
write: data = "mydata"
Then write will fail :(
#RequiresApi(api = Build.VERSION_CODES.R)
private BlobHandle createBlobHandle() {
//Transfer object
String content = "SomeContentToWrite";
String label = "label123";
String tag = "test";
//Sha256 summary of the transmission object
try {
byte[] contentByte = content.getBytes("utf-8");
MessageDigest md = MessageDigest.getInstance("sha256");
byte[] contentHash = md.digest(contentByte);
return BlobHandle.createWithSha256(contentHash, label,0, tag);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
private void write() {
String data = "SomeContentToWrite";
#SuppressLint("WrongConstant") final BlobStoreManager blobStoreManager = ((BlobStoreManager) applicationContext.getSystemService(Context.BLOB_STORE_SERVICE));
//Generate the session of this operation
try {
BlobHandle blobHandle = createBlobHandle();
if (blobHandle == null)
return;
long sessionId = blobStoreManager.createSession(blobHandle);
try (BlobStoreManager.Session session = blobStoreManager.openSession(sessionId)) {
try (OutputStream pfd = new ParcelFileDescriptor.AutoCloseOutputStream(session.openWrite(0, data.getBytes().length))) {
//The abstract of the written object must be consistent with the above, otherwise it will report SecurityException
Log.d(TAG, "writeFile: >>>>>>>>>>text = " + data);
pfd.write(data.getBytes());
pfd.flush();
//Allow public access
session.allowPublicAccess();
session.commit(applicationContext.getMainExecutor(), new Consumer<Integer>() {
#Override
public void accept(Integer integer) {
//0 success 1 failure
Log.d(TAG, "accept: >>>>>>>>" + integer);
}
});
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private String read() {
String data = "";
#SuppressLint("WrongConstant") final BlobStoreManager blobStoreManager = ((BlobStoreManager) applicationContext.getSystemService(Context.BLOB_STORE_SERVICE));
BlobHandle blobHandle = createBlobHandle();
if (blobHandle != null) {
try (InputStream pfd = new ParcelFileDescriptor.AutoCloseInputStream(blobStoreManager.openBlob(createBlobHandle()))) {
//Read data
byte[] buffer = new byte[pfd.available()];
pfd.read(buffer);
String text = new String(buffer, Charset.forName("UTF-8"));
Log.d(TAG, "readFile: >>>>>>>>>>>>>>>>>>>>" + text);
} catch (IOException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
}
return data;
}
According to the official training documentation linked in the question, the missing piece of information, at the time of the question having been asked, is that the four pieces of data contained in the BlobHandler need to be uploaded to a server owned by the client application then subsequently downloaded by which ever other application wants to access the blob via the BlobStorageManager.
So it would seem that on-device blob discovery is not supported. There could also be a solution possible using a Content Provider which could offer up the four required pieces of data, thus circumventing the need for the server infrastructure.

Android - ffmpeg best approach

I am trying to build ffmpeg for android. I want to achieve two things with it.
1. Rotate video
2. Join two or more videos.
There are two approaches for having ffmpeg in my application.
1. Having ffmpeg executable, copying it to /data/package/ and executing ffmpeg commands.
2. Build ffmpeg library .so file with ndk and write jni code etc.
Which approach is best according to my needs? And can I have some code snippets that follows those approaches?
You can achieve it by two ways, I would do it with the first one:
Place your ffmpeg file into you raw folder.
You need to use the ffmpeg executable file using commands, but you'll need to place the file into a file-system folder and change the permissions of the file, so use this code:
public static void installBinaryFromRaw(Context context, int resId, File file) {
final InputStream rawStream = context.getResources().openRawResource(resId);
final OutputStream binStream = getFileOutputStream(file);
if (rawStream != null && binStream != null) {
pipeStreams(rawStream, binStream);
try {
rawStream.close();
binStream.close();
} catch (IOException e) {
Log.e(TAG, "Failed to close streams!", e);
}
doChmod(file, 777);
}
}
public static OutputStream getFileOutputStream(File file) {
try {
return new FileOutputStream(file);
} catch (FileNotFoundException e) {
Log.e(TAG, "File not found attempting to stream file.", e);
}
return null;
}
public static void pipeStreams(InputStream is, OutputStream os) {
byte[] buffer = new byte[IO_BUFFER_SIZE];
int count;
try {
while ((count = is.read(buffer)) > 0) {
os.write(buffer, 0, count);
}
} catch (IOException e) {
Log.e(TAG, "Error writing stream.", e);
}
}
public static void doChmod(File file, int chmodValue) {
final StringBuilder sb = new StringBuilder();
sb.append("chmod");
sb.append(' ');
sb.append(chmodValue);
sb.append(' ');
sb.append(file.getAbsolutePath());
try {
Runtime.getRuntime().exec(sb.toString());
} catch (IOException e) {
Log.e(TAG, "Error performing chmod", e);
}
}
Call this method:
private void installFfmpeg() {
File ffmpegFile = new File(getCacheDir(), "ffmpeg");
String mFfmpegInstallPath = ffmpegFile.toString();
Log.d(TAG, "ffmpeg install path: " + mFfmpegInstallPath);
if (!ffmpegFile.exists()) {
try {
ffmpegFile.createNewFile();
} catch (IOException e) {
Log.e(TAG, "Failed to create new file!", e);
}
Utils.installBinaryFromRaw(this, R.raw.ffmpeg, ffmpegFile);
}else{
Log.d(TAG, "It was installed");
}
ffmpegFile.setExecutable(true);
}
Then, you will have your ffmpeg file ready to use by commands. (This way works for me but there are some people that says that it doesn't work, I don't know why, hope it isn't your case). Then, we use the ffmpeg with this code:
String command = "data/data/YOUR_PACKAGE/cache/ffmpeg" + THE_REST_OF_YOUR_COMMAND;
try {
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
Log.d(TAG, "Process finished");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
As I said, you have to use the ffmpeg file by commands, so you should search on Internet and choose the command you want to use, then, add it into the command string. If the command fails, you won't be alerted by any log, so you should try your command with a terminal emulator and be sure that it works. If it doesn´t work, you won't see any result.
Hope it's useful!!
The advantage of library approach is that you have better control over the progress of your conversion, and can tune it in the middle. One the other hand, operating the executable is a bit easier. Finally, you can simply install the ffmpeg4android app and work with their API.

Write File in Java Android, Read the File with Phonegap

I'm trying to write a json file using android like this:
String jsonString = broadcastDataArray.toString();
Writer output = null;
File fileAnnouncement = new File("announcement.json");
try {
output = new BufferedWriter(new FileWriter(fileAnnouncement));
output.write(jsonString);
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and now i'm trying to load/read the file using phonegap. Using this method shown here, i am able to read a file that was included in my application source. But i want to read some file that was generated by the android code.
Is there anyway to do this? Is there any specific directory where the file could be accessed from Java android and Phonegap/Sencha ?
Any kind of help or pointer is appreciated. Thanks.
You can do this in following way.
Write this function in your Android activity to write data in text file.
public void WriteDataToFile(String sFileName, String sBody){
try
{
FileWriter f = new FileWriter("/sdcard/data.txt");
f.append(sBody);
f.flush();
f.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
And, now you can read that file from your Sencha/Phonegap app by calling this function.
var user_data = function(){
var request = new XMLHttpRequest();
request.open("GET", "/sdcard/data.txt");
request.onreadystatechange = function() {
if (request.readyState == 4) {
// alert("*" + request.responseText + "*");
data = request.responseText;
}
}
request.send();
}

android not running on my phone, but on my emulator does

i wrote this ftp upload method...it works great on the emulator but doesnt on my phone...
can someone tell me why not?
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("ftp.atw.hu");
client.login("festivale", "festivale12");
Log.d("TravellerLog :: ", "Csatlakozva: ftp.atw.hu");
//
// Create an InputStream of the file to be uploaded
//
client.setFileType(FTP.BINARY_FILE_TYPE);
client.enterLocalPassiveMode();
String substr = globalconstant.path.substring(4, globalconstant.path.length());
String filename = substr + "/Festivale.db";
Log.e("TravellerLog :: ", substr + "/Festivale.db");
fis = new FileInputStream(filename);
//
// Store file to server
//
client.storeFile("Festivale.db", fis);
Log.d("TravellerLog :: ", "Feltöltve");
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
pls help i'm trying to do this ftp almost 3hours ago :S
On devices, you need to use a separate thread to handle the ftp connection.
"By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities."[android.developer.com/guide/components/services.html]

Android Uploading a file on ftp

Android file uploading issue
I am trying to upload image on my ftp server ,its not giving me any exception or error but image in nt deployed.Can anyone working on uploading image can identify problem.
FTPClient con = new FTPClient();
try{
con.connect("host",21);
con.login(username, pswd);
con.setFileType(FTP.BINARY_FILE_TYPE);
con.setFileTransferMode(FTP.ASCII_FILE_TYPE);
con.setSoTimeout(10000);
con.enterLocalPassiveMode();
if (con.login(username, pswd)) {
try {
File sFile = new File("mnt/sdcard/DCIM/download.jpg");
// connect.setText(sFile.toString());
BufferedInputStream buffIn = null;
buffIn = new BufferedInputStream(
new FileInputStream(sFile));
try {
String fileName = sFile.getName();
while (!dataUpResp) {
dataUpResp = con.storeFile(fileName,
buffIn);
// publishProgress("" + 10);
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.getMessage();
}
}
} catch (IOException e) {
}
Isn't it an issue that there are 2 times logging in in your code?
con.login(username, pswd); // 1st time
con.setFileType(FTP.BINARY_FILE_TYPE);
con.setFileTransferMode(FTP.ASCII_FILE_TYPE);
con.setSoTimeout(10000);
con.enterLocalPassiveMode();
if (con.login(username, pswd)) // 2nd time
Also you didn't use logout/disconnect for FTPClient and there are no flush and close for streams.
Tried your code with commons-net-3.2.jar with conjunctions of FileZilla FTP Server and it works fine.

Categories

Resources