Run apk from inside android application - android

I am thinking if there is a way to run an apk file and start the installation procedure from inside an already installed application.
I know that the following code opens an apk file:
File apkFile = new File(path + file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(apkFile),"application/vnd.android.package-archive");
startActivity(intent);
but how can I find the apk(path) when it is for example inside the resources folder of the application's folder? Could this be done?

It would depend on whether you have your phone rooted or not, but assuming it isn't, you can put your apk file inside raw folder, open it and then run that intent. It should look something like this:
File tempFile = Utils.openResourceFile(context, R.raw.yourapk, "yourapkname.apk");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(tempFile),"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Utils.java
public static File openResourceFile(Context context, int resFile, String tempFileName) throws IOException{
InputStream in = context.getResources().openRawResource(resFile);
byte[] b = new byte[in.available()];
in.read(b);
FileOutputStream fout = context.openFileOutput(tempFileName, Context.MODE_WORLD_READABLE);
fout.write(b);
fout.close();
in.close();
return context.getFileStreamPath(tempFileName);
}

Related

Android - Display PDF from server

Trying to display a PDF received from server but getting "Media not found error"
First I convert String to byte array:
byte[] data = Base64.decode(stringData, Base64.DEFAULT);
Then I write the byte[] to a file:
String path = getFilesDir() + "/myfile.pdf";
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream stream = new FileOutputStream(file);
stream.write(article.getFileDataBytes());
stream.close();
Then I try to display PDF:
Uri path2 = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path2, "application/pdf");
startActivity(intent);
But after calling startActivity I receive the "Media not found error"
I'm not sure what's wrong no exceptions are thrown when writing the file
You are writing the file to internal storage. No third-party apps have access to your internal storage directly. Use FileProvider to make the PDF available to third-party apps.
This sample app does pretty much what you need, except that I get the starting PDF from an asset.

Android Reading PDF files from asstes folder

I have list of PDF files need to Place in asstes folder,my requirement is to read files from asstes and display it inside a listview.
if we click on each list item need to read respective PDF file
I have followed this blog http://androidcodeexamples.blogspot.in/2013/03/how-to-read-pdf-files-in-android.html
But here they have given reading a PDF files from External Storage Directory
I want to implement the same reading files from Asstes Folder
Could any one help How to implement the same example reading files from asstes?
You cannot open the pdf file directly from the assets folder.You first have to write the file to sd card from assets folder and then read it from sd card.
Try out the below code to copy and read the file from assets folder:
//method to write the PDFs file to sd card
private void PDFFileCopyandReadAssets()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "test.pdf");
try
{
in = assetManager.open("test.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
readFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/test.pdf"),
"application/pdf");
startActivity(intent);
}
private void readFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
Open the file from sdcard as below:
File file = new File("/sdcard/test.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Also provide a permission to write into your external storage in your manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Writing File in External SD card in android

I have tried so many ways to write file in external as card but not working. Please suggest me what to do.
The code snippet that I wrote is as follows:
final String directoryFile = "file:///"+"mnt/extsd/Test";
String filename = "TextData.txt";
Context context;
//String file=Environment.getExternalStorageDirectory()+ "/TextData.txt";
//String file = "mnt/extsd/TextData.txt";
//String file=Environment.getExternalStorageDirectory()+ "/RudimentContent/test.txt";
//File root = android.os.Environment.getExternalStorageDirectory();
//File dir = new File (root.getAbsolutePath() + "/download");
//File path = Environment.getExternalStorageDirectory();
//String filename = "TextData.txt";
//String fileName = "TextData.txt";
//String path = "Environment.getExternalStorageDirectory()/TextData.txt";
//File path = Environment.getExternalStorageDirectory();
public void onClick(View v)
{
// write on SD card file data in the text box
// dir.mkdirs();
//File file = new File(dir, "myData.txt");
//String fileName = surveyName + ".csv";
//String headings = "Hello, world!";
//File file = new File(path, fileName);
//path.mkdirs();
//OutputStream os = new FileOutputStream(file);
//os.write(headings.getBytes());
//create path
//create file
//File outFile = new File(Environment.getExternalStorageDirectory(), filename);
//File directoryFile = new File("mnt/extsd", "Test");
//directoryFile.mkdirs();
//create file
//File file = new File(Environment.getExternalStorageDirectory(), filename);
try{
File myFile = new File(directoryFile, filename); //device.txt
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing SD "+myFile.getPath(),Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
I have commented on so may tried codes also. When I write in internal sd card then its working but not with external. Please suggest.
I had this before.
The reason you're having this exception is due to some bizarre ways the framework handles files and folders.
on my case was that I was testing, and all was working, and I deleted the testing folder and since then the system keeps trying to write on the deleted folder. I removed the project from the phone and reboot it and started working again.
furthermore, I suggest you a quick reading on this answer What is the best way to create temporary files on Android? and the comments of this answer... as there is a lot of useful information if you want to create a good app.
just set permission like this
android.permission.WRITE_EXTERNAL_STORAGE
If you're using API Level 8 or greater, use getExternalFilesDir() to open a File that represents the external storage directory where you should save your files. This method takes a type parameter that specifies the type of subdirectory you want, such as DIRECTORY_MUSIC and DIRECTORY_RINGTONES (pass null to receive the root of your application's file directory).
This method will create the appropriate directory if necessary.
If you're using API Level 7 or lower, use getExternalStorageDirectory(), to open a File representing the root of the external storage. You should then write your data in the following directory:
/Android/data//files/
You will have to set the permissions too:
android.permission.WRITE_EXTERNAL_STORAGE
try this
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
and add this in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
EDIT: By using this line you can able to see stores images in the gallery view.
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));

