Use same method for all option menu in whole Application Android - android

I have 10 to 12 Activity, All Activity has Help Menu as an Option Menu.
I am succeed with following code to create it and showing help on click of them.
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(cacheDir, "HELP.pdf")),"application/pdf");
context.startActivity(intent);
But I want to Reduce this code for all Activity, and for that i have created one class and make one method but still i want to reduce code.
I have searched and found that onClick attribute is available in OptionMenu but I didn't get how to use it.
Please Help..

Create a class, for example call it Helper, where you put a method called handleMenu(int id) and where you do all the work. Then, in every activity you call that method from onOptionsItemSelected(), passing the id of the item selected.

I have created following Class for openFile:
public class OpenHelpFile {
File cacheDir;
Context context;
/* Constructor */
public OpenHelpFile(Context context) {
this.context = context;
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), "OOPS");
else
cacheDir = context.getCacheDir();
if (!cacheDir.exists())
cacheDir.mkdirs();
try {
File helpFile = new File(cacheDir, "OOPS.pdf");
if (!helpFile.exists()) {
InputStream in = context.getAssets().open("OOPS.pdf");
OutputStream out = new FileOutputStream(helpFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.d(TAG, "File Copied...");
}
Log.d(TAG, "File exist...");
} catch (FileNotFoundException ex) {
Log.d(TAG, ex.getMessage() + " in the specified directory.");
System.exit(0);
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
}
public void openHelpFile() {
/* OPEN PDF File in Viewer */
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(cacheDir, "OOPS.pdf")), "application/pdf");
context.startActivity(intent);
}
}
and I have call it from every OptionMenu like this:
new OpenHelpFile(context).openHelpFile();

Related

How to download apk in internal storage from URL then install automatically in android?

