Parse error “installing an apk using intent” on Jelly Bean android - android

I am generating an android application which capable to include over-the-air updation in the android application. So that I am generating a Webservice for getting the versioncode so that I will compare the versioncode of installed application if it is lesser then I will trigger there is an update to install from the server, for this I using below code.
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "yourapp.apk");
downloadFile(file_url, outputFile);
installApk();
//downloadfile function
private static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("FileNotFoundException",e+"");
return;
} catch (IOException e) {
Log.e("IOException",e+"");
return;
}
}
//install apk file function
private void installApk(){
Intent installer = new Intent();
installer.setAction(android.content.Intent.ACTION_VIEW);
installer.putExtra(Intent.ACTION_PACKAGE_REPLACED, "org.wannatrak.android");
installer.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "yourapp.apk")), "application/vnd.android.package-archive");
installer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(installer);
}
I am generating an android application which capable to include over-the-air updation in the android application. So that I am generating a Webservice for getting the versioncode so that I will compare the versioncode of installed application if it is lesser then I will trigger there is an update to install from the server, for this I using below code.
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "yourapp.apk");
downloadFile(file_url, outputFile);
installApk();
//downloadfile function
private static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("FileNotFoundException",e+"");
return;
} catch (IOException e) {
Log.e("IOException",e+"");
return;
}
}
//install apk file function
private void installApk(){
Intent installer = new Intent();
installer.setAction(android.content.Intent.ACTION_VIEW);
installer.putExtra(Intent.ACTION_PACKAGE_REPLACED, "org.wannatrak.android");
installer.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "yourapp.apk")), "application/vnd.android.package-archive");
installer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(installer);
}
The above works well upto 4.0 versions.If i try it in the jelly bean I am getting "There is a parse error in a package error" Please help me to solve this issues
Thanks.

You need to give read permission to your apk file. In the install apk file function, add:
File file = new File(Environment.getExternalStorageDirectory() + "/download/" + "yourapp.apk")
file.setReadable(true, false);
installer.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");

Related

How to encrypt and decrypt a pdf/doc file in Android

I am new to Android, and I am trying to encrypt and decrypt a file and want to display in Android device after decrypt.
Here I am downloading the file from the URL and storing in SD card and I don't now how to encrypt the file and then store in SD card and file size may be more then 20MB.
Code:
File downloadFile(String dwnload_file_path) {
File file = null;
try {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "SampleFolder");
folder.mkdir();
file = new File(folder, dest_file_path);
try{
file.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
URL url = new URL(dwnload_file_path);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(file);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
//ToastManager.toast(this, "Download Complete. Open PDF Application installed in the device.");
} catch (final MalformedURLException e) {
//ToastManager.toast(this, "Some error occured. Press try again.");
} catch (final IOException e) {
//ToastManager.toast(this, "Some error occured. Press try again.");
} catch (final Exception e) {
//ToastManager.toast(this, "Failed to download image. Please check your internet connection.");
}
return file;
}
Here I am displaying the file in Android device but after decrypting the file, how can I display it?
Code:
File pdfFile = new File(Environment.getExternalStorageDirectory() + "/SampleFolder/" + "Sample."pref.getString(Constants.PrefConstants.PATH_NAME));
File f = new File(pdfFile.toString());
if(f.exists()) {
Uri path = Uri.fromFile(pdfFile);
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, pref.getString(Constants.PrefConstants.PATH_NAME_APP));
//pdfIntent.setFlags(Intent. FLAG_ACTIVITY_CLEAR_TOP);
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(pdfIntent);
} else {
//uiManager.execute(Constants.Commands.REQGET_INSTRUCTIONS_SCREEN,null);
ToastManager.toast(getApplicationContext(), "No data available...");
}
How can I resolve this issue?
You need to use the SecretKeySpec library .
Example of encrypt method
static void encrypt() throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
// Here you read the cleartext.
FileInputStream fis = new FileInputStream("SampleFolder/yourfilename");
// This stream write the encrypted text. This stream will be wrapped by another stream.
FileOutputStream fos = new FileOutputStream("SampleFolder/yourencryptedfilename");
// Length is 16 byte
// Careful when taking user input!!! https://stackoverflow.com/a/3452620/1188357
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), "AES");
// Create cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sks);
// Wrap the output stream
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
// Write bytes
int b;
byte[] d = new byte[8];
while((b = fis.read(d)) != -1) {
cos.write(d, 0, b);
}
// Flush and close streams.
cos.flush();
cos.close();
fis.close();
}
For decrypt method see the link below.
More details : How to encrypt file from SD card using AES in Android?

video download from google+/picasa android