Android - Share file from sd using bluetooth

Im trying to send a file from my SD using Bluetooth. I'm using Share intent, I wanna send a file from my SD (.mp3). ok when I open the share menu, I can send file to email, dropbox, whatsapp, but if I select Bluetooth, My device shows a message "File null was not sent to ..."
My steps are:
1. Create SEND intent.
2. Copy my file from res/raw to SD
3. Add my file to putExtra
4. Delete the file (is temporal file)
The code:
Intent shareIntent=new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("audio/mp3");
//Copiamos archivo a compartir en la sd
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = sonidoActual+"-temp.mp3";
File newSoundFile = new File(baseDir, fileName);
try {
byte[] readData = new byte[1024*500];
InputStream fis = getResources().openRawResource(contexto.getResources().getIdentifier(sonidoActual,"raw", contexto.getPackageName()));
FileOutputStream fos = new FileOutputStream(newSoundFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
////
shareIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse(newSoundFile.getAbsolutePath())/*Uri.parse("file:///sdcard/"+fileName)*//*Uri.parse("android.resource://com.genaut.instantbuttonsfreak/raw/"+texto)*/);
startActivity(Intent.createChooser(shareIntent,getString(R.string.share)));
//
newSoundFile.delete();
Anybody can help me with this? I read a lot but not found a working method, sorry my english.
I think your file is not release by File-I/O.
SO.. try flush() the FileOutPutStream.. like,
fos.flush();
fos.close();
then, use Uri.fromFile(File file) for uri to pass with Intent.. But before passing Uri to Intent just check whether file is exist or not..
like,
if(newSoundFile.exist())
{
shareIntent.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(newSoundFile))
startActivity(Intent.createChooser(shareIntent,getString(R.string.share)));
newSoundFile.delete();
}

Show PDF in Android

In my onCreate() I do this check:
//
// check if we have a PDF viewer, else bad things happen
//
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("application/pdf");
List<ResolveInfo> intents = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (intents == null || intents.size() == 0) {
// display message then...
finish();
}
On my HTC Desire, this doesn't return a match, even though I have Adobe's PDF viewer. An answer to this question android: open a pdf from my app using the built in pdf viewer mentions that Adobe may not have any public Intents, so the above check will obviously return nothing.
Can anyone verify whether you should be able launch Acrobat from an intent, or is there some other method or PDF viewer to use.
The actual use case is downloading copies of invoices and storing them on local storage using code such as:
URL url = new URL(data);
InputStream myInput = url.openConnection().getInputStream();
FileOutputStream fos = openFileOutput(fname, Context.MODE_WORLD_READABLE);
// transfer bytes from the input file to the output file
byte[] buffer = new byte[8192];
int length;
while ((length = myInput.read(buffer)) > 0) {
fos.write(buffer, 0, length);
progressDialog.setProgress(i++);
}
fos.close();
and then to show
// read from disk, and call intent
openFileInput(fname); // will throw FileNotFoundException
File dir = getFilesDir(); // where files are stored
File file = new File(dir, fname); // new file with our name
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file));
intent.setType("application/pdf");
startActivity(intent);
Connect your phone to you PC, start Eclipse and open the LogCat. Then download a PDF file with the browser and open it. You should see a line such as (I used the HTC desire):
09-14 17:45:58.152: INFO/ActivityManager(79): Starting activity: Intent { act=android.intent.action.VIEW dat=file:///sdcard/download/FILENAME.pdf typ=application/pdf flg=0x4000000 cmp=com.htc.pdfreader/.ActPDFReader }
Have a go with an explicit intent using the component information. Docs say here:
>
component -- Specifies an explicit name of a component class to use for the intent. Normally this is determined by looking at the other information in the intent (the action, data/type, and categories) and matching that with a component that can handle it. If this attribute is set then none of the evaluation is performed, and this component is used exactly as is. By specifying this attribute, all of the other Intent attributes become optional.
Downside is you will be bound to the htc reader. But you could try an implicit intent first and if that fails try the explicit intent as a fallback.
-Copy the following code in your activity. Call the function CopyReadAssets("File_name.pdf") from onCreate() function. Place the File_name.pdf file in assets folder.
private void CopyReadAssets(String pdfname)
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), pdfname);
try
{
in = assetManager.open(pdfname);
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Toast.makeText(getApplicationContext(), "Pdf Viewer not installed", Toast.LENGTH_SHORT).show();
}
try
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/"+pdfname),
"application/pdf");
startActivity(intent);
}catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), "Pdf Viewer not installed" ,Toast.LENGTH_SHORT).show();
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}

Categories

Resources