This is my code.
mUpdateNowView is a button and it's onClick method I download & update APK automatically.
I got an error while installing apk Parse Error
There was a problem while parsing the package.
How can I resolve this error
mUpdateNowView.setOnClickListener(updateNow);
public View.OnClickListener updateNow = new View.OnClickListener() {
public void onClick(View v) {
try {
ProgressDialog progress;
InstallAPK downloadAndInstall = new InstallAPK();
progress = new ProgressDialog(SplashActivity.this);
progress.setCancelable(false);
progress.setMessage("Downloading...");
downloadAndInstall.setContext(getApplicationContext(), progress);
downloadAndInstall.execute("http://APK_URL.apk");
} catch (Exception e) {
}
}
};
This is my InstallAPK class, This class is used for downloading apk in Internal storage and install apk automatically.
public class InstallAPK extends AsyncTask<String, Void, Void> {
private ProgressDialog progressDialog;
private int status = 0;
private Context context;
public void setContext(Context context, ProgressDialog progress) {
this.context = context;
this.progressDialog = progress;
}
public void onPreExecute() {
progressDialog.show();
}
#Override
protected Void doInBackground(String... arg0) {
try {
URL url = new URL(arg0[0]);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File myDir = new File(directory, "Android/data/MyAPK");
myDir.mkdirs();
File outputFile = new File(myDir, "MyAPK.apk");
if (outputFile.exists()) {
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is ;
int status = c.getResponseCode();
if (status != HttpURLConnection.HTTP_OK)
is = c.getErrorStream();
else
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();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(directory, "Android/data/MyAPK/MyAPK.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} catch (FileNotFoundException fnfe) {
status = 1;
Log.e("File", "FileNotFoundException! " + fnfe);
} catch (Exception e) {
Log.e("UpdateAPP", "Exception " + e);
}
return null;
}
public void onPostExecute(Void unused) {
progressDialog.dismiss();
if (status == 1)
Toast.makeText(context, "MyAPK Not Available", Toast.LENGTH_LONG).show();
}
}
Please help me.
Thanks in advance.
Here are the possible reasons behind this issue.
1. Could be renaming the apk file.
2. Could be that apk file downloaded but while installing you are not referring correct path in finder.
3. Could be that the file gets corrupted and there are other reasons as well.
In my case, i am running the app in devices having nougat and above, it is because i picked apk file but before using fileProvider; i forgot to add xml file and changes to manifest file
Here is what i did.
Step-1: FileProvider is a special subclass of ContentProvider which allows us to securely share file through a content:// URI instead of file:/// one.
<manifest>
...
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="#string/file_provider_authority"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_provider_paths" />
</provider>
...
</application>
</manifest>
Step-2:
Here set android:exported to false because we don’t need it to be public, android:grantUriPermissions to true because it will grant temporary access to files and android:authorities to a domain you control, so if your domain is com.quiro.fileproviderexample then you can use something like com.quiro.fileproviderexample.provider. The authority of a provider should be unique and that’s the reason why we are using our application ID plus something like .fileprovider:
<string name="file_provider_authority"
translatable="false">com.test.fileproviderexample.fileprovider</string>
Step3:
Create the file_provider_path in the res/xml folder. That’s the file which defines the folders which contain the files you will be allowed to share safely.
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external_files" path="." />
</paths>
Instead of using Uri.fromFile(file) we create our URI with FileProvider.getUriForFile(context, string, file) which will generate a new content:// URI with the authority defined pointing to the file we passed in.
(got inspired from this article)
code:
Uri apkURI = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
File apkFile = new File(Environment.getExternalStorageDirectory() + "/apks/test.apk");
apkURI = FileProvider.getUriForFile(mContext,
BuildConfig.APPLICATION_ID + ".provider",
apkFile);
}
else
{
apkUri = Uri.Fromfile(apkFile);
}
Intent intent = new Intent(Intent.VIEW);
intent.setData(apkURI);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
mContext.startActivity(intent);

Open pdf file url which is stored in Firebase storage

I have uploaded a Pdf file to firebase storage, after uploading the pdf file to firebase storage, I am getting the download url. Now I want to open the pdf file from this download url in my application.
Below is the url I am getting after uploading the pdf file to firebase storage.
https://firebasestorage.googleapis.com/v0/b/realtime-chat-46f4c.appspot.com/o/documents%2Fbf307aa5-79ae-4532-8128-ee394537b357.pdf?alt=media&token=2d0c5329-4717-4adc-9418-6614913e5bfa
Now I want to open an intent to view this pdf file, I've used the below code for this :
String url = "https://firebasestorage.googleapis.com/v0/b/realtime-chat-46f4c.appspot.com/o/documents%2Fbf307aa5-79ae-4532-8128-ee394537b357.pdf?alt=media&token=2d0c5329-4717-4adc-9418-6614913e5bfa";
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "application/pdf");
startActivity(Intent.createChooser(intent, "Choose an Application:"));
My phone is having applications which can open this pdf file, still it says there are no applications installed to view this file.
If I convert this url in File and use the below code, then the chooser of applications get opened but it gives error that the file can't be opened.
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
File file = new File(name);
intent.setDataAndType(Uri.fromFile(file), "aplication/pdf");
I've seen many answers that says first download the file and then open it, but I don't want to download the file, I just want to view it.
Please help me if anyone have any idea about this.
Thanks a lot in advanced.
You should use the Intent Chooser
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Intent newIntent = Intent.createChooser(intent, "Open File");
try {
startActivity(newIntent);
} catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
Your phone is not detecting the PDF because the URL you are using is a String object and not a PDF object. Technically, it should never open from the phone as PDF unless you download the PDF. PDF viewers on a phone only get activated once the Android OS tells them that it has a valid PDF file. Please take a look at source code of any of the PDF libraries to understand this better -> https://android-arsenal.com/tag/72?sort=created
However, to answer your problem, you should try opening your URL as a URL. It will activate the browser on your phone which in turn will detect that it needs a PDF reader and will activate the appropriate reader.
Something like
String url = "https://firebasestorage.googleapis.com/v0/b/realtime-chat-46f4c.appspot.com/o/documents%2Fbf307aa5-79ae-4532-8128-ee394537b357.pdf?alt=media&token=2d0c5329-4717-4adc-9418-6614913e5bfa";
public void openWebPage(String url) {
Uri webpage = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
However, I am thinking that you want to just validate if the file got uploaded successfully. And if there is a local copy on the phone then just open the local copy instead of downloading another copy. If that is the case, then I recommend using file metadata to achieve that. Something like:
// Create file metadata including the content type
StorageMetadata metadata = new StorageMetadata.Builder()
        .setCustomMetadata("myPDFfile", "localPDFfileName")
        .build();
// Upload the file and metadata
uploadTask = storageRef.child("pdf/localPDFfileName.pdf").putFile(file, metadata);
And on your success listener, retrieve the file metadata. If it is downloaded and looks complete, then open the PDF from your local phone storage. If not, then try downloading from the downloadURL as I mention at the start of the post. That should cover the validations you are trying to do.
Do elaborate more if I did not understand your problem, correctly. I will pick it up and amend my reply accordingly.
Please add following files/method to your project
PdfDownloader.java
PDFDownloaderAsyncTask.java
and then using following method handleViewPdf to view pdf:
private void handleViewPdf () {
File folder = getAppDirectory(context);
String fileName = "test.pdf";// getPdfFileName(pdfUrl);
File pdfFile = new File(folder, fileName);
if (pdfFile.exists () && pdfFile.length () > 0) {
openPDFFile (context, Uri.fromFile(pdfFile));
}
else {
if (pdfFile.length () == 0) {
pdfFile.delete ();
}
try {
pdfFile.createNewFile ();
}
catch (IOException e) {
e.printStackTrace ();
}
ArrayList<String> fileNameAndURL = new ArrayList<> ();
fileNameAndURL.add (pdfFile.toString ());
fileNameAndURL.add (pdfUrl);
fileNameAndURL.add (fileName);
if (pdfDownloaderAsyncTask == null) {
pdfDownloaderAsyncTask = new PDFDownloaderAsyncTask (context, pdfFile);
}
if (hasInternetConnection (context)) {
if (!pdfDownloaderAsyncTask.isDownloadingPdf ()) {
pdfDownloaderAsyncTask = new PDFDownloaderAsyncTask (context, pdfFile);
pdfDownloaderAsyncTask.execute (fileNameAndURL);
}
}
else {
//show error
}
}
}
PDFDownloaderAsyncTask.java
import java.io.File;
import java.util.ArrayList;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.Toast;
public class PDFDownloaderAsyncTask extends AsyncTask<ArrayList<String>, Void, String> {
private boolean isDownloadingPdf = false;
private File file;
private Context context;
public PDFDownloaderAsyncTask (Context context, File file) {
this.file = file;
this.context = context;
this.isDownloadingPdf = false;
}
public boolean isDownloadingPdf () {
return this.isDownloadingPdf;
}
#Override
protected void onPreExecute () {
super.onPreExecute ();
//show loader etc
}
#Override
protected String doInBackground (ArrayList<String>... params) {
isDownloadingPdf = true;
File file = new File (params[0].get (0));
String fileStatus = PdfDownloader.downloadFile (params[0].get (1), file);
return fileStatus;
}
#Override
protected void onPostExecute (String result) {
super.onPostExecute (result);
Loader.hideLoader ();
if (!TextUtils.isEmpty (result) && result.equalsIgnoreCase (context.getString (R.string.txt_success))) {
showPdf ();
}
else {
isDownloadingPdf = false;
Toast.makeText (context, context.getString (R.string.error_could_not_download_pdf), Toast.LENGTH_LONG).show ();
file.delete ();
}
}
#Override
protected void onCancelled () {
isDownloadingPdf = false;
super.onCancelled ();
//Loader.hideLoader ();
}
#Override
protected void onCancelled (String s) {
isDownloadingPdf = false;
super.onCancelled (s);
//Loader.hideLoader ();
}
private void showPdf () {
new Handler ().postDelayed (new Runnable () {
#Override
public void run () {
isDownloadingPdf = false;
openPDFFile (context, Uri.fromFile (file));
}
}, 1000);
}
}
PdfDownloader.java
package com.pdf;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class PdfDownloader {
private static final int MEGABYTE = 1024 * 1024;
public static String downloadFile (String fileUrl, File directory) {
String downloadStatus;
try {
URL url = new URL (fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection ();
urlConnection.connect ();
InputStream inputStream = urlConnection.getInputStream ();
FileOutputStream fileOutputStream = new FileOutputStream (directory);
int totalSize = urlConnection.getContentLength ();
Log.d ("PDF", "Total size: " + totalSize);
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while ((bufferLength = inputStream.read (buffer)) > 0) {
fileOutputStream.write (buffer, 0, bufferLength);
}
downloadStatus = "success";
fileOutputStream.close ();
}
catch (FileNotFoundException e) {
downloadStatus = "FileNotFoundException";
e.printStackTrace ();
}
catch (MalformedURLException e) {
downloadStatus = "MalformedURLException";
e.printStackTrace ();
}
catch (IOException e) {
downloadStatus = "IOException";
e.printStackTrace ();
}
Log.d ("PDF", "Download Status: " + downloadStatus);
return downloadStatus;
}
public static void openPDFFile (Context context, Uri path) {
Intent intent = new Intent (Intent.ACTION_VIEW);
intent.setDataAndType (path, "application/pdf");
intent.setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
context.startActivity (intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText (context, context.getString (R.string.txt_no_pdf_available), Toast.LENGTH_SHORT).show ();
}
Loader.hideLoader ();
}
public static File getAppDirectory (Context context) {
String extStorageDirectory = Environment.getExternalStorageDirectory ().toString ();
File folder = new File (extStorageDirectory, context.getString (R.string.app_folder_name).trim ());
if (!folder.exists ()) {
boolean success = folder.mkdirs();
Log.d ("Directory", "mkdirs():" + success);
}
return folder;
}
}
if you want to open the saved pdf file in your application rather than creating a intent to open in other application, you can use the following library to create the PdfView in Xml file. AndroidPdfViewer (this library also provides the zoom in-out facility)
After that as mentioned in the Firebase Document use the saved path reference of the file location in firebase Storage to fetch the file in Bytes and add it to your PdfView as
For example your file path will be like : "/folder1/yourfile.pdf"
pdfView = (PDFView) findViewById(R.id.pdfView);
mFirebaseStorage=FirebaseStorage.getInstance().getReference();
final long ONE_MEGABYTE = 1024 * 1024;
mFirebaseStorage.child("YourSavedFilePathRef").getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
pdfView.fromBytes(bytes).load();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this,"download unsuccessful",Toast.LENGTH_LONG).show();
}
});
Simple code :)
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri fileuri = Uri.parse("URL of file on storage") ;
intent.setDataAndType(fileuri,"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Intent in = Intent.createChooser(intent,"open file");
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(in);
Hope this works :)
try to encode your firebase database file url. it work with me
Use Webview for view pdf file-
WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
String pdf = "https://firebasestorage.googleapis.com/v0/b/realtime-chat-46f4c.appspot.com/o/documents%2Fbf307aa5-79ae-4532-8128-ee394537b357.pdf?alt=media&token=2d0c5329-4717-4adc-9418-6614913e5bfa";
webview.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);

