is it possible downloading application from my web site - android

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);
}

Related

Android partial download http

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 + "-");
}

How to download a file from OneDrive after using the OneDrive picker to get the weblink to the File?

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.

attach binary to android app

i am breaking my brain trying to attach an arm pre-compiled binary to my private android app.
if you don't mind, i tell you about my app. it just needs to modify iptables rules because of my gprs communication with my robot. it is a remote control for android, and i get better results if i deny all traffic instead my robot's one.
so i compiled an iptables with my cyanogenmod's version 11 iptables, but with -save -restore support, since i want to restore the rules after finishing the control of my robot..
the thing is that i've been searching in google for a lot of while, and i just found droidwall which seems to only create a 'raw' directory into the 'res' top dir, and once installed, i can see on adb shell the folder 'app_bin' inside /data/data's path.
but when i do install my app, with those dirs createds i can not see even the binary in some strange path... really, is this a very rare case? I don't find any documentation on the network...
thanks a lot,
hope you find it helpful.
abel.
EDIT (possible sollution)
I've downloaded the code from android_firewall project, where it seems to be copying from the apk resource, to the bin directory:
./src/com/jtschohl/androidfirewall/Api.java: final String app_iptables = dir + "/iptables_armv5";
./src/com/jtschohl/androidfirewall/Api.java: // Check iptables_armv5
./src/com/jtschohl/androidfirewall/Api.java: File file = new File(ctx.getDir("bin", 0), "iptables_armv5");
./src/com/jtschohl/androidfirewall/Api.java: copyRawFile(ctx, R.raw.iptables_armv5, file, "755");
I am going to try. Keep on news...
Yes, this is the sollution. The folder name "app_%{TYPE}" is the one returned by the calling of the function getDir(%{TYPE}, MODE_PRIVATE);
So the following code, does the desired functionality:
private static void copyRawFile(Context ctx, int resid, File file, String mode) throws IOException, InterruptedException {
final String abspath = file.getAbsolutePath();
// Write the iptables binary
final FileOutputStream out = new FileOutputStream(file);
final InputStream is = ctx.getResources().openRawResource(resid);
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
is.close();
// Change the permissions
Runtime.getRuntime().exec("chmod " + mode + " " + abspath).waitFor();
}
private boolean assertBinaries(Context ctx, boolean showErrors) {
try {
File file = new File(ctx.getDir("bin", MODE_PRIVATE), "xtables_multi");
if (!file.exists()) {
copyRawFile(ctx, R.raw.xtables_multi, file, "755");
}
file = new File(ctx.getDir("bin", MODE_PRIVATE), "iptables_new.sh");
if (!file.exists()) {
copyRawFile(ctx, R.raw.iptables_new, file, "755");
}
} catch(Exception e) {
if (showErrors) {
alert(ctx, R.string.error_assertbinaries + " " + e);
}
return false;
}
return true;
}
public static void alert(Context ctx, CharSequence msg) {
if (ctx != null) {
Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
}
}
Hope that helps,
cheers; Abel.

Download DRM Files on my develop android app

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.

How should I decompress a large data file in AsyncTask.doInBackground?

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".

Categories

Resources