We have a requirement to download video from google+/picasa and store it into sdcard.
Can you please any one help me to solve this issue?
google+/picasa
Converting from URI to byte[], then byte[] is stored to file:
InputStream videoStream = getActivity().getContentResolver().openInputStream(videoUri);
byte bytes[] = ByteStreams.toByteArray(videoStream );
videoFile = new File("abcd.mp4");
FileOutputStream out = new FileOutputStream(videoFile);
out.write(bytes);
out.close();
Can you try that one :
public String DownloadFromUrl(String DownloadUrl, String fileName) {
File SDCardRoot = null;
try {
SDCardRoot = Environment.getExternalStorageDirectory();
File files = new File(SDCardRoot+fileName);
int sizeoffile;
if(!files.exists())
{
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath());
if(dir.exists()==false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl);
File file = new File(dir, fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
sizeoffile = ucon.getContentLength();
Log.d("SIZEOFFILE: ", sizeoffile+" BYTE");
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
}
}
catch (IOException e) {
e.getMessage();
}
return SDCardRoot+fileName; }
Finally i found the solution.
Uri videoUri = data.getData();
File videoFile = null;
final InputStream imageStream;
try {
imageStream = getActivity().getContentResolver().openInputStream(videoUri);
byte bytes[] = ByteStreams.toByteArray(imageStream);//IStoByteArray(imageStream);
videoFile = new File(Environment.getExternalStorageDirectory()+ "/"+System.currentTimeMillis()+".mp4");
videoFile.createNewFile();
FileOutputStream out = new FileOutputStream(videoFile);
out.write(bytes);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (Exception ee){
ee.printStackTrace();
}
I have recently encountered this.
I first discovered that what I'm receiving is a picture rather than a video.
But I didn't understand why Facebook is successfully playing the online video I shared via (Google+'s) Photo.
I then occasionally discovered that the file they're currently giving is a GIF with the original extension in the MediaStore.Images.Media.DISPLAY_NAME section of the contentUri.
Eeek!

How to download and automatic install apk from url in android

I'm trying to programmatically download an .apk file from a given URL and then install it, but I am getting a FileNotFoundException. What could be a possible reason for the issue?
try {
URL url = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = "/mnt/sdcard/Download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "VersionUpdate.apk");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
**//Getting error in this line**
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.flush();
fos.close();
is.close();
} catch (Exception e) {
Log.e("UpdateAPP", "Update error! " + e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String unused) {
//dismiss the dialog after the file was downloaded
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.parse("file:///sdcard/download/VersionUpdate.apk"),"application/vnd.android.package-archive");
startActivity(intent);
}
You just replaced by InputStream is = c.getInputStream(); to given code.
InputStream is ;
int status = c.getResponseCode();
if (status != HttpURLConnection.HTTP_OK)
is = c.getErrorStream();
else
is = c.getInputStream();
Try the following code
File outputFile = new File(file, "VersionUpdate.apk");
if(!outputFile.exists())
{
outputFile.createNewFile();
}
What you are doing is deleting the file, when it already exist, then FileOutputStream will not get file where you want to download the apk .
If the file already exist, FileOutputStream will override the content with new update.
If you have queries, do ask!!

How to I write to the external storage from an Android app?

I'm trying to write some code to stream a file from a server directly into the Android external storage system.
private void streamPDFFileToStorage() {
try {
String downloadURL = pdfInfo.getFileServerURL();
URL url = new URL(downloadURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream pdfFileInputStream = new BufferedInputStream(httpURLConnection.getInputStream());
File pdfFile = preparePDFFilePath();
OutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(pdfFile));
byte[] buffer = new byte[8012];
int bytesRead;
while ((bytesRead = pdfFileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private File preparePDFFilePath() {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "filename");
return file;
/*
String pdfFileDirectoryPath = ApplicationDefaults.sharedInstance().getFileStorageLocation() + pdfInfo.getCategoryID();
File pdfFileDirectory = new File(pdfFileDirectoryPath);
pdfFileDirectory.mkdirs();
return pdfFileDirectoryPath + "/ikevin" + ".pdf";
*/
}
It keeps getting an exception of "No such file or directory" at
"OutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(pdfFile));"
How do I write the file? What's wrong with my code? (Also, I am not using Context.getExternalFilesDir() because I don't know how to get the Context from my controller logic code. Can anyone advise if this is the better solution?)
new File is returning you a file object and not the file. You might wana create a file before opening a stream to it. Try this
File pdfFile = preparePDFFilePath();
boolean isCreated = pdfFile.createNewFile();
if(isCreated){
OutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(pdfFile));
}
This code works:
String root = Environment.getExternalStorageDirectory().toString();
File dir = new File(root + "/dir1");
dir.mkdirs();

Android: downloaded file size less than its actual size

I want to update my application automatically
This is the code i am using
public void Update(String apkurl){
try {
URL url = new URL(apkurl);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "DeliverReceipt.apk");
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();//till here, it works fine - .apk is download to my sdcard in download file
/*Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/apk/" + "DeliverReceipt.apk")), "application/vnd.android.package-archive");
startActivity(intent); //installation is not working
*/
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Update error!", Toast.LENGTH_LONG).show();
}
}
The downloaded file is just 20kb size, which is less than the original
how can i solve this problem?
thank you
*noted : if i try this url in browser it's work, an apk can be downloaded
You should probably flush before you close the file, using fos.flush()

Categories

Resources