1

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.

Shivam Kumar
  • 1,892
  • 2
  • 21
  • 33
  • This type of error might occur if min sdk version of apk is higher than your device, Please check https://stackoverflow.com/questions/1492401/parse-error-there-is-a-problem-parsing-the-package-while-installing-android and https://stackoverflow.com/questions/21808188/error-parsing-the-package-while-installing-apk for reference – Manohar Jun 09 '17 at 05:34
  • android { compileSdkVersion 25 buildToolsVersion "25.0.2" defaultConfig { applicationId "com.vrvirtual.lionservices" minSdkVersion 15 targetSdkVersion 25 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } – Shivam Kumar Jun 09 '17 at 05:59
  • @Redman I used minSdkVersion 15 – Shivam Kumar Jun 09 '17 at 06:02
  • no of your app, but of the app which you are trying to install – Manohar Jun 09 '17 at 06:05
  • Yes sure minSdkVersion is same in both apk only versionName & versionCode are updated. – Shivam Kumar Jun 09 '17 at 06:10
  • see this answer https://stackoverflow.com/a/1501361/6478047 – Manohar Jun 09 '17 at 06:11
  • @Redman I follow your given link but I got same error while installing apk Parse Error There was a problem while parsing the package. – Shivam Kumar Jun 09 '17 at 08:47
  • Sorry bro thats the best i can help, i dont know any other reasons which causes this error – Manohar Jun 09 '17 at 08:50
  • @ShivamKumar; have you fixed this issue? similar pakcage parsing error while installing apk from code for devices above nougat. – GvSharma Mar 30 '18 at 11:51
  • @GvSharma No Dear, I can't resolved this issue, Can you resolve this issue in below nouget – Shivam Kumar Mar 30 '18 at 12:00
  • yes, i fixed this issue in all versions below and above versions Android-N – GvSharma Apr 01 '18 at 05:03
  • @GvSharma can you suggest me how to resolve this – Shivam Kumar Apr 02 '18 at 04:43

1 Answers1

0

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);
GvSharma
  • 2,632
  • 1
  • 24
  • 30