I'm newbe in android development.
I bulid app for automatic downloader,
every downloads work properly and save on my sd card,
but the drm file not open on device.
I explain my self, I try download file with extension dd\dm,
If the regular browser download dd\dm files, the device extract them to dcf extension.
my app not do that... I notied then if my device do restart, every is right,
in fact the device change the extension of this file to dcf, and i can play this song, If i didnt originator restart to device, the files extension stay on .dd.dm
mt content type is: application/vnd.oma.drm.message
Somebody knows how i need care of that??
This Is my code.....
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.getContent();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// Insert Information Of File to Array
getCurrentArray()[index].setSizeOfFile(OrangeFile.convertToStringRepresentation(lenghtOfFile));
getCurrentArray()[index].setMimeOfFile(conection.getContentType());
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream(mPath + getCurrentArray()[index].getNameOfFile() + "." + getCurrentArray()[index].getExtOfFile());
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
Though its an old question, not sure if you got any answer for this already.
Below is how to overcome this problem.
First of all you cannot download ".dm" & ".dd" files via File Connection API, though you can successfully download them you cannot use it directly.
Check this http://www.developer.nokia.com/Community/Wiki/Saving_and_reading_DRM-protected_files_using_FileConnection_API_and_Mobile_Media_API
".dm" files are converted to ".dcf" automatically when there is a thorough memory scan
of sd card by your device OS. If you just unmount the sd card and remount then also the files are converted without having to restart the device.
So how to actually download these files to be used immediately without restarting the device.
As stated in the above link you can download the protected content only via HTTP (in browser) or MMS.
So create an Intent with url pointing to the ".dm" file on your server and fire it. Browser will catch the url and download the file and convert it to ".dcf" automatically as soon as the download is complete.
Hope this helps.
Edit: You can explicitly invoke the media scanner once you downloaded the file via File Connection API by creating an intent with action "ACTION_MEDIA_SCANNER_SCAN_FILE" and send a broadcast.
Related
In my application I download media from server via HTTP connection. While downloading if connection is break anyhow (say, no n/w, permission revoke), File get downloaded partially.
Earlier we are deleting the file and downloading it from the scratch.
Now, the requirement is changed. I have to continue from where I left (like in WhatsApp).
So what I am doing is checking the file existence and if file exist skip the stream. Please find the below code snip.
InputStream is = con.getInputStream();
File file = new File(targetPath);
boolean fileExist = file.exists();
if (fileExist) {
long skippedBytes = is.skip(file.length());
}
// opens an output stream to save into file
OutputStream os = new FileOutputStream(targetPath, fileExist);
Its working merely in respect of skipping but actually not working.
Say, file (video) length is 20 sec and in first attempt I downloaded up to 6 sec and rest subsequently. But when I play it just play till 6 sec then after throw the usual Video playback error.
File file = new File(targetPath);
if (file.exists()) {
con.setRequestProperty("Range", "bytes=" + (file.length()) + "-");
} else {
con.setRequestProperty("Range", "bytes=" + 0 + "-");
}
I have implemented the OneDrive picker in my app to allow the user to easily select a file from the OneDrive cloud storage. My app then gets the weblink that points to the file. I would now like to download (make a copy) of the file to the local storage on the Android device.
I would have thought this would be simple (As Dropbox made downloading a local copy part of their picker function) but it seems OneDrive has not. I've done some searches to find out how to download a file give the weblink, but they either seem way to complicated or have not worked.
Below is the code for the onactivity result from the OneDrive picker. Now that I have the Uri, please help me with how to get a local copy of the file so that I can use it. Thanks!
if (requestCode == ONEDRIVE_CHOOSER_REQUEST)
{
// Get the results from the picker
IPickerResult result = mPicker.getPickerResult(requestCode, resultCode, data);
// Handle the case if nothing was picked
if (result != null) {
// Do something with the picked file
Uri fileUri = result.getLink();
Okay, third time was the charm. Although I really was surprised there isn't and easier way to download a file. If anyone has a simpler solution, I'd love to hear it.
I followed some advice from this post How to download and save a file from Internet using Java?
and have managed to download the file from OneDrive.
public static void download(String address, String localFileName) {
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
try {
URL url = new URL(address);
out = new BufferedOutputStream(new FileOutputStream(localFileName));
conn = url.openConnection();
in = conn.getInputStream();
byte[] buffer = new byte[1024];
int numRead;
long numWritten = 0;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
numWritten += numRead;
}
System.out.println(localFileName + "\t" + numWritten);
}
catch (Exception exception) {
exception.printStackTrace();
}
finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
catch (IOException ioe) {
}
}
I don't know what URL the picker gives you but doing this via OneDrive web you get a link which just shows the File. But you can translate this link to get a direct download link:
The link you get:
https://onedrive.live.com/redir?resid=8F99649728BEB2F3%212780
You just need to replace redir by download:
https://onedrive.live.com/download?resid=8F99649728BEB2F3%212780
Reference: How to get direct download link from OneDrive
But you should keep in mind that this is no official way (at least I couldn't find this information on a Microsoft website) so it's possible that Microsoft changes this and your links don't work anymore.
Items in my ListView contains images that should be downloaded from the network. I start downloading process in getView() method of my adapter. The question is related to next issue: when I fling list to the end images appears after quite big delay. This time is taken by downloading process for all the items that appeared on the screen. I'd like to cancel network request when item goes outside the screen. Currently I do it when view is recycled:
if (convertView != null)
CancelRequest(convertView.getTag);
But it cancel requests from very few items. So I'm wondering if someone know better solution.
I recommend you to use this library https://github.com/nostra13/Android-Universal-Image-Loader
It provides you easy way to show images (it downloaded and cash it) by url in any place, includes ListView. It will solve the problem you have now.
If you wan't write your own solutions, here is a small tip:
In GetView start download image in separate thread. This way you don't need to wait while image will be downloaded.
While image is downloading set temporary image into listview.
When image will be downloaded change temporary image to downloaded one.
You can't cancel request in the middle of downloading (you can't stop the Thread when it already started to download). You can use executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) to run lots of thread in the same time. But again, I think there is no reason to write all this logic, just use Universal Image Loader.
Edit:
If you you use AyncTask for downloading images, you can do something like this:
URL url = new URL(Your url);
URLConnection conexion = url.openConnection();
conexion.connect();
long lenghtOfFile = conexion.getContentLength();
InputStream is = url.openStream();
File directory = new File(
Environment.getExternalStorageDirectory() + "/Directory/"
+ yourImageName + "/");
if (!directory.exists()) {
podcastDirectory.mkdirs();
}
FileOutputStream fos = new FileOutputStream(directory + "/"
+ name + "." + extension);
byte data[] = new byte[1024];
int count = 0;
while ((count = is.read(data)) != -1) {
if (isCancelled()) {
// Stop everything if canceled.
is.close();
fos.flush();
fos.close();
return;
}
fos.write(data, 0, count);
}
is.close();
fos.flush();
fos.close();
I found better solution.
AbsListView has method setRecycleListener(RecyclerListener). A RecyclerListener is an interface with the only method onMovedToScrapHeap(View view). Probably it is the best place to cancel network request getting URL from views' tag.
See source
As you understand, I will download application from my server if user click on the download link. And of course for installing, user will accept in irder to install it. Thus, I wonder ;
Is it possible to download package from my server? If yes how ?
Yes, it is possible. Make sure you have your server configured to use the appropriate mime type.
AddType application/vnd.android.package-archive .apk
OR
Download App
To download the apk in your app, you can use the my open source library here. While it is meant for checking for and downloading updates, you can use it to download other apk files (or any other file at all) as well.
In your Activity add the following code to your onCreate(). If you don't want toast notifications, change the second parameter to false:
UpdateChecker checker = new UpdateChecker(this, true);
Then, use the following to download and install the update. Note that this will show a progress dialog while downloading:
checker.downloadAndInstall("URL with http:// to the location of the update apk");
If the Android framework has downloaded an .apk file it will ask you if you want to install it. Simple as that.
here is the code to download the apk file:
String fileName="yourApk.apk";
try
{
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath()+"/DownloadedApk/");
if(dir.exists()==false)
{
dir.mkdirs();
}
URL url = new URL("http://www.example.com/apk/yourApk.apk");
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
FileOutputStream fos = new FileOutputStream(dir+"/"+fileName);
byte data[] = new byte[1024];
long lenghtOfFile=ucon.getContentLength();
int count = 0;
long total = 0;
int progress = 0;
while (((count=is.read(data)) != -1))
{
total += count;
int progress_temp = (int) ((int)total*100/lenghtOfFile);
if(progress_temp%10 == 0 && progress != progress_temp)
{
progress = progress_temp;
publishProgress(progress);
}
fos.write(data, 0, count);
}
is.close();
fos.close();
} catch (Exception e)
{
Log.d("DownloadManager", "Error: " + e);
}
I have a large data file, which is zipped, and approximately 20MB. When it's unzipped, it's up to about 50MB. The following source code works fine. I found the original on the web somewhere else and modified it a bit. And this method is called within the AsyncTask.doInBackground.
So, what I want to know is, how can I save the on going status(? sorry, I don't know the proper English word) and resume the procedure later? I mean, this method takes a bit long time (about a minute on an emulator), and I know there is no way since the data is kind of huge. So, if a main activity of this method gets killed, I want to save the current status of decompressing the file, and when the activity gets active, I want to resume decompressing from the last point. Hope my explanation clears my intent.
I was thinking using a service, but I also want to interact with UI, such as showing a progress or whatever. I can't find good information to do that in the service when I roughly scan the reference, but is there a way to do that in the service? And do you think I should use it?
Anyway, my main point is how to resume decompressing a file.
private final static int CHUNK_SIZE = 32 * 1024;
byte[] _fileIOBuffer = new byte[CHUNK_SIZE];
public void unzipFile(DBFileDownloader downloader, File zipFile, String directory)
throws IOException
{
ZipInputStream in = null;
FileOutputStream os = null;
try
{
in = new ZipInputStream (new FileInputStream(zipFile));
ZipEntry entry = null;
while ((entry = in.getNextEntry ())!= null)
{
String entryName = entry.getName();
if (entry.isDirectory ()) {
File file = new File (directory, entryName);
file.mkdirs();
}
else {
File file = new File(directory, entryName);
if (file.exists()){
file.delete(); // I don't know how to append, so delete it always
}
os = new FileOutputStream (file);
int bytesRead = 0;
while ((bytesRead = in.read (_fileIOBuffer))!= -1) {
os.write(_fileIOBuffer, 0, bytesRead);
// progress procedure
}
os.close();
}
}
}
catch (FileNotFoundException e) {
Log.v("unzip", e.getMessage());
}
catch (IOException e) {
Log.v("unzip", e.getMessage());
}
finally{
if (in != null ){
in.close();
}
if (os != null ){
os.close();
}
}
}
Thanks in advance,
yokyo
So, if a main activity of this method
gets killed, I want to save the
current status of decompressing the
file, and when the activity gets
active, I want to resume decompressing
from the last point.
That will be extremely difficult, if not impossible.
I was thinking using a service, but I
also want to interact with UI, such as
showing a progress or whatever.
This is a fine plan. Just have the activity register a listener with the service, and the service calls that listener for "a progress or whatever".