How to view pdf from assets or raw folder?

I am using the MuPDF library to display pdf in my app..
It is possible to view PDFs saved in internal or external memories but the App doesn't show the pdf if they are stored in assets folder of the app...
How to view in app PDFs?
I've seen solutions which say thatbwe can copy our in app PDFs in app associated folder and then use them later on...
but I can't get that..
here's the code -
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button showPDFBtn = (Button)findViewById(R.id.btn_show_pdf);
showPDFBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri uri = Uri.parse("file:///android_asset/test.pdf");
Intent intent = new Intent(MainActivity.this, MuPDFActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
Try below code
private void readAssetAndMakeCopy()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "git.pdf");
try
{
in = assetManager.open("git.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(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() + "/git.pdf"),
"application/pdf");
startActivity(intent);
}
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);
}
}
Make sure to include
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in manifest

ftp file download result in black screen

I am downloading a file from ftp server. downloading code worked fine, however after download code screen doesn't show anything ,it gets black. Also download function is not returning true value, even the file is being saved in the specified directory.
public class FTPClass{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_player);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Intent intent = getIntent();
dirname = intent.getStringExtra("currentDirName");
MyFTPClient mftp = new MyFTPClient();
createPath = mftp.getAppRootPath().concat("/"+ dirname);
mftp.setCurrentDir(createPath);
System.out.println(mftp.ftpChangeDirectory(createPath));
FTPFile[] farr = mftp.ftpListAllFiles();
System.out.println(farr.length);
for(int i = 0; i<farr.length;i++){
System.out.println("SRC: "+createPath+"/"+farr[i].getName());
String src = createPath+"/"+farr[i].getName();
System.out.println("DEST: "+"/data/data/com.example.ftpplayer" + "/app_"+dirname);
String dest ="/data/data/com.example.ftpplayer" + "/app_"+dirname+"/"+farr[i].getName();
System.out.println(mftp.downloadFile(src,dest));
}
}
}
public class CallingIntent extends Activity{
System.out.println("In item click ");
Intent intent = new Intent(getApplicationContext(), FTPClass.class);
String dir = ((TextView) view).getText().toString();
intent.putExtra("currentDirName", dir);
startActivity(intent);
}
public class MyFTPClient{
public boolean downloadFile(String srcPath , String destPath){
try {
FileOutputStream fos = new FileOutputStream(destPath);
System.out.println(mftp.retrieveFile(srcPath, fos)); // retrieve file doesn't return true
fos.flush();
fos.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return false;
}
}
You need to run your code on the background thread, try using an asyncTask.

Android: BroadcastReceiver on application install / uninstall

I want to install an apk file and set a broadcast-receiver in order to catch information concerning install status.
I have prepared a BroadcastReceiver class :
public class newPackageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("DEBUG"," test for application install/uninstall");
}
}
In the main activity, I first register a new receiver object, then instanciate button for application install.
public void onCreate(Bundle savedInstanceState) {
...
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
filter.addAction(Intent.ACTION_PACKAGE_INSTALL);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
receiver = new newPackageReceiver();
registerReceiver(receiver, filter);
...
dlButton.setText(R.string.dl_button);
dlButton.setOnClickListener(new AppliDownloadOnClickListener(this ));
#Override
public void onDestroy(){
unregisterReceiver(receiver);
super.onDestroy();
}
In my OnclickListener class, i put :
#Override
public void onClick(View v) {
// actually, the below process is in an asyncTask
URL url;
Intent promptInstall;
try {
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, "app.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();
promptInstall = new Intent(Intent.ACTION_VIEW);
promptInstall.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")), "application/vnd.android.package-archive");
if (promptInstall != null) {
activity.startActivity(promptInstall);
} else {
ErrorDetails.displayToastMessage(activity,R.string.connection_error);
}
} catch (...) {
...
}
}
With the above code (I have shrunk it), when button is clicked, installer is displayed and application is perfectly installed, but receiver class(newPackageReceiver) is never called. Registering (registerReceiver) is done in the onCreate method and unregisterReceiver is called in the onDestroy method, so it shoud be valid. Do you know why ?
Thank you for reading !
You need to add the data scheme to your intent filter.
filter.addDataScheme("package");
Also, ACTION_PACKAGE_INSTALL was never in use.

Categories

Resources