#Override
protected Boolean doInBackground(String... strings) {
try {
File path = context.getFilesDir();
File outputFile = new File(path, fileName + ".apk");
int repetition = 1;
while (outputFile.exists()) {
outputFile = new File(path, fileName + " (+" + repetition + ").apk");
repetition++;
}
if (!path.exists()) {
path.mkdirs();
}
URL url = new URL(downloadUrl);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream inputStream = c.getInputStream();
float totalSize = (float) c.getContentLength();
Pair<Integer, InputStream> bitmapToStream = Pair.create((int) totalSize, inputStream);
InputStream in = bitmapToStream.second;
OutputStream out = new FileOutputStream(outputFile);
long fileSize = bitmapToStream.first;
byte[] buf = new byte[(int) fileSize];
int len;
float per;
float downloaded = 0f;
while ((len = in.read(buf)) > 0){
out.write(buf,0,len);
downloaded += len;
per = (downloaded * 100 / totalSize);
publishProgress((int) per);
}
out.close();
in.close();
installAPK(path, outputFile.getName());
updatePatchListener.onDone();
// openNewVersion(outputFile.getPath());
return true;
} catch (Exception exception) {
this.exception = exception;
}
return false;
}
private void installAPK(File path, String apkName) {
try {
Process p = new ProcessBuilder("pm install -r " + apkName).directory(path).start();
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
}
I want to install the apk that I have downloaded silently, but always get the error permission denied..
I already use command pm install or adb install or adb shell or run-as, but all not working for me. Always permission denied
is there any solution for me..?
2023-01-15 14:14:21.787 12507-12558/com.c.aka W/System.err: java.io.IOException: Cannot run program "pm install -r Update (+3).apk" (in directory "/data/user/0/com.c.aka/files"): error=13, Permission denied
2023-01-15 14:14:21.787 12507-12558/com.c.aka W/System.err: at java.lang.ProcessBuilder.start(ProcessBuilder.java:1050)
2023-01-15 14:14:21.787 12507-12558/com.c.aka W/System.err: at com.c.cpayid.UpdatePatch$DownloadNewVersion.installAPK(UpdatePatch.java:129)
2023-01-15 14:14:21.787 12507-12558/com.c.aka W/System.err: at com.c.cpayid.UpdatePatch$DownloadNewVersion.doInBackground(UpdatePatch.java:115)
2023-01-15 14:14:21.787 12507-12558/com.c.aka W/System.err: at com.c.cpayid.UpdatePatch$DownloadNewVersion.doInBackground(UpdatePatch.java:54)
2023-01-15 14:14:21.787 12507-12558/com.c.aka W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:333)
2023-01-15 14:14:21.787 12507-12558/com.c.aka W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
2023-01-15 14:14:21.787 12507-12558/com.c.aka W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
2023-01-15 14:14:21.787 12507-12558/com.c.aka W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
2023-01-15 14:14:21.787 12507-12558/com.c.aka W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
2023-01-15 14:14:21.787 12507-12558/com.c.aka W/System.err: at java.lang.Thread.run(Thread.java:764)
2023-01-15 14:14:21.787 12507-12558/com.c.aka W/System.err: Caused by: java.io.IOException: error=13, Permission denied
2023-01-15 14:14:21.787 12507-12558/com.c.aka W/System.err: at java.lang.UNIXProcess.forkAndExec(Native Method)
2023-01-15 14:14:21.787 12507-12558/com.c.aka W/System.err: at java.lang.UNIXProcess.(UNIXProcess.java:133)
2023-01-15 14:14:21.787 12507-12558/com.c.aka W/System.err: at java.lang.ProcessImpl.start(ProcessImpl.java:132)
2023-01-15 14:14:21.787 12507-12558/com.c.aka W/System.err: at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
this error show
You cannot install an APK silently. Imagine if any piece of malware could download an APK and install it to hide itself and include additional pieces of malware on a device. That would be bad. That's why no app can install others without the user intervening.
If you're the device owner and trying to install apps across your fleet, look at Android Enterprise. That can install apps. But there's no way to do it programatically.
Related
I want to record screen and record video from front camera simultaneously . Is it possible. I tried It gives exception of Media release . only one works either of two
public void setupRecorder(int resultCode, Intent data) {
NativeAppRecordingService.dataIntentScreenCapture = data;
NativeAppRecordingService.resultCodeDataScreenCapture = resultCode;
NativeAppRecordingService.recorder.reset();
recordingInfo = getRecordingInfo();
NativeAppRecordingService.recorder.setVideoSource(SURFACE);
// Enable Audio recording.......
NativeAppRecordingService.recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
NativeAppRecordingService.recorder.setOutputFormat(MPEG_4);
NativeAppRecordingService.recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
NativeAppRecordingService.recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
NativeAppRecordingService.recorder.setVideoSize(recordingInfo.width, recordingInfo.height);
NativeAppRecordingService.recorder.setVideoEncodingBitRate(15 * 1000 * 100);/**change this for video quality */
NativeAppRecordingService.recorder.setVideoFrameRate(recordingInfo.frameRate);
//String outputVideoFileName = fileFormat.format(new Date());
NativeAppRecordingService.recorder.setOutputFile(Utils.getOutputVideoFileNameForAmazonS3Bucket(""));
// NativeAppRecordingService.recorder.setOutputFile(NativeAppRecordingService.video_file.getAbsolutePath());
try {
NativeAppRecordingService.recorder.prepare();
NativeAppRecordingService.projection = NativeAppRecordingService.manager.getMediaProjection(resultCode, data);
Surface surface = NativeAppRecordingService.recorder.getSurface();
if (surface == null) {
Toast.makeText(StartRecorderActivity.this, "Your device is not able to capture screen!", Toast.LENGTH_SHORT).show();
File f = new File(Utils.getOutputVideoFileNameForAmazonS3Bucket(""));
if (f.exists()) {
f.delete();
}
// TODO if decive is not able to capture audio and video
// todo cancel the test
TerminatingTest();
} else {
NativeAppRecordingService.display = NativeAppRecordingService.projection.createVirtualDisplay(NativeAppRecordingService.DISPLAY_NAME,
recordingInfo.width, recordingInfo.height,
recordingInfo.density, VIRTUAL_DISPLAY_FLAG_PRESENTATION,
surface, null, null);
NativeAppRecordingService.recorder.start();
// todo PauseRecording
NativeAppRecordingService.isRecording = true;
finish();
}
} catch (IllegalStateException e) {
e.printStackTrace();
Toast.makeText(StartRecorderActivity.this, "Your device is not able to capture screen!", Toast.LENGTH_SHORT).show();
File f = new File(Utils.getOutputVideoFileNameForAmazonS3Bucket(""));
if (f.exists()) {
f.delete();
}
// TODO if decive is not able to capture audio and video
// todo cancel the test
TerminatingTest();
} catch (IOException e) {
Toast.makeText(StartRecorderActivity.this, "Your device is not able to capture screen!", Toast.LENGTH_SHORT).show();
File f = new File(Utils.getOutputVideoFileNameForAmazonS3Bucket(""));
if (f.exists()) {
f.delete();
}
// TODO if decive is not able to capture audio and video
// todo cancel the test
TerminatingTest();
}
}
the above is for screen recording and the below one is for video recording
public static void setUpVideoRecorder() {
try {
mMediaRecorder = new MediaRecorder();
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
/**
* create video output file
*/
video_file = getOutputMediaFile();
/**
* set output file in media recorder
*/
mMediaRecorder.setOutputFile(video_file.getAbsolutePath());
mMediaRecorder.setMaxDuration(300000);
CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_480P);
mMediaRecorder.setVideoFrameRate(profile.videoFrameRate);
mMediaRecorder.setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight);
mMediaRecorder.setVideoEncodingBitRate(profile.videoBitRate);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263);
mMediaRecorder.setAudioEncodingBitRate(profile.audioBitRate);
mMediaRecorder.setAudioSamplingRate(profile.audioSampleRate);
/* int rotation = windowManager.getDefaultDisplay().getRotation();
switch (mSensorOrientation) {
case SENSOR_ORIENTATION_DEFAULT_DEGREES:
mMediaRecorder.setOrientationHint(DEFAULT_ORIENTATIONS.get(rotation));
break;
case SENSOR_ORIENTATION_INVERSE_DEGREES:
mMediaRecorder.setOrientationHint(INVERSE_ORIENTATIONS.get(rotation));
break;
}*/
mMediaRecorder.prepare();
}
catch (IOException ioe)
{
Log.e(TAG,"setUpVideoRecorder ioe "+ioe);
}
}
Here is the LogCat
2019-11-05 14:46:52.581 11771-11771/com.seattleapplab.trymyui.beta E/MediaRecorder: start failed: -38
2019-11-05 14:46:52.581 11771-11771/com.seattleapplab.trymyui.beta W/System.err: java.lang.IllegalStateException
2019-11-05 14:46:52.581 11771-11771/com.seattleapplab.trymyui.beta W/System.err: at android.media.MediaRecorder.start(Native Method)
2019-11-05 14:46:52.581 11771-11771/com.seattleapplab.trymyui.beta W/System.err: at com.seattleapplab.trymyui.Activity.StartRecorderActivity.setupRecorder(StartRecorderActivity.java:229)
2019-11-05 14:46:52.582 11771-11771/com.seattleapplab.trymyui.beta W/System.err: at com.seattleapplab.trymyui.Activity.StartRecorderActivity.onActivityResult(StartRecorderActivity.java:757)
2019-11-05 14:46:52.582 11771-11771/com.seattleapplab.trymyui.beta W/System.err: at android.app.Activity.dispatchActivityResult(Activity.java:7454)
2019-11-05 14:46:52.582 11771-11771/com.seattleapplab.trymyui.beta W/System.err: at android.app.ActivityThread.deliverResults(ActivityThread.java:4354)
2019-11-05 14:46:52.582 11771-11771/com.seattleapplab.trymyui.beta W/System.err: at android.app.ActivityThread.handleSendResult(ActivityThread.java:4403)
2019-11-05 14:46:52.582 11771-11771/com.seattleapplab.trymyui.beta W/System.err: at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:49)
2019-11-05 14:46:52.582 11771-11771/com.seattleapplab.trymyui.beta W/System.err: at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
2019-11-05 14:46:52.582 11771-11771/com.seattleapplab.trymyui.beta W/System.err: at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
2019-11-05 14:46:52.582 11771-11771/com.seattleapplab.trymyui.beta W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1809)
2019-11-05 14:46:52.582 11771-11771/com.seattleapplab.trymyui.beta W/System.err: at android.os.Handler.dispatchMessage(Handler.java:106)
2019-11-05 14:46:52.582 11771-11771/com.seattleapplab.trymyui.beta W/System.err: at android.os.Looper.loop(Looper.java:193)
2019-11-05 14:46:52.582 11771-11771/com.seattleapplab.trymyui.beta W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6692)
2019-11-05 14:46:52.582 11771-11771/com.seattleapplab.trymyui.beta W/System.err: at java.lang.reflect.Method.invoke(Native Method)
2019-11-05 14:46:52.582 11771-11771/com.seattleapplab.trymyui.beta W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
2019-11-05 14:46:52.582 11771-11771/com.seattleapplab.trymyui.beta W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
I have added self-signed certificate for client-server communication
using "TLSv1" protocol working perfectly in all device, but in Android Q preview during the handshake process getting the following exception
The error can be generated from procedtoUnsafe or adding exception from browser
D/FA: Logging event (FE): user_engagement(_e), Bundle[{firebase_event_origin(_o)=auto, engagement_time_msec(_et)=9551, firebase_screen_class(_sc)=HomeActivity, firebase_screen_id(_si)=-2452361814686810599}]
D/FA: Connected to remote service
W/antra.rdservic: Accessing hidden method Ljava/net/InetAddress;->holder()Ljava/net/InetAddress$InetAddressHolder; (greylist, reflection, allowed)
W/antra.rdservic: Accessing hidden method Ljava/net/InetAddress$InetAddressHolder;->getOriginalHostName()Ljava/lang/String; (greylist-max-o, reflection, denied)
W/antra.rdservic: Accessing hidden method Ldalvik/system/CloseGuard;->close()V (greylist,core-platform-api, linking, allowed)
W/System.err: javax.net.ssl.SSLHandshakeException: Handshake failed
W/System.err: at com.google.android.gms.org.conscrypt.ConscryptFileDescriptorSocket.startHandshake(:com.google.android.gms#17122037#17.1.22 (100400-245988633):35)
W/System.err: at com.google.android.gms.org.conscrypt.ConscryptFileDescriptorSocket.waitForHandshake(:com.google.android.gms#17122037#17.1.22 (100400-245988633):1)
W/System.err: at com.google.android.gms.org.conscrypt.ConscryptFileDescriptorSocket.getOutputStream(:com.google.android.gms#17122037#17.1.22 (100400-245988633):5)
W/System.err: at com.mantra.rdservice.sslservice.SslServer.runSecureServer(SslServer.java:121)
W/System.err: at com.mantra.rdservice.sslservice.SslServer.runServer(SslServer.java:157)
W/System.err: at com.mantra.rdservice.sslservice.SslServer.findPort(SslServer.java:106)
W/System.err: at com.mantra.rdservice.sslservice.SecureService$1.run(SecureService.java:74)
W/System.err: at java.lang.Thread.run(Thread.java:919)
W/System.err: Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xc386a398: Failure in SSL library, usually a protocol error
W/System.err: error:10000416:SSL routines:OPENSSL_internal:SSLV3_ALERT_CERTIFICATE_UNKNOWN (third_party/openssl/boringssl/src/ssl/tls_record.cc:587 0xc5e7a888:0x00000001)
W/System.err: at com.google.android.gms.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
W/System.err: at com.google.android.gms.org.conscrypt.NativeSsl.doHandshake(:com.google.android.gms#17122037#17.1.22 (100400-245988633):7)
W/System.err: at com.google.android.gms.org.conscrypt.ConscryptFileDescriptorSocket.startHandshake(:com.google.android.gms#17122037#17.1.22 (100400-245988633):14)
W/System.err: ... 7 more
W/antra.rdservic: Accessing hidden method Ljava/net/InetAddress$InetAddressHolder;->getOriginalHostName()Ljava/lang/String; (greylist-max-o, reflection, denied)
W/antra.rdservic: Accessing hidden method Ljava/net/InetAddress$InetAddressHolder;->getOriginalHostName()Ljava/lang/String; (greylist-max-o, reflection, denied)
i have added function that created connection
Loopback ="127.0.0.1";
private void runSecureServer(final int port) throws Exception {
final ServerSocket socket = createSSLSocket();
socket.bind(new InetSocketAddress(Loopback, port));
socket.setReuseAddress(true);
this._url = "https://" + Loopback + ":" + String.valueOf(port) + "/";
while (true) {
try {
Socket client = socket.accept();
PrintWriter outputStream = new PrintWriter(client.getOutputStream(), true);
BufferedReader inputStream = new BufferedReader(new InputStreamReader(client.getInputStream()));
StringBuilder finalData = new StringBuilder();
String inputLine;
while ((inputLine = inputStream.readLine()) != null && !inputLine.equals("")) {
finalData.append(inputLine).append("\r\n");
}
executorService.execute(new HttpProcessor(ctx, _url, client, outputStream, inputStream, finalData.toString()));
} catch (Exception ex) {
ex.printStackTrace();
socket.close();
runServer(port);
break;
}
}
}
I have referred StackOverflow question but no solution found
I am using the following method to read the stream.
public static String readStream(InputStream inputStream) {
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = inputStream.read();
while (i != -1) {
bo.write(i);
i = inputStream.read();
}
return bo.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
I am getting the following Exception at this line
int i = inputStream.read();
Exception:
javax.net.ssl.SSLProtocolException: Read error: ssl=0x9af236c0: Failure in SSL library, usually a protocol error
2019-03-15 16:25:25.978 5367-5389/com.healics.myhealics W/System.err: error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT (external/boringssl/src/crypto/cipher/e_aes.c:1143 0x989b8e9f:0x00000000)
2019-03-15 16:25:25.978 5367-5389/com.healics.myhealics W/System.err: error:1000008b:SSL routines:OPENSSL_internal:DECRYPTION_FAILED_OR_BAD_RECORD_MAC (external/boringssl/src/ssl/tls_record.c:277 0x989b8e9f:0x00000000)
2019-03-15 16:25:25.979 5367-5389/com.healics.myhealics W/System.err: at com.android.org.conscrypt.NativeCrypto.SSL_read(Native Method)
2019-03-15 16:25:25.980 5367-5389/com.healics.myhealics W/System.err: at com.android.org.conscrypt.OpenSSLSocketImpl$SSLInputStream.read(OpenSSLSocketImpl.java:741)
2019-03-15 16:25:25.980 5367-5389/com.healics.myhealics W/System.err: at com.android.okhttp.okio.Okio$2.read(Okio.java:136)
2019-03-15 16:25:25.980 5367-5389/com.healics.myhealics W/System.err: at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:211)
2019-03-15 16:25:25.980 5367-5389/com.healics.myhealics W/System.err: at com.android.okhttp.okio.RealBufferedSource.read(RealBufferedSource.java:50)
2019-03-15 16:25:25.980 5367-5389/com.healics.myhealics W/System.err: at com.android.okhttp.internal.http.Http1xStream$FixedLengthSource.read(Http1xStream.java:393)
2019-03-15 16:25:25.980 5367-5389/com.healics.myhealics W/System.err: at com.android.okhttp.okio.RealBufferedSource$1.read(RealBufferedSource.java:371)
2019-03-15 16:25:25.981 5367-5389/com.healics.myhealics W/System.err: at java.io.BufferedInputStream.fill(BufferedInputStream.java:248)
2019-03-15 16:25:25.982 5367-5389/com.healics.myhealics W/System.err: at java.io.BufferedInputStream.read(BufferedInputStream.java:267)
2019-03-15 16:25:25.983 5367-5389/com.healics.myhealics W/System.err: at com.interrahealth.i3user.util.StreamReader.readStream(StreamReader.java:18)
Now, this is happening only on the emulator when I run the code in the real android device it does not happen. This is an intermittent issue sometimes coming not every time.
Adding the code
I have not added any code which sets up the SSL/TLS settings below is my code
private static String mGetResponseFromNetworkRequest(String userPass, String apiEndpoint, String
outputStreamBytes, String requestMethod, String contentType) {
long startTime = System.currentTimeMillis();
String response = "";
Logger.d("apiEndpoint: " + apiEndpoint);
try {
HttpURLConnection httpURLConnection = getHttpUrlConnectionWithDigestAuth(apiEndpoint, requestMethod);
httpURLConnection.setRequestMethod(requestMethod);
httpURLConnection.setRequestProperty("Content-Type", contentType);
httpURLConnection.setRequestProperty("Content-Language", "en-US");
httpURLConnection.setRequestProperty("charset", "utf-8");
httpURLConnection.addRequestProperty("User-Agent", "XYZ");
httpURLConnection.addRequestProperty("Full-App-Version", BuildConfig.VERSION_NAME);
httpURLConnection.addRequestProperty("Platform", "Android");
httpURLConnection.setUseCaches(false);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
dataOutputStream.writeBytes(outputStreamBytes);
dataOutputStream.flush();
dataOutputStream.close();
Logger.d("dataOutputStream: " + outputStreamBytes);
Logger.d("Response Code: " + httpURLConnection.getResponseCode());
Logger.d("httpURLConnection.getHeaderFields(): " + httpURLConnection.getHeaderFields().toString());
Logger.d("httpURLConnection: " + httpURLConnection.toString());
// WAS THROWING ERRORS
if (httpURLConnection.getResponseCode() == 500) {
return "500";
} else {
InputStream inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
response = StreamReader.readStream(inputStream);
httpURLConnection.disconnect();
}
Logger.d("Result: " + response);
} catch (MalformedInputException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.d("mGetResponseFromNetworkRequest", "Connection Time = " + (System.currentTimeMillis() - startTime));
return response;
}
You need to set the setSSLSocketFactory on your HttpsURLConnection like so:
httpURLConnection.setSSLSocketFactory(new MyFactory());
In Android API level 16+ TLS 1.1 and 1.2 are not enabled by default so it needs to be enabled. Above we are using a class called MyFactory which is where you will set the SSLContext. Here is a link to show you what you need to do https://blog.dev-area.net/2015/08/13/android-4-1-enable-tls-1-1-and-tls-1-2/
We are using Dropbox API v2 in our Android app to upload database files (.db) to a user's Dropbox App folder. Below is the code for uploading file:
InputStream inputStream = null;
FileMetadata obj = null;
try {
inputStream = new FileInputStream(dbFile);
obj = mDbxClient.files().uploadBuilder(remoteFilePath)
.withMode(WriteMode.OVERWRITE)
.uploadAndFinish(inputStream);
} catch (DbxException | IOException e) {
obj = null;
mException = e;
} finally {
if (inputStream != null)
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
The same file is uploaded in quick succession 3-4 times.
Now, everything works fine when Internet speed is fast (4G, Wifi) but when a user switches to 2G/3G network, the file isn't uploaded fully. The callback method onUploadComplete() is called but the file size here has drastically reduced. I have attached the version history of a database file.
https://www.dropbox.com/s/s7y43707ic1kqxg/dropbox.jpg?dl=0
You can see that the file size suddenly reduces to 104KB. This becomes a corrupt database file.
Is there any way to fix this?
Should I change the upload method? (maybe use UploadSession()
Or
Uploads shouldn't be called in quick succession?
Please guide
EDIT:
Below is the call to upload file:
AsyncTaskCompat.executeParallel(new DropboxUploadFileTask(DropboxClientFactory.getClient(), new DropboxUploadFileTask.Callback() {
#Override
public void onUploadComplete(FileMetadata result) {
String message = result.getName() + " size " + result.getSize() + " modified " +
java.text.DateFormat.getDateTimeInstance().format(result.getClientModified());
Log.i("BKSync upload ends: ", message);
}
#Override
public void onError(Exception e) {
Log.e("BKSync", "Failed to upload file.", e);
}
}, context), glDbName, "");
class DropboxUploadFileTask extends AsyncTask<String, Void, FileMetadata> {
private final DbxClientV2 mDbxClient;
private final Callback mCallback;
private Exception mException;
private Context mContext;
public interface Callback {
void onUploadComplete(FileMetadata result);
void onError(Exception e);
}
DropboxUploadFileTask(DbxClientV2 dbxClient, Callback callback, Context context) {
mDbxClient = dbxClient;
mCallback = callback;
mContext = context;
}
#Override
protected void onPreExecute() {
Log.e("BKSync", "upload starts");
}
#Override
protected void onPostExecute(FileMetadata result) {
Log.e("BKSync", "upload ends");
super.onPostExecute(result);
if (mException != null) {
mCallback.onError(mException);
} else if (result == null) {
mCallback.onError(null);
} else {
mCallback.onUploadComplete(result);
}
}
#Override
protected FileMetadata doInBackground(String... params) {
String dbFileName = params[0];
File dbFile = mContext.getDatabasePath(dbFileName);
String remoteFolderPath = params[1];
String remoteFileName = dbFile.getName();
InputStream inputStream = null;
FileMetadata obj = null;
try {
inputStream = new FileInputStream(dbFile);
obj = mDbxClient.files().uploadBuilder(remoteFolderPath + "/" + remoteFileName)
.withMode(WriteMode.OVERWRITE)
.uploadAndFinish(inputStream);
} catch (DbxException | IOException e) {
obj = null;
mException = e;
Log.e("BKSync", "exception1");
mException.printStackTrace();
} finally {
if (inputStream != null)
try {
inputStream.close();
} catch (IOException e) {
Log.e("BKSync", "exception2");
e.printStackTrace();
}
}
return obj;
}
}
And below is the log:
05-29 12:08:06.322 11232-11232/com.bk E/BKSync: upload starts
05-29 12:08:13.129 11232-11232/com.bk E/BKSync: upload ends
05-29 12:08:13.130 11232-11232/com.bk I/BKSync upload ends:: demo2_local.db size 692224 modified May 29, 2018 12:08:13 PM
05-29 12:08:13.471 11232-11232/com.bk E/BKSync: upload starts
05-29 12:08:22.992 11232-11232/com.bk E/BKSync: upload ends
05-29 12:08:22.993 11232-11232/com.bk I/BKSync upload ends:: demo2_local.db size 692224 modified May 29, 2018 12:08:23 PM
05-29 12:08:45.181 11232-11232/com.bk E/BKSync: upload starts
05-29 12:08:48.692 11232-11232/com.bk E/BKSync: upload starts
05-29 12:08:49.137 11232-11232/com.bk E/BKSync: upload starts
05-29 12:08:51.962 11232-11232/com.bk E/BKSync: upload starts
f05-29 12:09:24.183 11232-30020/com.bk E/BKSync: exception1
05-29 12:09:24.184 11232-30020/com.bk W/System.err: com.dropbox.core.NetworkIOException: Unable to resolve host "content.dropboxapi.com": No address associated with hostname
at com.dropbox.core.DbxUploader.finish(DbxUploader.java:235)
at com.dropbox.core.DbxUploader.uploadAndFinish(DbxUploader.java:106)
at com.dropbox.core.v2.DbxUploadStyleBuilder.uploadAndFinish(DbxUploadStyleBuilder.java:92)
05-29 12:09:24.185 11232-30020/com.bk W/System.err: at com.bk.DropboxUploadFileTask.doInBackground(DropboxUploadFileTask.java:81)
at com.bkbk.DropboxUploadFileTask.doInBackground(DropboxUploadFileTask.java:20)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:762)
05-29 12:09:24.189 11232-30020/com.bk W/System.err: Caused by: java.net.UnknownHostException: Unable to resolve host "content.dropboxapi.com": No address associated with hostname
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:125)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)
at java.net.InetAddress.getAllByName(InetAddress.java:752)
at okhttp3.Dns$1.lookup(Dns.java:39)
at okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:185)
at okhttp3.internal.connection.RouteSelector.nextProxy(RouteSelector.java:149)
at okhttp3.internal.connection.RouteSelector.next(RouteSelector.java:84)
05-29 12:09:24.190 11232-30020/com.bk W/System.err: at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:213)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:134)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:113)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
05-29 12:09:24.193 11232-30020/com.bk W/System.err: at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
05-29 12:09:24.194 11232-30020/com.bk W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
05-29 12:09:24.195 11232-30020/com.bk W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:125)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:147)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
... 3 more
05-29 12:09:24.196 11232-30020/com.bk W/System.err: Caused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
at libcore.io.Posix.android_getaddrinfo(Native Method)
at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:55)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:106)
... 26 more
05-29 12:09:24.211 11232-11232/com.bk E/BKSync: upload ends
Failed to upload file.
05-29 12:09:24.300 11232-11232/com.bk E/BKSync: upload starts
05-29 12:09:24.314 11232-30020/com.bk E/BKSync: exception1
05-29 12:09:24.315 11232-30020/com.bk W/System.err: com.dropbox.core.NetworkIOException: Pipe closed
at com.dropbox.core.DbxUploader.uploadAndFinish(DbxUploader.java:103)
at com.dropbox.core.v2.DbxUploadStyleBuilder.uploadAndFinish(DbxUploadStyleBuilder.java:92)
at com.bk.DropboxUploadFileTask.doInBackground(DropboxUploadFileTask.java:81)
at com.bk.DropboxUploadFileTask.doInBackground(DropboxUploadFileTask.java:20)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
05-29 12:09:24.316 11232-30020/com.bk W/System.err: at java.lang.Thread.run(Thread.java:762)
Caused by: com.dropbox.core.util.IOUtil$WriteException: Pipe closed
at com.dropbox.core.util.IOUtil.copyStreamToStream(IOUtil.java:61)
at com.dropbox.core.util.IOUtil.copyStreamToStream(IOUtil.java:68)
at com.dropbox.core.util.IOUtil.copyStreamToStream(IOUtil.java:43)
at com.dropbox.core.http.HttpRequestor$Uploader.upload(HttpRequestor.java:98)
at com.dropbox.core.DbxUploader.uploadAndFinish(DbxUploader.java:98)
... 8 more
05-29 12:09:24.318 11232-30020/com.bk W/System.err: Caused by: java.io.IOException: Pipe closed
at java.io.PipedInputStream.checkStateForReceive(PipedInputStream.java:267)
at java.io.PipedInputStream.receive(PipedInputStream.java:233)
at java.io.PipedOutputStream.write(PipedOutputStream.java:149)
at com.dropbox.core.util.IOUtil.copyStreamToStream(IOUtil.java:59)
... 12 more
05-29 12:09:24.441 11232-11232/com.bk E/BKSync: upload ends
05-29 12:09:24.442 11232-11232/com.bk E/BKSync: Failed to upload file.
com.dropbox.core.NetworkIOException: Pipe closed
at com.dropbox.core.DbxUploader.uploadAndFinish(DbxUploader.java:103)
at com.dropbox.core.v2.DbxUploadStyleBuilder.uploadAndFinish(DbxUploadStyleBuilder.java:92)
at com.bk.DropboxUploadFileTask.doInBackground(DropboxUploadFileTask.java:81)
at com.bk.DropboxUploadFileTask.doInBackground(DropboxUploadFileTask.java:20)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:762)
Caused by: com.dropbox.core.util.IOUtil$WriteException: Pipe closed
at com.dropbox.core.util.IOUtil.copyStreamToStream(IOUtil.java:61)
at com.dropbox.core.util.IOUtil.copyStreamToStream(IOUtil.java:68)
at com.dropbox.core.util.IOUtil.copyStreamToStream(IOUtil.java:43)
at com.dropbox.core.http.HttpRequestor$Uploader.upload(HttpRequestor.java:98)
at com.dropbox.core.DbxUploader.uploadAndFinish(DbxUploader.java:98)
at com.dropbox.core.v2.DbxUploadStyleBuilder.uploadAndFinish(DbxUploadStyleBuilder.java:92)
at com.bk.DropboxUploadFileTask.doInBackground(DropboxUploadFileTask.java:81)
at com.bk.DropboxUploadFileTask.doInBackground(DropboxUploadFileTask.java:20)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:762)
Caused by: java.io.IOException: Pipe closed
at java.io.PipedInputStream.checkStateForReceive(PipedInputStream.java:267)
at java.io.PipedInputStream.receive(PipedInputStream.java:233)
at java.io.PipedOutputStream.write(PipedOutputStream.java:149)
at com.dropbox.core.util.IOUtil.copyStreamToStream(IOUtil.java:59)
at com.dropbox.core.util.IOUtil.copyStreamToStream(IOUtil.java:68)
at com.dropbox.core.util.IOUtil.copyStreamToStream(IOUtil.java:43)
at com.dropbox.core.http.HttpRequestor$Uploader.upload(HttpRequestor.java:98)
at com.dropbox.core.DbxUploader.uploadAndFinish(DbxUploader.java:98)
at com.dropbox.core.v2.DbxUploadStyleBuilder.uploadAndFinish(DbxUploadStyleBuilder.java:92)
at com.bk.DropboxUploadFileTask.doInBackground(DropboxUploadFileTask.java:81)
at com.bk.DropboxUploadFileTask.doInBackground(DropboxUploadFileTask.java:20)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:762)
As you can see, exceptions raised by the app.
Issue occurs when user starts upload on 4G and then due to incoming call, network switches to 3G. File size on Dropbox reduces drastically then.
Please help.
I've created an issue on github: https://github.com/dropbox/dropbox-sdk-java/issues/191 for tracking. It looks like a bug in Uploader code. But we don't have plan to immediately fix it and release a new version.
So my suggestion of work around would be:
If you get an error and meanwhile the partial file was uploaded to Dropbox, please make sure you retry after error.
If you don't get error and the partial file was saved. (unlikely). You may want to compare the content hash of the file you just uploaded. The content hash is returned as the result of upload. And for the hash function you can refer https://www.dropbox.com/developers/reference/content-hash
I'm trying to modify ID3 tags of MP3 files using MyID3 for Android library:
...
int permissionCheck = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
String pathdata = "/storage/0094-1EEE/Music/example.mp3";
File src = new File(pathdata);
MusicMetadataSet src_set = null;
try {
src_set = new MyID3().read(src);
} catch (IOException e1) {
e1.printStackTrace();
} // read metadata
if (src_set == null) {
} else {
try {
IMusicMetadata metadata = src_set.getSimplified();
String artist = metadata.getArtist();
String year = metadata.getYear();
Log.i("artist", artist);
Log.i("year", year);
} catch (Exception e) {
e.printStackTrace();
}
File dst = new File(pathdata);
MusicMetadata meta = new MusicMetadata("name");
meta.setYear("1234");
try {
new MyID3().update(src, src_set, meta);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ID3WriteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} // write updated metadata
}
...
It works if the MP3 file is in internal storage, but if it's in external storage it returns:
W/System.err: java.io.IOException: Permission denied
W/System.err: at java.io.UnixFileSystem.createFileExclusively0(Native Method)
W/System.err: at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:280)
W/System.err: at java.io.File.createNewFile(File.java:948)
W/System.err: at java.io.File.createTempFile(File.java:1862)
W/System.err: at org.cmc.music.myid3.MyID3.update(MyID3.java:60)
W/System.err: at com.maxmpz.poweramp.apiexample.FilesActivity.onItemClick(FilesActivity.java:165)
W/System.err: at android.widget.AdapterView.performItemClick(AdapterView.java:310)
W/System.err: at android.widget.AbsListView.performItemClick(AbsListView.java:1164)
W/System.err: at android.widget.AbsListView$PerformClick.run(AbsListView.java:3139)
W/System.err: at android.widget.AbsListView$3.run(AbsListView.java:4054)
W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
W/System.err: at android.os.Looper.loop(Looper.java:154)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6186)
W/System.err: at java.lang.reflect.Method.invoke(Native Method)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
My "AndroidManifest.xml" file has:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
First, requestPermissions() is asynchronous. It is not a blocking call. When it returns, you do not yet have the permission, but your code assumes that it does.
Second, WRITE_EXTERNAL_STORAGE has nothing to do with a path like /storage/0094-1EEE/Music/example.mp3, in all likelihood. WRITE_EXTERNAL_STORAGE is for external storage. It is very unlikely that /storage/0094-1EEE/ is a location on external storage. More likely, it is a location on removable storage, and you cannot read or write this location on Android 4.4+ using File.