I`am trying to download and install an apk from some link,
but for some reason i get an exception.
I have one method downloadfile() which downloading the file and a call
to and installFile() method, which supposed to install it in the device.
some code:
public void downloadFile()
{
String fileName = "someApplication.apk";
MsgProxyLogger.debug(TAG, "TAG:Starting to download");
try
{
URL u = new URL(
"http://10.122.233.22/test/someApplication.apk");
try
{
HttpURLConnection c = (HttpURLConnection) u.openConnection();
try
{
c.setRequestMethod("GET");
c.setDoOutput(true);
try
{
c.connect();
FileOutputStream f = context.openFileOutput(fileName,
context.MODE_WORLD_READABLE);
try
{
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
int totsize = 0;
try
{
while ((len1 = in.read(buffer)) > 0)
{
totsize += len1;
f.write(buffer, 0, len1);// .write(buffer);
}
} catch (IOException e)
{
e.printStackTrace();
}
f.close();
MsgProxyLogger.debug(TAG, TAG
+ ":Saved file with name: " + fileName);
InstallFile(fileName);
} catch (IOException e)
{
e.printStackTrace();
}
} catch (IOException e)
{
e.printStackTrace();
}
} catch (ProtocolException e)
{
e.printStackTrace();
}
} catch (IOException e)
{
e.printStackTrace();
}
} catch (MalformedURLException e)
{
e.printStackTrace();
}
}
and this is the install file method:
private void InstallFile(String fileName)
{
MsgProxyLogger.debug(TAG, TAG + ":Installing file " + fileName);
String src = String.format(
"file:///data/data/com.test/files/",
fileName);
Uri mPackageURI = Uri.parse(src);
PackageManager pm = context.getPackageManager();
int installFlags = 0;
try
{
PackageInfo pi = pm.getPackageInfo("com.mirs.agentcore.msgproxy",
PackageManager.GET_UNINSTALLED_PACKAGES);
if (pi != null)
{
MsgProxyLogger.debug(TAG, TAG + ":replacing " + fileName);
installFlags |= PackageManager.REPLACE_EXISTING_PACKAGE;
}
} catch (NameNotFoundException e)
{
}
try
{
// PackageInstallObserver observer = new PackageInstallObserver();
pm.installPackage(mPackageURI);
} catch (SecurityException e)
{
//!!!!!!!!!!!!!here i get an security exception!!!!!!!!!!!
MsgProxyLogger.debug(TAG, TAG + ":not permission? " + fileName);
}
this is the exception details:
"Neither user 10057 nor current process has android.permission.INSTALL_PACKAGES".
and i have set in my main app that permission in the manifest.
anyone has any idea?
thanks,
ray.
You cannot install APKs that way -- only applications that are part of the system firmware can do that.
You should be able to use an ACTION_VIEW Intent, with a MIME type of application/vnd.android.package-archive and a Uri pointing to your file. Note that this may not work on devices that do not have "allow non-Market installs" checked.
You need add that permission to manifest
http://developer.android.com/reference/android/Manifest.permission.html
Related
i am trying to create a file in the internal storage, i followed the steps in android developers website but when i run the below code there is no file created
please let me know what i am missing in the code
code:
File file = new File(this.getFilesDir(), "myfile");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fOut = null;
try {
fOut = openFileOutput("myfile",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fOut.write("SSDD".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
By default these files are private and are accessed by only your application and get deleted , when user delete your application
For saving file:
public void writeToFile(String data) {
try {
FileOutputStream fou = openFileOutput("data.txt", MODE_APPEND);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fou);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
For loading file:
public String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("data.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
Try to get the path for storing files were the app has been installed.The below snippet will give app folder location and add the required permission as well.
File dir = context.getExternalFilesDir(null)+"/"+"folder_name";
If you are handling files that are not intended for other apps to use, you should use a private storage directory on the external storage by calling getExternalFilesDir(). This method also takes a type argument to specify the type of subdirectory (such as DIRECTORY_MOVIES). If you don't need a specific media directory, pass null to receive the root directory of your app's private directory.
Probably, this would be the best practice.
Use this method to create folder
public static void appendLog(String text, String fileName) {
File sdCard=new File(Environment.getExternalStorageDirectory().getPath());
if(!sdCard.exists()){
sdCard.mkdirs();
}
File logFile = new File(sdCard, fileName + ".txt");
if (logFile.exists()) {
logFile.delete();
}
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.write(text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
In this method, you have to pass your data string as a first parameter and file name which you want to create as second parameter.
I am facing trouble in updating the existing cached file within my Android Application.
for(DbxFileInfo fInfo : fileList)
{
Log.d(TAG, "File Path = "+fInfo.path.toString());
String fileName = fInfo.path.getName().trim();
try
{
DbxPath tempFilePath = new DbxPath(fInfo.path.toString());
DbxFile tempFile = mDbFileSystem.open(tempFilePath);
if(tempFile.getSyncStatus().isCached)
{
Log.v(TAG, "File is already cached !");
if(tempFile.getSyncStatus().isLatest)
{
Log.v(TAG, "File's Latest Version is Cached !");
}
else
{
Log.v(TAG, "File's Latest Version is not Cached !");
}
}
try
{
tempFile.getNewerStatus();
}
catch(Exception dBException)
{
Log.e(TAG, "Error while getting newer Status !");
}
InputStream input = new BufferedInputStream(tempFile.getReadStream());
OutputStream output = new FileOutputStream(cntx.getFilesDir() + "/SyncedData/" + fileName);
byte data[] = new byte[1024];
int count;
//total size is in Bytes
while ((count = input.read(data)) != -1)
{
totalBytesDownloaded += count;
publishProgress((int) (totalBytesDownloaded * 100/totalFileSize));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
tempFile.close();
mDbFileSystem.delete(tempFile.getPath());
result = true;
}
catch(Exception e)
{
Log.e(TAG, "Error occured while downloading files !, Error = "+e.toString());
result = false;
}
}
I am putting different files with same names on my Synced Dropbox folder and after Downloading them i am getting the older version of files.
Is there any way i can update my existing cached files or Clear the Dropbox Cache (that is within my App)
Any help is highly appreciated, thanks.
Here's how the Sync API works:
It constantly syncs metadata (what files exist and their revisions) and notifies you via listeners you set up on the file system.
For open files, it downloads any newer version of the file available and notifies you via the listener you set up on the file itself.
So if you want to get the latest version of a file, you need to open the file and hold it open while waiting for the listener to notify you that the newer version of the file is cached. Then you can call update to get access to that new data.
EDIT: Pasting code from https://www.dropbox.com/developers/sync/start/android#listeners:
DbxFileStatus status = testFile.getSyncStatus();
if (!status.isCached) {
testFile.addListener(new DbxFile.Listener() {
#Override
public void onFileChange(DbxFile file) {
// Check testFile.getSyncStatus() and read if it's ready
}
});
// Check if testFile.getSyncStatus() is ready already to ensure nothing
// was missed while adding the listener
}
Here is my attempt to get the latest file but as I stated in the comment to your question, it seems I sometimes have to do two sync calls in order to get the latest file.
The fileModified and fileSize comparison is rather crude but seems to do the trick. Better than what I have found so far at least.
public DropboxFileDownloader() {
super("FileDownloader");
}
#Override
protected void onHandleIntent(Intent intent) {
String turiosHome = intent.getStringExtra(Constants.EXTRA_HOME);
String fileName = intent.getStringExtra(Constants.EXTRA_FILENAME);
String folderPath = intent.getStringExtra(Constants.EXTRA_FOLDERPATH);
ResultReceiver receiver = intent.getParcelableExtra(Constants.EXTRA_RECEIVER);
Bundle bundle = new Bundle();
String fullpath = folderPath + "/" + fileName;
DbxFile file;
long fileModified = 0;
long fileSize = 0;
try {
file = dbxFs.open(new DbxPath(fullpath));
try {
DbxFileStatus fileStatus = file.getNewerStatus();
if (fileStatus != null && !fileStatus.isLatest) {
/*while (file.getNewerStatus().pending == PendingOperation.DOWNLOAD) {
Log.d(TAG, "Waiting for " + fileName + " to be downloaded");
Thread.sleep(1000);
}*/
if (fileStatus.isCached) {
//Start of Edit
try
{
//Running this do while loop until the Latest version of this file is cached.
do
{
Log.d(TAG, "Updating the existing file !");
//Updating the file
file.update();
while (file.getNewerStatus().pending ==PendingOperation.DOWNLOAD)
{
Log.d(TAG, "Waiting for " + fileName+ " to be downloaded");
Thread.sleep(1000);
}
} while (fileStatus.isLatest);
}
catch (Exception dBException)
{
Log.e(TAG, "Error while getting newer Status !, Error = "+dBException.toString());
dBException.printStackTrace();
}
//End of Edit
}
}
fileModified = file.getInfo().modifiedTime.getTime();
fileSize = file.getInfo().size;
} catch (DbxException e) {
Log.e(TAG, e.getMessage(), e);
bundle.putString(Constants.EXTRA_MESSAGE, e.getMessage());
receiver.send(DropboxFileDownloaderResultReceiver.RESULTCODE_ERROR, bundle);
return;
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (InvalidPathException e1) {
Log.e(TAG, e1.getMessage(), e1);
bundle.putString(Constants.EXTRA_MESSAGE, e1.getMessage());
receiver.send(DropboxFileDownloaderResultReceiver.RESULTCODE_ERROR, bundle);
return;
} catch (DbxException e1) {
Log.e(TAG, e1.getMessage(), e1);
bundle.putString(Constants.EXTRA_MESSAGE, e1.getMessage());
receiver.send(DropboxFileDownloaderResultReceiver.RESULTCODE_ERROR, bundle);
return;
}
File stored_dir = new File(turiosHome + "/" + folderPath);
if (!stored_dir.exists()) {
stored_dir.mkdirs();
}
File stored_file = new File(turiosHome + "/" + folderPath,
fileName);
// File stored_file = getFileStreamPath(fileName);
long local_modified = stored_file.lastModified();
long local_size = stored_file.length();
boolean should_sync = (fileModified > local_modified)
|| fileSize != local_size;// && Math.abs(fileModified -
// local_modified) >
// TimeUnit.MILLISECONDS.convert(1,
// TimeUnit.MINUTES);
boolean fileexists = stored_file.exists();
if (should_sync || !fileexists) {
InputStream inputStream = null;
FileOutputStream out = null;
try {
// read this file into InputStream
inputStream = file.getReadStream();
out = new FileOutputStream(stored_file);
int read = 0;
byte[] bytes = new byte[1024];
int bytes_counter = 0;
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
bytes_counter++;
}
Log.d(TAG, "Wrote: " + file.getPath().getName() + " "
+ bytes_counter + " kb");
if (!fileexists) {
bundle.putString(Constants.EXTRA_FILEPATH, fullpath);
receiver.send(DropboxFileDownloaderResultReceiver.RESULTCODE_CREATED, bundle);
} else {
bundle.putString(Constants.EXTRA_FILEPATH, fullpath);
receiver.send(DropboxFileDownloaderResultReceiver.RESULTCODE_UPDATED, bundle);
}
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
bundle.putString(Constants.EXTRA_MESSAGE, e.getMessage());
receiver.send(DropboxFileDownloaderResultReceiver.RESULTCODE_ERROR, bundle);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (out != null) {
out.flush();
out.close();
}
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
bundle.putString(Constants.EXTRA_MESSAGE, e.getMessage());
receiver.send(DropboxFileDownloaderResultReceiver.RESULTCODE_ERROR, bundle);
}
}
}
else {
bundle.putString(Constants.EXTRA_FILEPATH, fullpath);
receiver.send(DropboxFileDownloaderResultReceiver.RESULTCODE_UPTODATE, bundle);
}
file.close();
}
}
I can't found working example for me. But for my case - i don't need cashed version of files - only newest (data synchronization between devices).
I used
mDbFileSystem.setMaxFileCacheSize(0);
All or nothing. But now nessasary thread for downloading in background.
I unable to attach Audio file to Some of the Samsung Devices like Samsung GalaxyS2,Nexus etc.I don't know whats the problem.I am able to attach all other devices.Please someone help me for my this issue.My code is as:
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra("sms_body",
getResources().getText(R.string.Message));
sendIntent.setClassName("com.android.mms",
"com.android.mms.ui.ComposeMessageActivity");
AssetManager mngr = getAssets();
InputStream path = null;
try {
path = mngr.open("*.mp3");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedInputStream bis = new BufferedInputStream(path, 1024);
// get the bytes one by one
int current = 0;
//
try {
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
} catch (IOException e) {
// /TODO Auto-generated catch block
e.printStackTrace();
}
byte[] bitmapdata = baf.toByteArray();
File file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), "*.mp3");
// if (file.exists() == true) {
// } else {
// Log.v("directory is created", "new dir");
// file.mkdir();
// }
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
final File file1 = new File(Environment
.getExternalStorageDirectory().getAbsolutePath(),
"*.mp3");
Uri uri = Uri.fromFile(file1);
Log.e("Path", "" + uri);
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
sendIntent.setType("audio/mp3");
// sendIntent.putExtra(Intent.EXTRA_STREAM, mms_uri.toString());
startActivity(Intent.createChooser(sendIntent, ""));
// startActivity(sendIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!", Toast.LENGTH_LONG)
.show();
e.printStackTrace();
}
Don't set the class name explicitly by calling setClassName(). Instead just set the action, type and extra as described here.
You are assuming that there is ExternalStorage i.e. sd card available on the device. Your S2 or Nexus probably does not have the sd card. I have seen this issue before.
I am a newbie to Android. I am trying download a file from ftp server to sdcard using Apache Commons FTPClient. The line InputStream input = client.retrieveFileStream("/" + fileName); always returns null. But the file is there in Ftp location. Kindly help me to know where the mistake is.
I have set the following permissions in my manifest; android:name="android.permission.INTERNET" and android:name="android.permission.WRITE_EXTERNAL_STORAGE"
My Code
private static void downLoad(){
FTPClient client = new FTPClient();
FileOutputStream fos = null;
try {
client.connect("ftp.doamin.com");
client.login("8888", "8888");
String filePath = "/mnt/sdcard/download/CheckboxHTML.txt" ;
String fileName = "CheckboxHTML.txt";
fos = new FileOutputStream(filePath);
InputStream input = client.retrieveFileStream("/" + fileName);
byte[] data = new byte[1024];
int count = input.read(data);
while ((count = input.read(data)) != -1) {
fos.write(data, 0, count);
}
fos.close();
if(!client.completePendingCommand()) {
client.logout();
client.disconnect();
System.err.println("File transfer failed.");
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Thanks for your time and interest. Ananth.
AFAIK. You are suppose to finalize file transfers by calling completePendingCommand() and verifying that the transfer was indeed successful. i.e. you need to add call the function below fos.clos().
fos.close();
client.completePendingCommand()
You may also consider this, according to the API for FTPClient.retrieveFileStream(), the method returns null when it cannot open the data connection, in which case you should check the reply code (e.g. getReplyCode(), getReplyString(), getReplyStrings()) to see why it failed.
File file = new File(Environment.getExternalStorageDirectory() + "/pdf");
if(!file.exists())
file.mkdir(); //directory is created;
try {
ftp = new FTPClient();
ftp.connect("yours ftp URL",21);//don't write ftp://
try {
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
throw new Exception("Connect failed: " + ftp.getReplyString());
}
if (!ftp.login("username","password")) {
throw new Exception("Login failed: " + ftp.getReplyString());
}
try {
ftp.enterLocalPassiveMode();
if (!ftp.setFileType(FTP.BINARY_FILE_TYPE)) {
// Log.e(TAG, "Setting binary file type failed.");
}
transferFile(ftp);
} catch(Exception e) {
// handleThrowable(e);
} finally {
if (!ftp.logout()) {
// Log.e(TAG, "Logout failed.");
}
}
} catch(Exception e) {
// handleThrowable(e);
} finally {
ftp.disconnect();
}
} catch(Exception e) {
// handleThrowable(e);
}
}
private void transferFile(FTPClient ftp) throws Exception {
long fileSize=0;
fileSize = getFileSize(ftp, "nag.pdf");
Log.v("async","fileSize"+fileSize);
if(!(fileSize==0)){
InputStream is = retrieveFileStream(ftp, "nag.pdf");
downloadFile(is, fileSize);
is.close();
}
else
//nosuch files
if (!ftp.completePendingCommand()) {
throw new Exception("Pending command failed: " + ftp.getReplyString());
}
}
private InputStream retrieveFileStream(FTPClient ftp, String filePath)
throws Exception {
InputStream is = ftp.retrieveFileStream(filePath);
int reply = ftp.getReplyCode();
if (is == null
|| (!FTPReply.isPositivePreliminary(reply)
&& !FTPReply.isPositiveCompletion(reply))) {
throw new Exception(ftp.getReplyString());
}
return is;
}
private byte[] downloadFile(InputStream is, long fileSize)
throws Exception {
outputStream os = newFileOutputStream(Environment.getExternalStorageDirectory()
+ "/pdf/nag.pdf");
byte[] buffer = new byte[(int) fileSize];
int readCount;
while( (readCount = is.read(buffer)) > 0) {
os.write(buffer, 0, readCount);
}
Log.i("tag", "buffer = " + buffer);
return buffer; // <-- Here is your file's contents !!!
}
private long getFileSize(FTPClient ftp, String filePath) throws Exception {
long fileSize = 0;
FTPFile[] files = ftp.listFiles(filePath);
if (files.length == 1 && files[0].isFile()) {
fileSize = files[0].getSize();
}
Log.i("tag", "File size = " + fileSize);
return fileSize;
}
}
After have worked on this problem and spent hours, I've found out that the Android Apache retrieveFile() and retrieveFileStream sometimes don't work very well when the FileSize is too big.
Ensure to set the right TypeFile to BinaryFile
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
Also never forget to pass in LocalPassiveMode for download commands
mFTPClient.enterLocalPassiveMode();
I am trying to fetchg data from server like MP3 files, video files, etc. in my application. The application should show the list of video files received from the server.
How can I do this?
/** this function will download content from the internet */
static int writeData(String fileurl, boolean append, String path,
String filename, Activity mContext) throws CustomException {
URL myfileurl = null;
ByteArrayBuffer baf = null;
HttpURLConnection conn = null;
String mimeType="";
final int length;
try {
myfileurl = new URL(fileurl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn = (HttpURLConnection) myfileurl
.openConnection();
conn.setDoInput(true);
conn.connect();
conn.setConnectTimeout(100000);
length = conn.getContentLength();
mimeType=conn.getContentType().toString();
System.out.println("Extension..."+mimeType);
if(mimeType.equalsIgnoreCase("application/vnd.adobe.adept+xml") || mimeType.equalsIgnoreCase("text/html; charset=utf-8"))
return 0;
if (length > 0) {
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
baf = new ByteArrayBuffer(1000);
int current = 0;
while ((current = bis.read()) != -1) {
try {
baf.append((byte) current);
mBufferError=false;
} catch (Exception e){
// TODO: handle exception
mBufferError=true;
e.printStackTrace();
throw new CustomException("### memory problem ", "Buffer Error");
}
}
}
} catch (IOException e) {
mBufferError=true;
e.printStackTrace();
}
try{
if(conn.getResponseCode()==200 && mBufferError==false)
{
path = path + "/" + filename;
boolean appendData = append;
FileOutputStream foutstream;
File file = new File(path);
boolean exist = false;
try {
if (appendData)
exist = file.exists();
else
exist = file.createNewFile();
} catch (IOException e) {
try {
return 1;
} catch (Exception err) {
Log.e("SAX", err.toString());
}
}
if (!appendData && !exist) {
} else if (appendData && !exist) {
} else {
try {
foutstream = new FileOutputStream(file, appendData);
foutstream.write(baf.toByteArray());
foutstream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}catch (Exception e) {
// TODO: handle exception
throw new CustomException("### I/O problem ", "I/O Error");
}
return 1;
}
once download complete search the file with extension(.3gp) for video
hope it helps
Check this link,
https://stackoverflow.com/search?q=how+to+download+mp3+%2Cvideos+from+server+in+android
Try this code
url = "your url name+filename.jpg,mp3,etc..."
FileName = "/sdcard/savefilename" // save in your sdcard
try{
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.net.URL(url).openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(FileName);
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte[] data = new byte[1024];
int x=0;
while((x=in.read(data,0,1024))>=0){
bout.write(data,0,x);
}
fos.flush();
bout.flush();
fos.close();
bout.close();
in.close();
}
catch (Exception ex)
{
}
and after you want to use MediaPlayer
and create object of mediaplayer in your activity
and play.
mp.reset();
mp.start();