I'm uploading files(Images,Videos and Audios) from Android side to PHP server. It's working good for small files. But for large files it is giving unexpected results, like file uploads but on android side it gives timeout exception.
So please help me, how i tackle all the scenarios for file uploading. How i can use HttpMultipart entity and how i can set relative timeout against different size files.
My code is:
File myFile = new File(filePath);
RequestParams params = new RequestParams();
try {
params.put("uploaded_file", myFile);
} catch (FileNotFoundException e) {
}
URL=getResources().getString(com.newing.R.string.server_adderess)+URL+fileType+"&lessonID="+LessonID;
client.post(URL, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.w("async", "success!!!!");
UtilityFunctions.showNotification(getApplicationContext(),
"File uploading completed.");
stopSelf();
}
#Override
public void onFailure(Throwable error) {
Log.w("async", "failure!!!!");
UtilityFunctions.showNotification(getApplicationContext(),
"File couldn't upload. Please try later.");
stopSelf();
}
});
you can try use Ion is a great library for Asynchronous Networking and Image Loading https://github.com/koush/ion
a simple example uploading a file
Ion.with(getContext(), "https://koush.clockworkmod.com/test/echo")
.uploadProgressBar(uploadProgressBar)
.setMultipartFile("filename.zip", new File("/sdcard/filename.zip"))
.asJsonObject()
.setCallback(...)
check the project site for more examples and wiki
Related
In an Android aplication, developed in Java, I download an apk from a web service. After downloading file to the mobile device (tablet) I can not open the file by clicking on it. I get "error" message when I try to open the downloaded file.
But If I copy the file using Android system copy function I can open the copied version.
If I restart the Android device the downloaded file can be opened.
What can be the problem in downloading file?
This is the class that downloads file.
public class NewAppDownloader extends AsyncTask<String, String, String> {
Context context;
public NewAppDownloader(Context aContext) {
this.context=aContext;
}
protected String doInBackground(String... params) {
String downloadedAppFilePath= params[1];
HttpURLConnection connection = null;
BufferedReader bufferedReader = null;
FileOutputStream fileOutputStream = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/apk");
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// create directory
File dir = new File(downloadedAppFilePath);
dir.mkdirs();
InputStream inputStream = connection.getInputStream();
fileOutputStream = new FileOutputStream(downloadedAppFilePath + "/my.apk");
byte[] b = new byte[1024];
int len = 0;
while ((len = inputStream.read(b, 0, b.length)) != -1) {
fileOutputStream.write(b, 0, len);
}
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return "Download completed.";
}
protected void onPostExecute (String s){
context=null;
}
}
This is the calling code in an onclick event
public void onClick(View v) {
(new NewAppDownloader(getContext())).execute(appDownloadConnection,downloadedAppFilePath);
}
Thanks in advance for all help and answers.
This is by design. Refer to the developer page on alternative distribution, specifically the section on distributing through a website. Copied here for reference:
If you don't want to release your apps on a marketplace such as Google Play, you can make them available for download on your website or server, including on a private or enterprise server. To do this, first prepare your apps for release in the normal way, then host the release-ready APK files on your website and provide users with a download link. To install an app distributed in this way, users must opt-in for installing unknown apps.
If your device already has that security restriction disabled, it might be that whatever app you are using to open the downloaded APK does not recognize it as that format. What app are you using to open it and what is the error message displayed? The reason it opens upon restart is likely due to the OS scanning and identifying it as an APK, such that whatever app you use to open it installs it successfully. Copying the downloaded file could also trigger the same process.
Also, AsyncTask has been deprecated. Consider using an Executor or some other modern concurrency pattern instead. Check out Processes and Threads for alternatives or switch to Kotlin for even easier concurrency with Coroutines :)
How can I get a shared link of a recently uploaded file when using box in Android.
mFileApi.getCreateSharedLinkRequest(fileId).setCanDownload(true)
.setAccess(BoxSharedLink.Access.OPEN)
.toTask().addOnCompletedListener(new BoxFutureTask.OnCompletedListener<BoxFile>() {
#Override
public void onCompleted(BoxResponse<BoxFile> response) {
if (response.isSuccess()) {
BoxFile boxFile = response.getResult();
String downloadUrl = boxFile.getSharedLink().getDownloadURL();
Log.e("downloadurl", "onCompleted: " + downloadUrl);
//This return me a web link to show the Box page to download the file
} else {
Toast.makeText(MainActivity.this, "error while getting sharelink", Toast.LENGTH_SHORT).show();
}
}
}).run();
You must first create the link, it is not created automatically. See this answer how to do it: How to create shared link in box using java sdk
I'm developing a stream video app in Android with MediaPlayer. The problem is that I need to show the current bitrate, but I haven't found any valid suggestions on how to do get it?
Here is how I'm setting the video url to play:
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(VIDEO_PATH);
mediaPlayer.prepare();
mediaPlayer.init();
} catch (IOException e) {
e.printStackTrace();
}
I don't know if the only way to get that working is using ExoPlayer (which I've read it may be possible)
Any suggestions?
Thanks!
Apparently you cannot do this with MediaPlayer but you can use MediaMetadataRetriever, which is available since API level 10, i.e., quite a while ago.
int getBitRate(String url) {
final MediaMetadataRetriever mmr = new MediaMetadataRetriever();
try {
mmr.setDataSource(url, Collections.EMPTY_MAP);
return Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE));
} catch (NumberFormatException e) {
return 0;
} finally {
mmr.release();
}
}
The disadvantage this can have is that you will make an extra HTTP request for getting the metadata (only an RTT if you are streaming from an URI; if you are reading from an file descriptor it could be more serious). Hopefully no big deal.
I've got a really odd problem with the Google Drive Android SDK. I've been using it for several months now, and until last week it performed perfectly. However, there is now a really odd error, which doesn't occur all the time but does 9 out of 10 times.
I'm trying to list the user's files and folders stored in a particular Google Drive folder. When I'm trying to use the method Drive.files().list().execute(), 9 out of 10 times literally nothing happens. The method just hangs, and even if I leave it for an hour, it just remains doing... nothing.
The code I'm using is below - all of this being run within the doInBackground of an AsyncTask. I've checked credentials - they are all fine, as is the app's certificate's SHA1 hash. No exceptions are thrown. Google searches have yielded nothing. Here is the particular bit of code that's bothering me:
try {
GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
SettingsActivity.this, Arrays.asList(DriveScopes.DRIVE));
if (googleAccountName != null && googleAccountName.length() > 0) {
credential.setSelectedAccountName(googleAccountName);
Drive service = new Drive.Builder(AndroidHttp.newCompatibleTransport(),
new GsonFactory(), credential).build();
service.files().list().execute(); // Google Drive fails here
} else {
// ...
}
} catch (final UserRecoverableAuthIOException e) {
// Authorisation Needed
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
startActivityForResult(e.getIntent(), REQUEST_AUTHORISE_GDRIVE);
} catch (Exception e) {
Log.e("SettingsActivity: Google Drive", "Unable to add Google Drive account due to Exception after trying to show the Google Drive authroise request intent, as the UserRecoverableIOException was originally thrown. Error message:\n" + e.getMessage());
}
}
});
Log.d("SettingsActivity: Google Drive", "UserRecoverableAuthIOException when trying to add Google Drive account. This is normal if this is the first time the user has tried to use Google Drive. Error message:\n" + e.getMessage());
return;
} catch (Exception e) {
Log.e("SettingsActivity: Google Drive", "Unable to add Google Drive account. Error message:\n" + e.getMessage());
return;
}
I'm using Drive API v2. Thanks everyone!
Edit
Having played around a bit more, it turns out this isn't for just listing files. Trying to interact with any file on Google Drive behaves the same way - deleting, downloading, creating... Anything! I have also noticed that putting the device in aeroplane mode so it has not internet access makes no difference either: Google Drive doesn't throw an exception, or even return, it just freezes the thread it's on.
I've updated to the very latest Drive API lib but that hasn't helped. I remembered that the error happened soon after I added the JSch SSH library to the project, so I removed that, but it made no difference. Removing and re-adding the Drive API v2 has made no difference either, and nor has cleaning the project.
Edit 2
I've found something which may be significant. On the Google Developer console, I had some Drive errors recorded as follows:
TOP ERRORS:
Requests % Requests Methods Error codes
18 38.30% drive.files.list 400
14 29.79% drive.files.insert 500
11 23.40% drive.files.update 500
4 8.51% drive.files.get 400
Do you reckon these are the errors? How could I fix them? Thanks
This is my code and it's work
new AsyncTask<Void, Void, List<File>>() {
#Override
protected List<File> doInBackground(Void... params) {
List<File> result = new ArrayList<File>();
try {
com.google.api.services.drive.Drive.Files.List list = service.files().list();
list.setQ("'" + sourcePath + "' in parents");
FileList fileList = list.execute();
result = fileList.getItems();
if(result != null) {
return result;
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(List<File> result) {
//This is List file from Google Drive
};
}.execute();
I've come up with a solution which does work, and thought I'd post it so others could see it if they happen to come across the problem.
Luckily, I had backed up all of the previous versions of the app. So I restored the whole project to how it was two weeks ago, copied and pasted all changes from the newer version which had been made since then, and it worked. I don't see why this should work, since the end result is the same project, but it does!
Google Drive List Files
This might help you.. Try to display it in ListView u will see all fetched folders
public void if_db_updated(Drive service)
{
try {
Files.List request = service.files().list().setQ("mimeType = 'application/vnd.google-apps.folder'");
FileList files = request.execute();
for(File file : files.getItems())
{
String title = file.getTitle();
showToast(title);
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT).show();
}
});
I'm working on this project for a client and we're supposed to stream audio from a server onto a device running Android Gingerbread. To retrieve the stream, the Android client needs to make a request for a variant playlist, and then make a request for the playlist itself (the one with URIs that point to the TS file chunks themselves). Once that's done, the client app decrypts the chunks and sends them to the platform for playback.
The problem I'm having revolves around the security part. Our client(the company in question) uses a proprietary encryption scheme that serves the keys for decrypting the TS file chunks ahead of time through an HTTP request instead of following the HLS spec and serving the key files through URI(s) listed in the index files themselves. As far as I can tell, the Android Mediaplayer framework has the ability to find these key files and generate/find the appropriate IVs for decryption IF the key file URIs are in the index files.
Unfortunately, what this all means is that I can't decrypt the file chunks and play back the stream without gaps between each segment -- I accomplish this by making HTTP GET requests for each segment, downloading them to internal storage, applying decrypting, and then playing them back using the following code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File dir = new File(TS_FILE_DIR);
String [] files = dir.list();
mTsFiles = new ArrayList<File>();
for (String file : files) {
String path = TS_FILE_DIR + file;
mTsFiles.add(new File(path));
}
mMediaController = new MediaController(this);
mVideoView = (VideoView)findViewById(R.id.video_view_1);
mVideoView.setVideoPath(mTsFiles.get(0).getAbsolutePath());
mVideoView.setMediaController(mMediaController);
mVideoView.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.start();
}
});
mVideoView.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.pause();
mp.reset();
if (mIndex < mTsFiles.size()) {
mIndex++;
try {
mp.setDataSource(mTsFiles.get(mIndex).getAbsolutePath());
mp.prepareAsync();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
I've tried:
1) Using 2 mediaplayers and switching between the 2, but it doesn't work at all
2) Staring at the source code for ICS to get an idea of how this all works, but its very complex and I'm not well versed in c++
Is there anything I missed?